text stringlengths 1 2.12k | source dict |
|---|---|
python, machine-learning
The if __name__ guard is nice.
May as well push down all these statements
so they're within def main():,
and then we're guarding just a single line which calls main().
Why?
So local variables go out of scope upon exiting main().
And so it's easy to rename to something more meaningful
as you write and write more code and then you step
back to notice what it really does once you've finished it.
Now, let's work on that data directory.
from pathlib import Path
data_dir = Path('../data').resolve()
assert data_dir.exists()
You might also consider defining a models_dir parameter.
And let's modify the preprocess signature so
we're passing in a CSV filespec.
preprocess_data(data_dir / 'movies_metadata.csv')
df = pd.read_csv(data_dir / 'processed_movies_metadata.csv')
But, wait!
The last preprocessing step was to write that out.
DRY.
Rather than evaluating the preprocessor for side effects,
returning None, it makes more sense for it to
return that processed CSV pathname.
Better still, since it already has a dataframe
of joined genres, it should simply return df
and then caller won't need to re-read a CSV.
Ok, back to the program in progress.
df = pd.read_csv(...)
df = df[['overview', 'genres']]
That's a pretty typical approach that naturally falls out
of iterative hacking, nothing wrong with it.
We read many columns and project down to just two of them.
Consider telling pandas about that up front:
df = pd.read_csv(... , usecols=['overview', 'genres'])
df.dropna(inplace=True)
Again, there's nothing super wrong with that.
But it would be
better
to get in the habit of phrasing it this way:
df = df.dropna()
I have had too many colleagues run afoul
of the dreaded SettingWithCopyWarning,
and then it takes forever to explain why
a script that ran fine for months is
suddenly not behaving as expected after
one tiny edit.
Avoid inplace -- you don't need it.
Similarly when you later drop rows with no popular genre,
and when you reset indexes. | {
"domain": "codereview.stackexchange",
"id": 44801,
"lm_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, machine-learning",
"url": null
} |
python, machine-learning
df['genres'] = ... .literal_eval) \
.apply(lambda x: [i['name'] for i in x])
Pep-8
encourages you to wrap the assigned expression within "extra"
( ) parentheses, no biggie.
The lambda is nice enough, but conventionally we name that expression
itemgetter.
X = df['overview']
This is fine.
It's worth noting that
X = df[['overview']]
would have given you a DataFrame rather than a Series.
Possibly you would then have less "reset_index" trouble.
Don't be afraid to write a one-sentence """docstring"""
for each function you define.
This code achieves its design objectives.
I would be willing to delegate or accept maintenance
tasks for this codebase. | {
"domain": "codereview.stackexchange",
"id": 44801,
"lm_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, machine-learning",
"url": null
} |
python, beginner, python-3.x, strings
Title: Automate the boring stuff with python - Comma Code
Question:
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list value as an argument and returns a
string with all the items separated by a comma and a space, with and
inserted before the last item. For example, passing the previous spam
list to the function would return 'apples, bananas, tofu, and cats'.
But your function should be able to work with any list value passed to
it.
# Function for getting user input.
def get_input():
user_input = input('Enter some random stuff: ')
return user_input
# Function for appending the input to the list
def logic_code(input, big_list):
big_list.append(input)
return big_list
# Function for printing the output
def print_output(big_list):
while True:
input = get_input()
if input == 'Done': # If user input == 'Done', break loop.
break
logic_output = logic_code(input, big_list) # Output of logic_code
output = print(logic_output)
return output
def main() -> None:
big_list = []
print('Type Done to stop.')
output = print_output(big_list)
if __name__ == '__main__': # Program starts here, then main() get's called.
main()
This was a 'simple' exercise; I had to think a bit more with everything being a function, bit it looks a lot neater.
Everything is in functions; could I have handle the user input differently?
Should int and floats be in a separate list?
Answer: The problem statement asks for
a function that takes a list value as an argument and returns a string
That's not what we have here. This requirement means our function should have the following form:
def join_strings(items: list[str]) -> str:
'''
Combine the members of "items" into a single string,
with commas between each item, and 'and' before the last.
''' | {
"domain": "codereview.stackexchange",
"id": 44802,
"lm_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, beginner, python-3.x, strings",
"url": null
} |
python, beginner, python-3.x, strings
I've used type annotations to be completely clear about the inputs and outputs. Even if you've not seen these before, I think you should be able to see how they describe this function.
We can test it manually like this:
if __name__ == '__main__':
print(join_strings(ham', 'eggs', 'sausage', 'spam']))
Or we can use doctest to embed some automated testing as examples in our documentation string:
def join_strings(items: list[str]) -> str:
'''
Combine the members of "items" into a single string,
with commas between each item, and 'and' before the last.
For example:
>>> join_strings(['Dave Dee', 'Dozy', 'Beaky', 'Mick', 'Tich'])
'Dave Dee, Dozy, Beaky, Mick, and Tich'
>>> join_strings(['ham', 'eggs', 'sausage', 'spam'])
'ham, eggs, sausage, and spam'
>>> join_strings(['fish', 'chips'])
'fish, and chips'
>>> join_strings(['soup'])
'soup'
'''
We exercise these tests by adding a couple of lines (don't worry if this looks like magic - for now, just consider it the standard incantation for self-tested code):
if __name__ == '__main__':
import doctest
doctest.testmod()
With that framework in place, I encourage you to re-write the logic so that matches the requirements. | {
"domain": "codereview.stackexchange",
"id": 44802,
"lm_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, beginner, python-3.x, strings",
"url": null
} |
c, number-systems
Title: Printing a number in binary in C
Question: I wrote a short function whose purpose is simple: Print the binary representation of number to the console. I also aim to be as portable as possible, hence my use of CHAR_BIT and + instead of | in case the character encoding for '0' happens to be odd. Is my code as good and portable as I intended?
#include <stdio.h>
#include <limits.h>
#define SIZE (sizeof(unsigned long long)*CHAR_BIT)
int putb(const unsigned long long n) {
char b[SIZE+1];
for (unsigned i = SIZE; i--; b[i^SIZE-1] = ((char)(n>>i)&1)+'0');
b[SIZE] = 0;
return puts(b);
}
Answer: The obvious portability problem is that we have b[i^SIZE-1] where I'd expect b[SIZE-1-i]. That looks like an error of judgement: it produces the same results when SIZE is an exact power of 2, but not otherwise.
Instead of the SIZE preprocessor macro, I'd probably use a constant within the function:
static const size_t length = sizeof n * CHAR_BIT;
If you do stick with the macro, consider #undef SIZE afterwards so it's available to other code.
As a style issue, I don't like the for loop with empty body on the same line. That looks more like code-golf than something that's intended to be readable - especially with the "work" of the loop stuffed into the control expression.
We really want the cast to char to happen to the sum, since char+char yields int. That said, gcc -pedantic -Wconversion doesn't complain without it.
I would write the character constant 0 as '\0' to better convey the intent. That's especially important as we have '0' close by.
You might find it easier, clearer and more efficient to work backwards from the least-significant bit:
int putb(unsigned long long n)
{
char b[(sizeof n * CHAR_BIT) + 1];
char *p = b + sizeof b;
*--p = '\0';
for (; p-- > b; n >>= 1) {
*p = '0' + (char)(n & 1);
}
return puts(b);
} | {
"domain": "codereview.stackexchange",
"id": 44803,
"lm_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, number-systems",
"url": null
} |
c, number-systems
This gives the option of a version that doesn't print leading zeros (and therefore modified to accept any size integer):
#include <stdint.h>
int putb(uintmax_t n)
{
char b[(sizeof n * CHAR_BIT) + 1];
char *p = b + sizeof b;
*--p = '\0';
do {
*--p = '0' + (n & 1);
} while (n >>= 1);
return puts(p);
}
This one is trivially modified to add a 0b prefix, should that be desired. | {
"domain": "codereview.stackexchange",
"id": 44803,
"lm_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, number-systems",
"url": null
} |
error-handling, rust
Title: Solution to the Rustlings from_into exercise
Question: I've got a working solution to the Rustlings from_into exercise (i.e. the code compiles and all the tests pass). The task required that I implemented the From trait for struct Person. I've highlighted the relevant section inline with comments below.
// The From trait is used for value-to-value conversions.
// If From is implemented correctly for a type, the Into trait should work conversely.
// You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html
#[derive(Debug)]
struct Person {
name: String,
age: usize,
}
// We implement the Default trait to use it as a fallback
// when the provided string is not convertible into a Person object
impl Default for Person {
fn default() -> Person {
Person {
name: String::from("John"),
age: 30,
}
}
}
// THE BELOW IMPLEMENTATION IS WHAT I'D LIKE INPUT ON
//
// Steps:
// 1. If the length of the provided string is 0, then return the default of Person
// 2. Split the given string on the commas present in it
// 3. Extract the first element from the split operation and use it as the name
// 4. If the name is empty, then return the default of Person
// 5. Extract the other element from the split operation and parse it into a `usize` as the age
// If while parsing the age, something goes wrong, then return the default of Person
// Otherwise, then return an instantiated Person object with the results
impl From<&str> for Person {
fn from(s: &str) -> Person {
let s_as_vec = s.split(",").collect::<Vec<&str>>();
let name = s_as_vec[0].to_string(); | {
"domain": "codereview.stackexchange",
"id": 44804,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "error-handling, rust",
"url": null
} |
error-handling, rust
if name.is_empty() {
Person::default()
} else if s_as_vec.len() > 1 {
match s.splitn(2, ",").collect::<Vec<&str>>()[1].parse::<usize>() {
Ok(age) => Person {name, age},
Err(_) => Person::default()
}
} else {
Person::default()
}
}
}
// END OF WHAT I'D LIKE INPUT ON
fn main() {
// Use the `from` function
let p1 = Person::from("Mark,20");
// Since From is implemented for Person, we should be able to use Into
let p2: Person = "Gerald,70".into();
println!("{:?}", p1);
println!("{:?}", p2);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default() {
// Test that the default person is 30 year old John
let dp = Person::default();
assert_eq!(dp.name, "John");
assert_eq!(dp.age, 30);
}
#[test]
fn test_bad_convert() {
// Test that John is returned when bad string is provided
let p = Person::from("");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_good_convert() {
// Test that "Mark,20" works
let p = Person::from("Mark,20");
assert_eq!(p.name, "Mark");
assert_eq!(p.age, 20);
}
#[test]
fn test_bad_age() {
// Test that "Mark.twenty" will return the default person due to an error in parsing age
let p = Person::from("Mark,twenty");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_comma_and_age() {
let p: Person = Person::from("Mark");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_age() {
let p: Person = Person::from("Mark,");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
} | {
"domain": "codereview.stackexchange",
"id": 44804,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "error-handling, rust",
"url": null
} |
error-handling, rust
#[test]
fn test_missing_name() {
let p: Person = Person::from(",1");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_age() {
let p: Person = Person::from(",");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_invalid_age() {
let p: Person = Person::from(",one");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
}
My primary question is: how do I make this more idiomatic? The pair of split[n]() calls seems wrong, but I'm not sure how to handle the various ways it would panic if I don't have explicit length checks.
Answer: Congratulations on your Rustlings challenge. Your code seems fine and is easy to understand, however, as you said yourself, some parts of it don't seem idiomatic yet.
However, before I begin this review, I would like to mention that I consider myself a Rust beginner with a lot more experience in other languages. Keep that in mind while you read this review (and feel free to disagree and comment!).
Use clippy
While clippy cannot work miracles, it can warn you about some lints. For example, the patterns in split are single character literals and thus should be written as ',', not ",".
Reuse what you already have
The longest line in your code is the match on parse's result:
// indentation removed for simplicity
match s.splitn(2, ",").collect::<Vec<&str>>()[1].parse::<usize>()
However, we already have s.split(...)'s result at hand. We don't need to split it a second time:
match s_as_vec[1].parse::<usize>()
If your concerned about the n in splitn then use splitn in your binding for s_as_vec. Note that the turbofish ::<usize> isn't necessary, as rustc can infer its type by the use in Person.
Use if-let when applicable
Back to the explicit length check. Instead of
if s_as_vec.len() > 1 | {
"domain": "codereview.stackexchange",
"id": 44804,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "error-handling, rust",
"url": null
} |
error-handling, rust
we can use get(1) and check whether the element exist via if let:
if let Some(age) = s_as_vec.get(1) {
match age.parse() {
Ok(age) => Person { name.to_string(), age },
Err(_) => Person::default
}
}
This also prevents us from accidentally changing one of the index locations, e.g.
if s_as_vec.len() > 2 {
match s_as_vec[3].parse() { // whoops, wrong number here
...
Defer possible heavy operations if possible
We don't need name to be a String unless we have a valid age. Therefore, we can have let name = s_as_vec[0] until we create the Person. This removes unnecessary allocations.
All remarks above applied
If we apply all remarks above, we end up with the following variant.
impl From<&str> for Person {
fn from(s: &str) -> Person {
let s_as_vec = s.splitn(2, ',').collect::<Vec<&str>>();
let name = s_as_vec[0];
if name.is_empty() {
Person::default()
} else if let Some(age) = s_as_vec.get(1) {
match age.parse() {
Ok(age) => Person {name, age},
Err(_) => Person::default()
}
} else {
Person::default()
}
}
}
However, I personally would probably try to minimize the possible return paths and use a single match expression, but that's based on my Haskell experience:
impl From<&str> for Person {
fn from(s: &str) -> Person {
let parts = s.splitn(2, ',').collect::<Vec<&str>>();
match &parts[..] {
[name, age] if !name.is_empty() => age
.parse()
.map(|age| Person {
name: name.to_string(),
age,
})
.unwrap_or_default(),
_ => Person::default(),
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44804,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "error-handling, rust",
"url": null
} |
python, recursion
Title: Test whether every element in an array is equal to sum of subsequent elements
Question: I want to ask how to improve this code. Is it well-written or should anything be changed? Please let me know. And is it a bad thing to use arguments to store some info, such as the argument value here?
Here's the problem:
Write a recursive function that will receive an array of integers as an argument and as a result will check whether the sum of the array elements after the ith element is equal to the ith element itself. If all elements meet the condition, the function returns 1, otherwise it returns 0.
Test cases
nums([16,8,4,2,1,1]) # 1 first element is 16, we skip it and then
# 8+4+2+1+1 = 16
nums([256,128,64,32,14,7,7]) # 0 first element 256, 128 + 64 + 32 + 14 + 7 + 7 its not 256 so we return 0
def list_of_numbers(nums, value=0, index=1):
if index == len(nums):
if value == nums[0]:
return 1
else:
return 0
else:
return list_of_numbers(nums, value + nums[index], index + 1)
print(list_of_numbers([16, 8, 4, 2, 1, 1])) # 1
print(list_of_numbers([256, 128, 64, 32, 14, 7, 7])) # 0 | {
"domain": "codereview.stackexchange",
"id": 44805,
"lm_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, recursion",
"url": null
} |
python, recursion
Answer: At least in most situations, if you mean true-false, don't return one-zero.
The former is more explicit, readable, and communicative. And since bool is a
subclass of int, the more explicit return values are still usable in numeric
contexts.
Handle empty sequences. Your code blows up if given an empty sequence. It
should either return None or raise an explicit ValueError.
Naming: functions do things. Although functions are things (they are
objects), their primary purpose is to do things. As a result, their names
usually involve verbs or verb-like operations. Your function name lacks that:
it has no verb, implies no operation, and tells us nothing about what the
function does (it's actually just an elaboration of the variable nums).
Granted, this function is not easy to name (I tried my best below), but even an
imperfect name conveying something about the function's behavior is better than
a bland, noun-oriented name.
Naming: when feasible, be specific. The nums and index names are clear
enough, but what is value? Rather than using a generic term like that, select
something more explicit, such as total.
Consider processing the sequence in reverse order. The function is supposed
to recurse over the sequence to compute a sum and then, at the end, return
whether that sum equals the first number in the sequence. In that context, it
seems a bit more intuitive to go in reverse order, eliminating the need to
check len(nums) repeatedly. Just stop when you hit the index of zero.
Consider using a second function to handle the recursion. The optional
arguments in your current implementation are not really part of the function's
intended API. A common technique in recursive scenarios like this is
to have two functions: (1) a top-level function for users to call, and (2) a
secondary function to handle the recursion. The first function can
handle any validations (for example, checking for empty sequences) and then | {
"domain": "codereview.stackexchange",
"id": 44805,
"lm_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, recursion",
"url": null
} |
python, recursion
handle any validations (for example, checking for empty sequences) and then
make the appropriate call to bootstrap the recursion. The second function can
be an inner function (as illustrated below) or another top-level function (use
the latter if you ever need to call the recursive function separately, for
example, for testing purposes).
def first_equals_sum_of_rest(nums): | {
"domain": "codereview.stackexchange",
"id": 44805,
"lm_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, recursion",
"url": null
} |
python, recursion
def check_seq(i, total):
n = nums[i]
if i == 0:
return n == total
else:
return check_seq(i - 1, total + n)
if nums:
return check_seq(len(nums) - 1, 0)
else:
return None
Consider generalizing the recursive behavior. This programming exercise can
be decomposed into two parts: (1) a simple equality check against the first
number, and (2) computing a sum recursively. Why not make the sum computation a
first-class citizen?
def first_equals_sum_of_rest(nums):
if nums:
return nums[0] == recursive_sum(nums, i = 1)
else:
return None
def recursive_sum(nums, i = 0, stop = None, total = 0):
stop = len(nums) if stop is None else stop
if i == stop:
return total
else:
return recursive_sum(nums, i + 1, stop, total + nums[i]) | {
"domain": "codereview.stackexchange",
"id": 44805,
"lm_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, recursion",
"url": null
} |
c++, c++11, binary-search-tree
Title: Pet Shelter in C++
Question: The provided code represents an implementation of a Binary Search Tree (BST) in C++, specifically tailored for a "Pet Shelter program" that has been the focal theme in a data structures class for an extensive period of six months.
This BST structure serves as a container for nodes that hold Pet* objects, with the utilization of pointers being mandated by the overarching project requirements.
The implemented code encompasses some fundamental methods commonly associated with a BST. These methods allow for operations such as inserting, deleting, and searching for pets based on their names within the tree and much more...
Restrictions:
Has to compile in C++ 11
No templates
Have to hold Pet pointers in the tree
Sort the Pets by name
I want to know if there is anything I could improve on, OOP, design choices, code documentation, MakeFile (I've been pasting the same one since I started working with classes), and so on. I really want to learn how to do unit tests in a better way, I think these suck but that's the way she wants us to do them. Any help or insights would be appreciated.
The code should compile by running make in the terminal, it compiles to prog and after that ./prog to run.
ShelterBST.h
/** DOCUMENTATION:
* @author Jakob Balkovec
* @file shelterBST.h -> @headerfile
* @brief ShelterBST class variables and methods declaration
*/
#ifndef SHELTERBST_H
#define SHELTERBST_H
#include <string>
#include <vector> | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
#ifndef SHELTERBST_H
#define SHELTERBST_H
#include <string>
#include <vector>
class ShelterBST {
private:
/** @struct Pet, used to store the age and the naem of a pet in a shelter */
struct Pet {
std::string name;
int age;
Pet(std::string name = "", int age = 0) : name(name), age(age) {} //Constructor
};
/** @struct TreeNode, used to implement a tree
* @members:
* Pet *pet -> pointer to a Pet object
* TreeNode *left -> left child
* TreeNode *right -> right child
*
* @note noth develop in a new subtree if left or right != NULL
*/
struct TreeNode {
struct Pet *pet;
struct TreeNode *left;
struct TreeNode *right;
};
/** @note BST base*/
struct TreeNode *root;
/** @note Methods*/
struct TreeNode* insert(struct TreeNode* &root, Pet *pet);
struct TreeNode* search(struct TreeNode* root, std::string name);
struct TreeNode* findParent(struct TreeNode* root, std::string name);
struct TreeNode* findPredecessor(struct TreeNode* root, std::string name);
struct TreeNode* deleteNode(struct TreeNode* root, std::string name);
struct TreeNode* destroyTree(struct TreeNode* root);
void searchHelper(struct TreeNode* &node1, struct TreeNode* &node2, std::string name);
void inOrder(struct TreeNode* root);
void postOrder(struct TreeNode* root);
void preOrder(struct TreeNode* root);
void copyHelper(TreeNode* root);
int numberOfChildren(struct TreeNode* root, std::string name);
int numberOfNodes(struct TreeNode* root);
int numberOfInternalNodes(struct TreeNode* root);
int numberOfNodesAtLevel(struct TreeNode* root, int level);
int findHeight(struct TreeNode* root);
bool isBalanced(struct TreeNode* root);
void findPredecessorHelper(struct TreeNode* root, std::vector<std::string> &names);
void preOrderHelper(struct TreeNode* root, std::vector<std::string> &names);
void postOrderHelper(struct TreeNode* root, std::vector<std::string> &names); | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** @note Methods END*/
/** @note tests*/
bool testSearch();
bool testSearchB();
bool testInsert();
bool testFindParent();
bool testFindPredecessor();
bool testDeleteNode();
bool testDestroyTree();
bool testNumberOfChildren();
bool testNumberOfNodes();
bool testNumberOfInternalNodes();
bool testHeight();
bool testBalance();
bool testNodesAtLevel();
bool testInOrder();
bool testPreOrder();
bool testPostOrder();
std::vector<bool> runAllTests(std::vector<bool> &testResults);
/** @note tests END*/
public:
/** @note Methods*/
ShelterBST(); //constructor
~ShelterBST(); //destructor
ShelterBST(const ShelterBST& other); //copy constructor
ShelterBST& operator=(const ShelterBST& other);
void inOrderDisplay();
void preOrderDisplay();
void postOrderDisplay();
void insertPet(std::string name, int age);
void findInorderPredecessor(std::string name);
void findParent(std::string name);
void searchPet(std::string name);
void deleteNode(std::string name);
void numberOfNodes();
void numberOfInternalNodes();
void numberOfNodesAtLevel(int level);
void findHeight();
void isBalanced();
void destroyTree();
/** @note Methods END*/
void test();
};
#endif //SHELTER_BST
ShelterBST.cpp
/** DOCUMENTATION:
*
* @author Jakob Balkovec
* @file ShelterBST.cpp [Source code]
* @brief This is the source code file for my ShelterBST class.
* Defines all the private and public methods
* @name Assignment 3
*/
#include <queue>
#include <string>
#include <iostream>
#include <vector>
#include "ShelterBST.h"
#include <unistd.h>
#include <stdexcept>
/** DOCUMENTATION:
* CONSTRUCTOR: @name ShelterBST::ShelterBST()
* @brief
*/
ShelterBST::ShelterBST() {
root = nullptr; /** @note set root to NULL*/
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* DESTRUCTOR: @name ShelterBST::~ShelterBST()
* @brief Handles the memory/ frees the resources allocated by the constructor
* @call: calls the destroyTree() method to deallocate all the memory
*/
ShelterBST::~ShelterBST() {
destroyTree(root); //call destroyTree
}
/** DOCUMENTATION:
* COPYCONSTRUCTOR: @name ShelterBST::ShelterBST(const ShelterBST& other)
* @brief Copy constructor for the ShelterBST class.
* @param other The ShelterBST object to be copied.
*/
ShelterBST::ShelterBST(const ShelterBST& other) {
root = nullptr;
copyHelper(other.root);
}
/** DOCUMENTATION:
* OPERATOR: @name ShelterBST& ShelterBST::operator=()
* @brief Copy assignment operator for the ShelterBST class.
* @param other The ShelterBST object to be copied.
* @return The copied ShelterBST object.
*/
ShelterBST& ShelterBST::operator=(const ShelterBST& other) {
if (this != &other) {
destroyTree(root);
root = nullptr;
copyHelper(other.root);
}
return *this;
}
/** DOCUMENTATON:
* PRIVATE: @name void ShelterBST::copyHelper()
* @brief Copies over all the Pets in a tree rooted at root to this tree.
* @param root Pointer to the root of the tree to be copied
*/
void ShelterBST::copyHelper(TreeNode* root) {
if (root == nullptr) {
return;
}
insertPet(root->pet->name, root->pet->age);
copyHelper(root->left);
copyHelper(root->right);
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name struct ShelterBST::TreeNode* ShelterBST::insert()
* @brief Inserts a new node with a Pet object into the binary search tree.
* @param root A pointer to the root of the binary search tree.
* @param pet A pointer to the Pet object to be inserted into the binary search tree.
* @return A pointer to the root of the binary search tree, after insertion.
* @invariant This function assumes that the Pet objects in the tree are ordered by name.
*/
struct ShelterBST::TreeNode* ShelterBST::insert(struct TreeNode*& root, Pet *pet) {
/** @note if tree is empty create a new node*/
if(root == nullptr) {
root = new TreeNode;
root -> pet = pet;
/** @note L and R are NULL if just creted*/
root -> right = nullptr;
root -> left = nullptr;
}
/** @note go left*/
else if (pet -> name < root -> pet -> name) {
root->left = insert(root->left, pet);
}
/** @note go right*/
else if (pet -> name > root -> pet -> name) {
root->right = insert(root->right, pet);
}
/** @note handle duplicates*/
/** @bug TEST:*/
else {
TreeNode* existingPet = search(root, pet -> name);
if (existingPet != nullptr) {
std::cout << "\n[A pet with this name already exists in the BST]\n";
return root;
}
}
return root;
}
/** DOCUMENTATION:
* PUBLIC: @name ShelterBST::insertPet()
* @brief Inserts a new pet into the binary search tree
* @param name Name of the pet to be inserted
* @param age Age of the pet to be inserted
* @return void-type
*/
void ShelterBST::insertPet(std::string name, int age) {
root = insert(root, new Pet(name, age));
/** @note handle memory... IN THE END*/
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name struct ShelterBST::TreeNode* ShelterBST::search()
* @brief Searches for a node with a Pet object of the given age in the binary search tree.
* @param root A pointer to the root of the binary search tree.
* @param name The name of the Pet object to search for in the binary search tree.
* @return A pointer to the node with the Pet object of the given age, or nullptr if it does not exist in the tree.
* @invariant This function assumes that the Pet objects in the tree are ordered by name.
*/
struct ShelterBST::TreeNode* ShelterBST::search(struct TreeNode* root, std::string name) {
if(root == nullptr || root -> pet -> name == name) {
return root;
}
/** @note go left if greater*/
else if(name < root -> pet -> name) {
return search(root -> left, name);
}
/** @note go right if less*/
else {
return search(root -> right, name);
}
return nullptr;
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name struct ShelterBST::TreeNode* ShelterBST::findParent()
* @brief Finds the parent node of a given node in the binary search tree
* @param root Root node of the tree
* @param name Name of the node whose parent is to be found
* @return Pointer to the parent node, or nullptr if no parent is found
* @note This function is called recursively to search for the parent of the given node
*/
/** @bug
* Returns A is the parent of B when inserted in the following order -> B, A, C
*/
struct ShelterBST::TreeNode* ShelterBST::findParent(struct TreeNode* root, std::string name) {
if(root == nullptr) {
return nullptr; /** @note no tree*/
}
if(root -> pet -> name == name) {
return root; /** @note the first node is the one we're looking for*/
/** @note return nullptr*/
}
/** @note left side using a recursive approach*/
if(name < root -> pet -> name && root -> left != nullptr) {
if(root -> left -> pet -> name == name) {
return root;
} else {
return findParent(root -> left, name);
}
/** @note right side using a recursive approach*/
}else if(name > root -> pet -> name && root -> right != nullptr) {
if(root -> right -> pet -> name == name) {
return root;
} else {
return findParent(root -> right, name);
}
}
return nullptr;
}
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::searchPet()
* @brief Searches for a pet with the given name in the binary search tree
* @param name Name of the pet to search for
* @return Pointer to the node containing the pet, or nullptr if the pet is not found
*/
void ShelterBST::searchPet(std::string name) {
TreeNode* found = search(root, name);
if(found == nullptr) {
std::cout << "\n\n[[nullptr] was returned -> A Pet with the name " << found -> pet -> name << " is [NOT] in the BST]\n\n";
} else {
std::cout << "\n[A Pet with the name \"" << found->pet->name << "\" [IS] in the BST]\n";
}
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
}
}
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::findParent()
* @brief Finds the parent node of a pet with the given name in the binary search tree
* @param name Name of the pet whose parent node is to be found
* @return Pointer to the parent node of the pet, or nullptr if the pet is not found or is the root node
*/
void ShelterBST::findParent(std::string name) {
TreeNode* parent = findParent(root, name);
if(parent == nullptr) {
std::cout << "\n[[" << name << "] does not have a parent]\n";
}
std::cout << "\n[The Parent of: [" << name << "] is [" << parent -> pet -> name << "]]\n";
}
/** DOCUMENTATION:
* PRIVATE: @name void ShelterBST::preOrderHelper()
* @brief Recursive helper function that psuhes valeus into a vector
* @param root Pointer to the root node of the current subtree
* @param names Vector of pet names representing the current subtree in in-order traversal
* @remark These functions enable testing later on
*/
void ShelterBST::preOrderHelper(struct TreeNode* root, std::vector<std::string> &names) {
if(root == nullptr) {
return;
} else if(root != nullptr) {
preOrderHelper(root -> left, names);
preOrderHelper(root -> right, names);
names.push_back(root -> pet -> name);
}
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name void ShelterBST::postOrderHelper()
* @brief Recursive helper function that psuhes valeus into a vector
* @param root Pointer to the root node of the current subtree
* @param names Vector of pet names representing the current subtree in in-order traversal
* @remark These functions enable testing later on
*/
void ShelterBST::postOrderHelper(struct TreeNode* root, std::vector<std::string> &names) {
if(root == nullptr) {
return;
} else if(root != nullptr) {
names.push_back(root -> pet -> name);
postOrderHelper(root -> left, names);
postOrderHelper(root -> right, names);
}
}
/** DOCUMENTATION:
* PRIVATE: @name void ShelterBST::findPredecessorHelper()
* @brief Recursive helper function for finding the predecessor of a pet with the given name in the binary search tree
* @param root Pointer to the root node of the current subtree
* @param names Vector of pet names representing the current subtree in in-order traversal
*/
void ShelterBST::findPredecessorHelper(struct TreeNode *root, std::vector<std::string> &names) {
/** @brief modifiying the inOrder() traversal so it pushes the values into a vector
* from there we can find the predecessor as stated in the PDF File
*/
if(root == nullptr) {
return;
} else if(root != nullptr) {
findPredecessorHelper(root -> left, names);
names.push_back(root -> pet -> name);
findPredecessorHelper(root -> right, names);
}
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name struct ShelterBST::TreeNode* ShelterBST::findPredecessor()
* @brief Finds the predecessor of a node in the BST
* @param root The root of the BST
* @param name The name of the node whose predecessor is to be found
* @return A pointer to the predecessor node in the BST
* @invariant This function assumes that the BST contains the node with the given name
*/
struct ShelterBST::TreeNode* ShelterBST::findPredecessor(struct TreeNode* root, std::string name) {
//traverse in order, push values into a vector, find predecessor
std::vector<std::string> namesInBST; /** @note empty vecotr*/
findPredecessorHelper(root, namesInBST); /** @note pushback*/
/** @note search for the predecessor*/
std::string storedName;
for(long unsigned int i = 0; i < namesInBST.size(); i++) {
if(namesInBST[0] == name) {
return nullptr; /** @note first element's predecessor in NULL*/
}
else if(namesInBST[i] == name) {
storedName = namesInBST[i-1]; /** @note segfaulting here [i-1]*/
}
}
TreeNode* preDecessorNode = search(root, storedName);
return preDecessorNode;
}
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::findInorderPredecessor()
* @brief Finds the in-order predecessor of the node with the given name.
* @param name The name of the node whose in-order predecessor is to be found.
* @return void-type
*/
void ShelterBST::findInorderPredecessor(std::string name) {
TreeNode* node = findPredecessor(root, name); /** @note change back to name*/
if(node == nullptr) {
std::cout << "\n[\"" << name << "\" does [NOT] have a predecessor]\n";
return;
} else {
std::cout << "\n[The Predecessor of [" << name << "] is: [" << node -> pet -> name << "]\n";
}
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name int ShelterBST::numberOfChildren()
* @brief Counts the number of children of a given node with the given name.
* @param root Pointer to the root node of the BST.
* @param name Name of the pet whose children are to be counted.
* @return The number of children of the node with the given name.
* @note Returns 0 if there is no tree or if the node with the given name is not found.
*/
int ShelterBST::numberOfChildren(struct TreeNode* root, std::string name) {
if(root == nullptr) {
return 0; /** @note no tree*/
}
TreeNode* node = search(root, name);
if(node == nullptr) {
/** @note node not found*/
return 0;
}
int numOfChildren = 0;
if(node -> left != nullptr) {
numOfChildren++;
}
if(node -> right != nullptr) {
numOfChildren++;
}
return numOfChildren;
}
/** DOCUMENTATION:
* PRIVATE: @name struct ShelterBST::TreeNode* ShelterBST::deleteNode()
* @brief Deletes a node with the given name from the tree
* @param root A pointer to the root of the tree.
* @param name The name of the node to delete.
* @return A pointer to the root of the updated tree.
*/
/**
* BUG: Segufaulting if I delete the predecessor before the root
*/
struct ShelterBST::TreeNode* ShelterBST::deleteNode(struct TreeNode* root, std::string name) {
/** @note find predecessor if it has 2 children*/
/** @note delete and link grandchild if only one child*/
/** @note delete if no children*/
/** @note parent is inacessible -> segafulting here*/
int const NO_CHILDREN = 0;
int const ONE_CHILD = 1;
int const TWO_CHILDREN = 2;
/** @note tree is empty*/
if(root == nullptr) {
return root;
}
TreeNode* toBeDeleted = search(root, name);
if(toBeDeleted == nullptr) {
return root; /** @note node not found*/
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
if(toBeDeleted == nullptr) {
return root; /** @note node not found*/
}
/** @note no children*/
if(numberOfChildren(root, name) == NO_CHILDREN) {
if(toBeDeleted == root) {
delete toBeDeleted;
return nullptr; //idk if thats right
}
TreeNode* parent = findParent(root, toBeDeleted -> pet -> name);
if(toBeDeleted == parent -> left) {
parent -> left = nullptr;
} else {
parent -> right = nullptr;
}
delete toBeDeleted;
}
else if(numberOfChildren(root, name) == ONE_CHILD && !toBeDeleted -> left) { /** @note != nullptr*/
if(toBeDeleted == root) {
TreeNode* temp = root -> right;
delete root;
return temp;
}
TreeNode* parent = findParent(root, toBeDeleted -> pet -> name);
if(toBeDeleted == parent -> left) {
parent -> left = toBeDeleted -> right;
} else {
parent -> right = toBeDeleted -> right;
}
delete toBeDeleted;
}
else if(numberOfChildren(root, name) == ONE_CHILD && !toBeDeleted -> right) {
if(toBeDeleted == root) {
TreeNode* temp = root -> right;
delete root;
return temp;
}
TreeNode* parent = findParent(root, toBeDeleted -> pet -> name);
if(toBeDeleted == parent -> left) {
parent -> left = toBeDeleted -> left;
} else {
parent -> right = toBeDeleted -> left;
}
delete toBeDeleted;
}
else if(numberOfChildren(root, name) == TWO_CHILDREN) {
TreeNode* predecessor = findPredecessor(root, toBeDeleted -> pet -> name);
while(predecessor -> right != nullptr) {
predecessor = predecessor -> right;
toBeDeleted -> pet -> name = predecessor -> pet -> name;
toBeDeleted -> left = deleteNode(toBeDeleted -> left, predecessor -> pet -> name);
}
}
return root;
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name struct ShelterBST::TreeNode* ShelterBST::destroyTree()
* @brief Recursively deletes all nodes in the tree.
* @return A null pointer.
* @param root Pointer to the root of the tree.
* @note This is a private member function.
*/
struct ShelterBST::TreeNode* ShelterBST::destroyTree(struct TreeNode* root) {
/** @note using recursion to delete the tree*/
/** @note base case*/
if(root == nullptr) {
return nullptr;
/** @note recursive case*/
} else {
destroyTree(root -> left);
destroyTree(root -> right);
delete root -> pet;
delete root;
return nullptr;
}
return nullptr;
}
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::deleteNode()
* @brief Deletes the node with the specified name from the BST
* @param name The name of the pet in the node to be deleted.
*/
void ShelterBST::deleteNode(std::string name) {
TreeNode* deleted = deleteNode(root, name);
if(search(root, deleted -> pet -> name) == nullptr) {
std::cout << "\nNode with the name: [" << name << "] was deleted]\n";
} else {
std::cout << "\n[Soemthing went wrong]\n";
}
}
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::destroyTree()
* @brief Calls destroy tree to destroy and deallocated the memory used by the BST
*/
void ShelterBST::destroyTree() {
root = destroyTree(root);
if(root != nullptr) {
std::cout << "\n[Something went wrong]\n";;
}
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name void ShelterBST::inOrder()
* @brief Traverses the binary search tree in-order, printing the name and age of each Pet object.
* @param root A pointer to the root of the binary search tree.
* @invariant This function assumes that the Pet objects in the tree are ordered by name.
*/
void ShelterBST::inOrder(struct TreeNode* root) {
if(root == nullptr) {
return; /** @note do nothing*/
}
/** @note traverse*/
else if(root != nullptr) {
/** @note left-sub tree*/
inOrder(root -> left);
/** @note cout data*/
std::cout << "Name: [" << root -> pet -> name << "] " << "Age: [" << root -> pet -> age << "]" << std::endl;
/** @note right sub-tree*/
inOrder(root -> right);
}
}
/** DOCUMENTATION:
* PRIVATE: @name void ShelterBST::postOrder()
* @brief Traverses the binary search tree in post-order, printing the name and age of each Pet object.
* @param root A pointer to the root of the binary search tree.
* @invariant This function assumes that the Pet objects in the tree are ordered by name.
*/
void ShelterBST::postOrder(struct TreeNode* root) {
if(root == nullptr) {
return; /** @note do nothing*/
}
else if(root != nullptr) {
/** @note left sub-tree*/
postOrder(root -> left);
/** @note right sub-tree*/
postOrder(root -> right);
/** @note cout last*/
std::cout << "Name: [" << root -> pet -> name << "] " << "Age: [" << root -> pet -> age << "]" << std::endl;
}
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name void ShelterBST::preOrder()
* @brief Traverses the binary search tree in pre-order, printing the name and age of each Pet object.
* @param root A pointer to the root of the binary search tree.
* @invariant This function assumes that the Pet objects in the tree are ordered by name.
*/
void ShelterBST::preOrder(struct TreeNode* root) {
if(root == nullptr) {
return; /** @note do nothing*/
}else if(root != nullptr){
/** @note cout first*/
std::cout << "Name: [" << root -> pet -> name << "] " << "Age: [" << root -> pet -> age << "]" << std::endl;
/** @note left sub-tree*/
postOrder(root -> left);
/** @note right sub-tree*/
postOrder(root -> right);
}
}
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::inOrderDisplay()
* @brief Displays the contents of the binary search tree using in-order traversal.
* @call: calls the corresponding private method
*/
void ShelterBST::inOrderDisplay() {
std::cout << "\n[In-Order Traversal]";
std::cout << std::endl << std::endl;
inOrder(root);
}
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::preOrderDisplay()
* @brief Displays the contents of the binary search tree using pre-order traversal.
* @call: calls the corresponding private method
*/
void ShelterBST::preOrderDisplay() {
std::cout << "\n[Pre-Order Traversal]";
std::cout << std::endl << std::endl;
preOrder(root);
}
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::postOrderDisplay()
* @brief Displays the contents of the binary search tree using post-order traversal.
* @call: calls the corresponding private method
*/
void ShelterBST::postOrderDisplay() {
std::cout << "\n[Post-Order Traversal]";
std::cout << std::endl << std::endl;
postOrder(root);
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name int ShelterBST::numberOfNodes()
* @brief Counts the number of nodes in the binary search tree rooted at the given node
* @param root A pointer to the root node of the binary search tree
* @return The number of nodes in the binary search tree rooted at the given node
* @note This is a private member function
*/
int ShelterBST::numberOfNodes(struct TreeNode* root) {
int leftSide = 0;
int rightSide = 0;
if(root == nullptr) {
return 0; /** @note tree is empty*/
}
/** @note right side*/
rightSide = numberOfNodes(root -> right);
/** @note left side*/
leftSide = numberOfNodes(root -> left);
return 1 + leftSide + rightSide; /** @note recursive function call*/
}
/** DOCUMENTATION:
* PRIVATE: @name int ShelterBST::numberOfInternalNodes()
* @brief Returns the number of internal nodes in the binary search tree.
* @param root Pointer to the root node of the tree.
* @return Integer representing the number of internal nodes in the tree.
*/
int ShelterBST::numberOfInternalNodes(struct TreeNode* root) {
if(root == nullptr || (root -> left == nullptr && root -> right == nullptr)) {
/** @note The tree doesn't exist or we reached a leaf node*/
return 0;
}
/** @note +1 cuz of root*/
return 1 + numberOfInternalNodes(root -> left) + numberOfInternalNodes(root -> right);
/** @note recursive call*/
}
/** DOCUMENTATION:
* PRIVATE: @name int ShelterBST::numberOfNodesAtLevel()
* @brief Counts the number of nodes at a given level in the binary search tree
* @param root A pointer to the root node of the binary search tree
* @param level An integer specifying the level at which to count the nodes
* @return An integer specifying the number of nodes at the given level
*/ | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** BUG:
* Do I worry about parameter checking(level) -> validation
* Idk if its working
*/
int ShelterBST::numberOfNodesAtLevel(TreeNode* root, int level) {
if (root == nullptr) {
return 0;
} else if (level == 0) {
return 1;
} else {
int count = 0;
if (root->left && root->right) {
count += numberOfNodesAtLevel(root->left, level - 1);
count += numberOfNodesAtLevel(root->right, level - 1);
} else if(root -> right && root -> left == nullptr) {
count += numberOfNodesAtLevel(root -> right, level - 1);
} else if(root -> left && root -> right == nullptr) {
count += numberOfNodesAtLevel(root -> left, level - 1);
}
return count;
}
}
/** DOCUMENTATION:
* PUBLIC: @name void Shelter::BSTnumberOfNodes()
* @brief handles UI
* @return void-type
*/
void ShelterBST::numberOfNodes() {
/** @note handle UI in main*/
std::cout << "\n[The total number of nodes in the BST is: [" << numberOfNodes(root) << "]\n";
}
/** DOCUMENTATION:
* PUBLIC: @name void Shelter::BSTnumberOfInternalNodes()
* @brief handles UI
* @return void-type
*/
void ShelterBST::numberOfInternalNodes() {
std::cout << "\n[The total number of internal nodes in the BST is: [" << numberOfInternalNodes(root) << "]]\n";
}
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::numberOfNodesAtLevel()
* @brief handles UI
* @param level initger corrsponding to the level in a binary tree
* @return void-type
*/
void ShelterBST::numberOfNodesAtLevel(int level) {
int nodesAtLevel = numberOfNodesAtLevel(root, level);
std::cout << "\n[The total number of nodes at level [" << level << "] is: [" << nodesAtLevel << "]]\n";
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name int ShelterBST::findHeight()
* @brief Calculates the height of the binary search tree starting from the given root node.
* @param root A pointer to the root node of the binary search tree.
* @return The height of the binary search tree.
* @note The height of the binary search tree is defined as the number of edges on the longest
* path from the root node to a leaf node in the tree.
*/
int ShelterBST::findHeight(struct TreeNode* root) {
if (root == nullptr) {
return 0;
}
int leftHeight = findHeight(root->left);
int rightHeight = findHeight(root->right);
return 1 + std::max(leftHeight, rightHeight); /** @note std::max() finds the maximum value in-between the two*/
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::isBalanced()
* @brief Check if the binary search tree is balanced.
* @param root The root node of the binary search tree.
* @return True if the binary search tree is balanced, false otherwise.
*/
bool ShelterBST::isBalanced(struct TreeNode* root) {
/** @note find the height of each subtree recursively and compare -> call findHeight with subtrees as params
* can't differ by more than one
*/
if (root == nullptr) {
return true;
}
int leftHeight = findHeight(root->left); /** @note L subtree*/
int rightHeight = findHeight(root->right); /** @note R subtree*/
if (abs(leftHeight - rightHeight) > 1) { /** @note using abs because it cant be negative */
return false;
}
return isBalanced(root->left) && isBalanced(root->right); /** @note true if right and left subtree are balanced*/
}
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::findHeight()
* @brief Handles UI
* @return void-type
*/
void ShelterBST::findHeight() {
std::cout << "\n[The height of the tree is: [" << findHeight(root) << "]\n";
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::isBalanced()
* @brief Handles UI
* @return void-type
*/
void ShelterBST::isBalanced() {
bool balanced = isBalanced(root);
if(balanced) {
std::cout << "\n[BST is balanced]\n";
} else {
std::cout << "\n[BST is [NOT] balanced]\n";
}
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testSearch()
* @brief Tests the search() function by checking if it returns nullptr for non-existent values.
* @return Returns true if the search() function correctly returns nullptr for non-existent values, false otherwise.
* @note Test 1A: Tests for non-existent values
* @post If the value is not found in the BST, search() should return nullptr.
* @note Assumes that user does not enter spaces for names.
*/
bool ShelterBST::testSearch() { //?1
/** @note
* - assuming user doesnt enter spaces for names
* - might not work idk yet
*/
TreeNode* root = nullptr;
TreeNode* node1 = search(root, "12");
TreeNode* node2 = search(root, "18");
TreeNode* node3 = search(root, "11");
TreeNode* node4 = search(root, "4");
TreeNode* node5 = search(root, "3");
std::vector<TreeNode*> nodes;
nodes.push_back(node1);
nodes.push_back(node2);
nodes.push_back(node3);
nodes.push_back(node4);
nodes.push_back(node5);
for(auto node : nodes) { //== to for each loop in python (<3)
if(node != nullptr) {
std::cout << "\n *** TEST1 [Expected [nullptr] but got something else] *** \n";
return false;
}
}
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testSearchB()
* @brief Private function to test search() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testSearchB() { //?2
TreeNode* root = nullptr; | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** @note insert nodes*/
root = insert(root, new Pet("D", 3));
root = insert(root, new Pet("C", 5));
root = insert(root, new Pet("R", 2));
root = insert(root, new Pet("A", 1));
TreeNode* exists = search(root, "D");
TreeNode* exists2 = search(root, "R");
if(exists == nullptr) {
std::cout << "\n*** TEST2 [Expected [" << root << "] but got [nullptr]] *** \n";
return false;
} else if(exists -> pet -> name != "D") {
std::cout << "\n*** TEST2 [Expected [\"D\"] but got " << exists -> pet -> name <<" *** \n";
}
if(exists2 == nullptr) {
std::cout << "\n*** TEST2 [Expected [" << root << "] but got [nullptr]] *** \n";
return false;
} else if(exists2 -> pet -> name != "R") {
std::cout << "\n*** TEST2 [Expected [\"\"] but got " << exists2 -> pet -> name <<" *** \n";
}
/** @note deallocate*/
destroyTree(root);
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testInsert()
* @brief Private function to test insert() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.m
* @return
*/
bool ShelterBST::testInsert() { //?3
TreeNode* root = nullptr;
/** @note insert nodes*/
root = insert(root, new Pet("D", 1));
root = insert(root, new Pet("B", 2));
root = insert(root, new Pet("A", 3));
root = insert(root, new Pet("C", 4));
root = insert(root, new Pet("F", 5));
root = insert(root, new Pet("G", 6));
root = insert(root, new Pet("E", 7));
/** @note expected tree
D
/ \
B F
/ \ / \
A C E G
*/
if(root -> pet -> name != "D") { //A
std::cout << "\n*** TEST2[A] [Expected [D] but got [" << root -> pet -> name << "]] ***\n";
return false;
}
if(root -> right -> pet -> name != "F") { //B
std::cout << "\n*** TEST2[B] [Expected [F] but got [" << root -> right -> pet -> name << "]] ***\n";
return false;
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
if(root -> right -> left -> pet -> name != "E") { //C
std::cout << "\n*** TEST2[C] [Expected [E] but got [" << root -> right -> left -> pet -> name << "]] ***\n";
return false;
}
if(root -> right -> right -> pet -> name != "G") { //D
std::cout << "\n*** TEST2[D] [Expected [G] but got [" << root -> right -> right -> pet -> name << "]] ***\n";
return false;
}
if(root -> left -> pet -> name != "B") { //E
std::cout << "\n*** TEST2[E] [Expected [B] but got [" << root -> left -> pet -> name << "]] ***\n";
return false;
}
if(root -> left -> left -> pet -> name != "A") { //F
std::cout << "\n*** TEST2[F] [Expected [A] but got [" << root -> left -> left -> pet -> name << "]] ***\n";
return false;
}
if(root -> left -> right -> pet -> name != "C") { //G
std::cout << "\n*** TEST2[G] [Expected [C] but got [" << root -> left -> right -> pet -> name << "]] ***\n";
return false;
}
if(root -> left -> left -> left != nullptr) { //H
std::cout << "\n*** TEST2[H] [Unexpected node found] ***\n";
return false;
}
if(root -> left -> left -> right != nullptr) { //I
std::cout << "\n*** TEST2[I] [Unexpected node found] ***\n";
return false;
}
if(root -> left -> right -> left != nullptr) { //J
std::cout << "\n*** TEST2[J] [Unexpected node found] ***\n";
return false;
}
if(root -> left -> right -> right != nullptr) { //K
std::cout << "\n*** TEST2[K] [Unexpected node found] ***\n";
return false;
}
if(root -> right -> right -> right != nullptr) { //L
std::cout << "\n*** TEST2[L] [Unexpected node found] ***\n";
return false;
}
if(root -> right -> right -> left != nullptr) { //M
std::cout << "\n*** TEST2[M] [Unexpected node found] ***\n";
return false;
}
if(root -> right -> left -> right != nullptr) { //N
std::cout << "\n*** TEST2[N] [Unexpected node found] ***\n";
return false;
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
if(root -> right -> left -> left != nullptr) { //O
std::cout << "\n*** TEST2[O] [Unexpected node found] ***\n";
return false;
}
/** @note deallocate*/
destroyTree(root);
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testFindParent()
* @brief Private function to test findParent() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testFindParent() { //?4
TreeNode* root = nullptr;
Pet* pet1 = new Pet("C", 5);
root = insert(root, pet1);
Pet* pet2 = new Pet("B", 3);
root = insert(root, pet2);
Pet* pet3 = new Pet("D", 8);
root = insert(root, pet3);
Pet* pet4 = new Pet("J", 12);
root = insert(root, pet4);
Pet* pet5 = new Pet("A", 17);
root = insert(root, pet5);
TreeNode* resultOne = findParent(root, "D");
if (resultOne->pet->name != "C") {
return false; /** @test failed*/
std::cout << "\n*** TEST4 [Expected \"C\" but got \"" << resultOne -> pet -> name << "\"] *** \n";
}
if (resultOne == nullptr) {
std::cout << "\n*** TEST4 [Expected " << findParent(root, "C") << " but got [nullptr]] *** \n";
return false; /** @test failed*/
}
destroyTree(root);
return true; /** @test failed*/
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testFindPredecessor()
* @brief Private function to test findPredecessor() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testFindPredecessor() { //?5
TreeNode* root = nullptr;
Pet* pet1 = new Pet("C", 5);
root = insert(root, pet1);
Pet* pet2 = new Pet("B", 3);
root = insert(root, pet2);
Pet* pet3 = new Pet("D", 8);
root = insert(root, pet3);
Pet* pet4 = new Pet("J", 12);
root = insert(root, pet4);
Pet* pet5 = new Pet("A", 17);
root = insert(root, pet5);
std::vector<std::string> names;
findPredecessorHelper(root, names); | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
std::vector<std::string> names;
findPredecessorHelper(root, names);
if (names.size() != 5 || names[0] != "A" || names[1] != "B" || names[2] != "C" || names[3] != "D" || names[4] != "J") {
std::cout << "\n*** TEST5 [Expected <\"C\" \"B\" \"D\" \"J\" \"A\"> but got ";
for(auto name : names) { //for name in names
std::cout << "\"" << name << "\" ";
}
std::cout << ">] ***\n";
return false; /** @test failed*/
}
TreeNode* predecessor = findPredecessor(root, "C");
if(predecessor -> pet -> name != "B") {
std::cout << "\n*** TEST5 [Expected \"B\" but got \"" << predecessor -> pet -> name << "\"] ***\n";
return false;
}
destroyTree(root);
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testDeleteNode()
* @brief Private function to test deleteNode() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testDeleteNode() { //?6
TreeNode* root = nullptr;
root = insert(root, new Pet("cat", 1));
root = insert(root, new Pet("dog", 2));
root = insert(root, new Pet("fish", 3));
root = deleteNode(root, "dog");
if (search(root, "dog") != nullptr) {
std::cout << "\n*** TEST6 [Expected [nullptr] but got [" << search(root, "dog") << "]]\n ***";
return false;
}
root = deleteNode(root, "cat");
if (search(root, "cat") != nullptr) {
std::cout << "\n*** TEST6 [Expected [nullptr] but got [" << search(root, "cat") << "]]\n ***";
return false;
}
root = deleteNode(root, "fish");
if(root != nullptr) {
std::cout << "\n*** TEST6 [Expected [nullptr] but got [" << root << "]] ***\n";
return false;
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testDestroyTree()
* @brief Private function to test destroyTree() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testDestroyTree() { //?7
TreeNode* root = nullptr;
root = insert(root, new Pet("D", 3));
root = insert(root, new Pet("B", 2));
root = insert(root, new Pet("A", 2));
root = insert(root, new Pet("C", 2));
root = insert(root, new Pet("F", 2));
root = insert(root, new Pet("G", 2));
root = insert(root, new Pet("E", 2));
root = destroyTree(root);
if (root != nullptr) {
std::cout << "\n*** TEST7 [Expected [nullptr] but got [" << root << "]] ***\n";
return false;
}
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testNumberOfChildren()
* @brief Private function to test numberOfChildren() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testNumberOfChildren() { //?8
TreeNode* root = nullptr;
root = insert(root, new Pet("D", 3));
root = insert(root, new Pet("B", 2));
root = insert(root, new Pet("A", 2));
root = insert(root, new Pet("C", 2));
root = insert(root, new Pet("F", 2));
root = insert(root, new Pet("G", 2));
root = insert(root, new Pet("E", 2));
root = insert(root, new Pet("Z", 2));
int EQnumChildrenOne = 0;
int EQnumChildrenTwo = 1;
int EQnumChildrenThree = 2;
int numChildrenRoot = numberOfChildren(root, "D"); //has 2 children
if (numChildrenRoot != EQnumChildrenThree) {
std::cout << "\n*** TEST8 [Expected [" << EQnumChildrenThree << "] but got [" << numChildrenRoot << "]] ***\n";
return false;
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
int numChildrenLeaf = numberOfChildren(root, "C"); //has zero children
if (numChildrenLeaf != EQnumChildrenOne) {
std::cout << "\n*** TEST8 [Expected [" << EQnumChildrenOne << "] but got [" << numChildrenLeaf << "]] ***\n";
return false;
}
int numChildrenHanging = numberOfChildren(root, "G"); //has one child
if (numChildrenHanging != EQnumChildrenTwo) {
std::cout << "\n*** TEST8 [Expected [" << EQnumChildrenThree << "] but got [" << numChildrenHanging << "]] ***\n";
return false;
}
destroyTree(root);
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testNumberOfNodes()
* @brief Private function to test numberOfNodes() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testNumberOfNodes() { //?9
TreeNode* root = nullptr;
/** @note the tree is degenerate*/
root = insert(root, new Pet("A", 1));
root = insert(root, new Pet("B", 2));
root = insert(root, new Pet("C", 3));
root = insert(root, new Pet("D", 4));
root = insert(root, new Pet("E", 5));
root = insert(root, new Pet("F", 6));
root = insert(root, new Pet("G", 7));
root = insert(root, new Pet("H", 8));
root = insert(root, new Pet("I", 9));
root = insert(root, new Pet("J", 10));
root = insert(root, new Pet("K", 11));
root = insert(root, new Pet("L", 12));
root = insert(root, new Pet("M", 13));
root = insert(root, new Pet("N", 14));
root = insert(root, new Pet("O", 15));
root = insert(root, new Pet("P", 16));
root = insert(root, new Pet("R", 17));
root = insert(root, new Pet("S", 18));
root = insert(root, new Pet("T", 19));
root = insert(root, new Pet("U", 20));
root = insert(root, new Pet("V", 21));
root = insert(root, new Pet("Z", 22));
root = insert(root, new Pet("Q", 23));
int EQnumNodes = 23;
int numNodes = numberOfNodes(root); | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
int EQnumNodes = 23;
int numNodes = numberOfNodes(root);
if (numNodes != EQnumNodes) {
std::cout << "\n*** TEST9 [Expected [" << EQnumNodes << "] but got [" << numNodes << "]] ***\n";
return false;
}
destroyTree(root);
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testNumberOfInternalNodes()
* @brief Private function to test numberOfInternalNodes() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testNumberOfInternalNodes() { //?10
TreeNode* root = nullptr;
root = insert(root, new Pet("F", 1));
root = insert(root, new Pet("C", 2));
root = insert(root, new Pet("J", 3));
root = insert(root, new Pet("B", 4));
root = insert(root, new Pet("D", 5));
root = insert(root, new Pet("G", 6));
root = insert(root, new Pet("Z", 7));
int EQinternalNodes = 3;
int internalNodes = numberOfInternalNodes(root);
if(EQinternalNodes != internalNodes) {
std::cout << "\n*** TEST10 [Expected [" << EQinternalNodes << "] but got [" << internalNodes << "]] ***\n";
return false;
}
destroyTree(root);
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testHeight()
* @brief Private function to test findHeight() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testHeight() { //?11
TreeNode* root = nullptr;
/** @note the tree is degenarate/sparse*/ | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** @note the tree is degenarate/sparse*/
root = insert(root, new Pet("A", 1));
root = insert(root, new Pet("B", 2));
root = insert(root, new Pet("C", 3));
root = insert(root, new Pet("D", 4));
root = insert(root, new Pet("E", 5));
root = insert(root, new Pet("F", 6));
root = insert(root, new Pet("G", 7));
root = insert(root, new Pet("H", 8));
root = insert(root, new Pet("I", 9));
root = insert(root, new Pet("J", 10));
root = insert(root, new Pet("K", 11));
root = insert(root, new Pet("L", 12));
root = insert(root, new Pet("M", 13));
root = insert(root, new Pet("N", 14));
root = insert(root, new Pet("O", 15));
root = insert(root, new Pet("P", 16));
root = insert(root, new Pet("Q", 17));
root = insert(root, new Pet("R", 18));
root = insert(root, new Pet("S", 19));
root = insert(root, new Pet("T", 20));
root = insert(root, new Pet("U", 21));
root = insert(root, new Pet("V", 22));
root = insert(root, new Pet("W", 23));
root = insert(root, new Pet("X", 24));
root = insert(root, new Pet("Y", 25));
root = insert(root, new Pet("Z", 26));
int EQheight = 26;
int height = findHeight(root);
if(EQheight != height) {
std::cout << "\n*** TEST11 [Expected [" << EQheight << "] but got [" << height << "]] *** \n";
return false;
}
destroyTree(root);
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testBalance()
* @brief Private function to test isBalanced() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testBalance() { //?12
TreeNode* root = nullptr;
root = insert(root, new Pet("F", 1));
root = insert(root, new Pet("C", 2));
root = insert(root, new Pet("J", 3));
root = insert(root, new Pet("B", 4));
root = insert(root, new Pet("D", 5));
root = insert(root, new Pet("G", 6));
root = insert(root, new Pet("Z", 7));
bool EQbalance = true;
bool balance = isBalanced(root); | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
bool EQbalance = true;
bool balance = isBalanced(root);
if(EQbalance != balance) {
/** @note boolalpha -> prints true and flase isnstead of 1 and 0*/
std::cout << std::boolalpha << "\n *** TEST12 [Expected [" << EQbalance << "] but got [" << balance << "]] ***\n";
return false;
}
destroyTree(root);
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testNodesAtLevel()
* @brief Private function to test nodesAtLevel() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testNodesAtLevel() { //?13
TreeNode* root = nullptr;
root = insert(root, new Pet("F", 1));
root = insert(root, new Pet("C", 2));
root = insert(root, new Pet("J", 3));
root = insert(root, new Pet("B", 4));
root = insert(root, new Pet("D", 5));
root = insert(root, new Pet("G", 6));
root = insert(root, new Pet("R", 13));
root = insert(root, new Pet("Z", 7));
int EQnodesAtLevelZero = 1; //root
int EQnodesAtLevelOne = 2; //root children
int EQnodesAtLevelTwo = 4; //full -> perfect tree, splits to two more
int EQnodesAtLevelThree = 1; //Z
int nodesAtLevelZero = numberOfNodesAtLevel(root, 0);
int nodesAtLevelOne = numberOfNodesAtLevel(root, 1);
int nodesAtLevelTwo = numberOfNodesAtLevel(root, 2);
int nodesAtLevelThree = numberOfNodesAtLevel(root, 3);
if(EQnodesAtLevelZero != nodesAtLevelZero) {
std::cout << "\n*** TEST13[A] [Expected [" << EQnodesAtLevelZero << "] but got [" << nodesAtLevelZero << "]] ***\n";
return false;
}
if(EQnodesAtLevelOne != nodesAtLevelOne) {
std::cout << "\n*** TEST13[B] [Expected [" << EQnodesAtLevelOne << "] but got [" << nodesAtLevelOne << "]] ***\n";
return false;
}
if(EQnodesAtLevelTwo != nodesAtLevelTwo) {
std::cout << "\n*** TEST13[C] [Expected [" << EQnodesAtLevelTwo << "] but got [" << nodesAtLevelTwo << "]] ***\n";
return false;
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
if(EQnodesAtLevelThree != nodesAtLevelThree) {
std::cout << "\n*** TEST13[D] [Expected [" << EQnodesAtLevelThree << "] but got [" << nodesAtLevelThree << "]] ***\n";
return false;
}
destroyTree(root);
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testInOrder()
* @brief Private function to test inOrder() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testInOrder() { //?14
TreeNode* root = nullptr;
root = insert(root, new Pet("F", 1));
root = insert(root, new Pet("C", 2));
root = insert(root, new Pet("J", 3));
root = insert(root, new Pet("B", 4));
root = insert(root, new Pet("D", 5));
root = insert(root, new Pet("G", 6));
root = insert(root, new Pet("Z", 7));
std::vector<std::string> names;
findPredecessorHelper(root, names);
std::vector<std::string> EQ = {"B", "C", "D", "F", "G", "J", "Z"};
if(names == EQ) { // == operator defined int the vector class (no need to iterate)
return true;
} else {
for(auto i = 0; i < (int)names.size(); i++) {
if(names[i] != EQ[i]) {
std::cout << "\n*** TEST14 [Expected [" << EQ[i] << "] but got [" << names[i] << "]] ***\n";
return false;
}
}
}
destroyTree(root);
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testPreOrder()
* @brief Private function to test preOrder() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testPreOrder() { //?15
TreeNode* root = nullptr;
root = insert(root, new Pet("F", 1));
root = insert(root, new Pet("C", 2));
root = insert(root, new Pet("J", 3));
root = insert(root, new Pet("B", 4));
root = insert(root, new Pet("D", 5));
root = insert(root, new Pet("G", 6));
root = insert(root, new Pet("Z", 7));
std::vector<std::string> names;
preOrderHelper(root, names); | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
std::vector<std::string> EQ = {"B", "D", "C", "G", "Z", "J", "F"};
if(names == EQ) { // == operator defined int the vector class (no need to iterate)
return true;
} else {
for(auto i = 0; i < (int)names.size(); i++) {
if(names[i] != EQ[i]) {
std::cout << "\n*** TEST14 [Expected [" << EQ[i] << "] but got [" << names[i] << "]] ***\n";
return false;
}
}
}
destroyTree(root);
return true;
}
/** DOCUMENTATION:
* PRIVATE: @name bool ShelterBST::testPostOrder()
* @brief Private function to test postOrder() method of ShelterBST class.
* @return Returns a boolean value indicating whether the test has passed or not.
*/
bool ShelterBST::testPostOrder() { //?16
TreeNode* root = nullptr;
root = insert(root, new Pet("F", 1));
root = insert(root, new Pet("C", 2));
root = insert(root, new Pet("J", 3));
root = insert(root, new Pet("B", 4));
root = insert(root, new Pet("D", 5));
root = insert(root, new Pet("G", 6));
root = insert(root, new Pet("Z", 7));
std::vector<std::string> names;
postOrderHelper(root, names);
std::vector<std::string> EQ = {"F", "C", "B", "D", "J", "G", "Z"}; //Z
if(names == EQ) { // == operator defined int the vector class (no need to iterate)
return true;
} else {
for(auto i = 0; i < (int)names.size(); i++) {
if(names[i] != EQ[i]) {
std::cout << "\n*** TEST16 [Expected [" << EQ[i] << "] but got [" << names[i] << "]] ***\n";
return false;
}
}
}
destroyTree(root);
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DOCUMENT:
* PRIVATE: @name std::vector<bool> ShelterBST::runAllTests()
* @brief Runs all tests on the ShelterBST object and returns a map of the test results.
* @return An unordered map with the test results. The keys are strings representing the test names,
* and the values are booleans indicating whether each test passed (true) or failed (false).
*/
std::vector<bool> ShelterBST::runAllTests(std::vector<bool> &testResults) {
testResults.push_back(testSearch());
testResults.push_back(testSearchB());
testResults.push_back(testInsert());
testResults.push_back(testFindParent());
testResults.push_back(testFindPredecessor());
testResults.push_back(testDeleteNode());
testResults.push_back(testDestroyTree());
testResults.push_back(testNumberOfChildren());
testResults.push_back(testNumberOfNodes());
testResults.push_back(testNumberOfInternalNodes());
testResults.push_back(testHeight());
testResults.push_back(testBalance());
testResults.push_back(testNodesAtLevel());
testResults.push_back(testInOrder());
testResults.push_back(testPreOrder());
testResults.push_back(testPostOrder());
return testResults;
}
/** DOCUMENTATION:
* PUBLIC: @name void ShelterBST::test()
* @brief Runs tests for all the funcntions
*/
void ShelterBST::test() {
using std::vector;
#define PASS true //macro preprocessor directive
#define FAIL false
std::string const TEST = "*** TEST ";
std::string const PASSED = " PASSED ***";
std::string const FAILED = " - FAILED ###";
std::string const PASSED_2 = " PASSED ***";
std::string const FAILED_2 = " - FAILED ###";
long int const PAUSE = 1000000; | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
vector<bool> testValues;
std::cout << "\n\n*** RUNNING ALL TESTS *** ";
std::cout << std::flush; //flush the buffer or else usleep doesn't work
usleep(PAUSE);
runAllTests(testValues);
std::cout << std::endl << std::endl;
for(auto i = 0; i < (int)testValues.size(); i++) {
if(testValues[i] == PASS && i < 9) { /** @bug fail and pass*/
std::cout << TEST << i+1 << PASSED << std::endl;
} else if(testValues[i] == FAIL && i < 9) {
std::cout << TEST << i+1 << FAILED << std::endl;
} else if(testValues[i] == PASS && i > 9) {
std::cout << TEST << i+1 << PASSED_2 << std::endl;
} else if(testValues[i] == FAIL && i > 9) {
std::cout << TEST << i+1 << FAILED_2 << std::endl;
}
}
}
assignment3.cpp
/** DOCUMENTATION:
* @author Jakob Balkovec
* @file assignment3.cpp [Driver Code]
* @note Driver code for A3
*
* @brief This assigment focuses on using multiple operations regarding BST like:
* - Insertion
* - Traversals
* - Searching
* - Deletion
*
* Those operations were implemented using a ShelterBST class that includes a struct for Pets and
* A struct for the TreeNodes.
*/
#include <string>
#include <iostream>
#include "ShelterBST.h"
#include <vector>
#include <limits>
#pragma message("[" __FILE__"] " "Last compiled on [" __DATE__ "] at [" __TIME__"]")
/** @name OPID (opeartion ID)
* @enum for the switch statement
* @brief Every operation has a numerical value
*/
enum OPID {
ID_1 = 1,
ID_2 =2,
ID_3 = 3,
ID_4 = 4,
ID_5 = 5,
ID_6 = 6,
ID_7 = 7,
ID_8 = 8,
ID_9 = 9,
ID_10 = 10,
ID_11 = 11,
ID_12 = 12,
ID_13 = 13,
ID_14 = 14,
ID_15 = 15,
ID_16 = 16
}; | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** @name printTitle()
* @brief The function prints the title
* @remark Handles UI
* @return void-type
*/
void printTitle() {
std::cout << "\n\n*** [binary search tree]. *** \n\n";
std::cout << "[select one of the following]\n\n";
}
/** @name printMenu()
* @brief The function prints a menu for the user
* @remark Handles UI
* @return void-type
*/
void printMenu() {
std::cout << "\n\n"
<< "[1] [in-order traversal]\n"
<< "[2] [pre-order traversal]\n"
<< "[3] [post-order traversal]\n"
<< "[4] [insert a pet]\n"
<< "[5] [find the predecessor]\n"
<< "[6] [find the parent]\n"
<< "[7] [search for a pet]\n"
<< "[8] [delete a node]\n"
<< "[9] [number of nodes]\n"
<< "[10] [number of internal nodes]\n"
<< "[11] [number of nodes per level]\n"
<< "[12] [get the height]\n"
<< "[13] [BST balance]\n"
<< "[14] [destroy BST]\n"
<< "[15] [quit]\n"
<< "[16] [run-tests]\n";
}
/** @name goodbye()
* @brief The function prompts the user goodbye
* @remark Handles UI
* @return void-type
*/
void goodbye() {
std::cout << "\n\nGoodbye!\n\n";
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** @name getInput()
* @brief The function prompts the user to enter a number corresponding to the menu
* @return int choice (0 < choice < 8)
*/
int getInput() {
int const MIN = 1;
int const MAX = 17;
int choice = 0;
std::cout << "\n[Enter]: ";
while (true) {
try {
std::cin >> choice;
if (std::cin.fail()) { //std::cin.fail() if the input is not an intiger returns true
/// @link https://cplusplus.com/forum/beginner/2957/
std::cin.clear(); // clear error flags
std::cin.ignore(10000, '\n'); // ignore up to 10000 characters or until a newline is encountered
throw std::invalid_argument("[Invalid input]");
}
else if (choice < MIN || choice > MAX) {
throw std::out_of_range("[Input out of range. Please enter an integer between 1 and 16]");
}
else {
return choice;
}
}
catch (const std::exception& error) {
std::cout << error.what() << std::endl;
std::cout << "[Re-enter]: ";
}
}
}
/** @name getName()
* @brief Prompts the user to enter a name
* @param name passed by reference
* @return std::string name
*/
std::string getName(std::string &name) {
std::cout << "[Enter Name]: ";
while (true) {
try {
std::cin >> name;
if (std::cin.fail()) {
throw std::runtime_error("[Invalid input. Please enter a valid name]");
}
return name;
} catch (const std::runtime_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cin.clear();
std::cin.ignore(10000, '\n');
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** @name getAge()
* @brief Prompts the user to enter an age
* @param age passed by reference
* @return int age
*/
int getAge(int &age) {
std::cout << "\n[Enter Age]: ";
while (true) {
try {
std::cin >> age;
if (std::cin.fail() || age < 0) {
throw std::runtime_error("[Invalid input. Please enter a positive integer]");
}
return age;
} catch (const std::runtime_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
std::cin.clear();
std::cin.ignore(10000, '\n');
std::cout << "\n[Enter Age]: ";
}
}
}
/** @name getLevel()
* @brief Prompts the user to enter a level
* @param level passed by reference
* @return int level
*/
int getLevel(int &level) { /** @note should I check for user input here -> ???*/
std::cout << "\n[Enter Level]: ";
while (true) {
try {
std::cin >> level;
if (std::cin.fail()) { //std::cin.fail() if the input is not an intiger returns true
/// @link https://cplusplus.com/forum/beginner/2957/
std::cin.clear(); // clear error flags
std::cin.ignore(10000, '\n'); // ignore up to 10000 characters or until a newline is encountered
throw std::invalid_argument("[Invalid input]");
}else {
return level;
}
}
catch (const std::exception& error) {
std::cout << error.what() << std::endl;
std::cout << "[Re-enter]: ";
}
}
}
int main(int argc, char **argv) { | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
/** DECLARATIONS: */
ShelterBST tree;
std::string name = "";
int age = 0;
int level = 0;
/** DECLARATIONS: */
printTitle();
while(true) {
printMenu();
switch(getInput()) {
case OPID::ID_1: {
/** @note in-order*/
tree.inOrderDisplay();
break;
}
case OPID::ID_2: {
/** @note pre-order*/
tree.preOrderDisplay();
break;
}
case OPID::ID_3: {
/** @note post-order*/
tree.postOrderDisplay();
break;
}
case OPID::ID_4: {
/** @note insert a pet*/
tree.insertPet(getName(name), getAge(age));
break;
}
case OPID::ID_5: {
/** @note find predecessor*/
tree.findInorderPredecessor(getName(name));
break;
}
case OPID::ID_6: {
/** @note find parent*/
tree.findParent(getName(name));
break;
}
case OPID::ID_7: {
/** @note search for a pet*/
tree.searchPet(getName(name));
break;
}
case OPID::ID_8: {
/** @note delte a node*/
tree.deleteNode(getName(name));
break;
}
case OPID::ID_9: {
/** @note number of nodes in BST*/
tree.numberOfNodes();
break;
}
case OPID::ID_10: {
/** @note number of internal nodes*/
tree.numberOfInternalNodes();
break;
}
case OPID::ID_11: {
/** @note number of nodes @ level*/
tree.numberOfNodesAtLevel(getLevel(level));
break;
}
case OPID::ID_12: {
/** @note get height*/
tree.findHeight();
break;
}
case OPID::ID_13: {
/** @note is the BST balanced*/
tree.isBalanced();
break;
}
case OPID::ID_14: {
/** @note destroy the tree*/
tree.destroyTree();
break;
}
case OPID::ID_15: {
/** @note quit*/
tree.destroyTree();
goodbye();
exit(EXIT_FAILURE);
break;
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
tree.destroyTree();
goodbye();
exit(EXIT_FAILURE);
break;
}
case OPID::ID_16: {
/** @note run tests*/
tree.test();
break;
}
default: {
/** @note do nothing...*/
}
}
}
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
MakeFile
CC=g++
CFLAGS= -O3 -Wall -Werror -pedantic -std=c++11
SRCS=ShelterBST.cpp assignment3.cpp
OBJS=$(subst .cpp,.o,$(SRCS))
all: prog
prog: $(OBJS)
$(CC) $(CFLAGS) $(OBJS) -o prog
%.o: %.cpp
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -f $(OBJS) prog
Answer: Things you would not do in real code
I know you have been given some restrictions, however in code you write outside of a course you would not have these restrictions and you would do things differently. I just want to point that out for readers:
C++11 is quite old and nowadays you'd aim for C++20, unless you can't because of backwards compatibility reasons.
You would definitely use templates to make your code more generic. In particular, you could create a template<typename T> class BST, have a separate class Pet, and then you can typedef BST<Pet> ShelterBST.
Of course if you just want a container for pets sorted on name, and don't care too much about the underlying datastructure, you'd use a standard container like std::set or std::map. | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
That said, you will definitely learn some useful things about C++ from the given assignment.
Documentation format
I see you have comments in your code that look remarkably similar to Doxygen style comments, but not quite. It would be great if you follow the Doyxgen format exactly; this way the Doxygen tools can generate PDF and HTML versions of the documentation, check that you have documented everything, and some code editors even understand Doxygen as well and will be able to display it when you hover over function and class names.
Separate concerns
Your code does not follow the separation of concerns design principle. The ShelterBST class does too many things: it contains the logic of managing the BST, it has unit tests built-in, and it can interact with the user, printing directly to std::cout.
Having a function void insertPet(std::string name, int age) is fine, but void searchPet(std::string name) is bad, because it doesn't return anything to the caller, it just prints to std::cout. That means you can't do anything other than printing whether that pet is in the database or not. What if you want to know its age? What if there was more data stored in class Pet? Ideally, a function like searchPet() would return a pointer to the Pet that was found, or nullptr in case the pet was not found. The caller can then decide what to do with the result, which greatly increases the flexibility of that function.
So how to do this for things like inOrderDisplay()? You want to separate the act of traversing the BST in order from displaying the items. You can do this in C++ by creating a function inOrderVisit() that takes a std::function as a parameter, so the caller can pass a function to inOrderVisit(), and the latter can call it for every item it visits:
void inOrderVisit(std::function<void(Pet*)>); | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
The caller could then do:
ShelterBST shelter;
…
auto printPet = [](Pet* pet) {
std::cout << "Name: [" << pet->name << "] Age: [" << pet->age << "]\n";
};
shelter.inOrderVisit(printPet);
Note that printPet is a lambda in this example (still C++11), but you could just make it a regular function as well. You want to write a test for pre-order traversal? There is no more need for a preOrderHelper(); just pass preOrderVisit() a different function:
ShelterBST shelter;
shelter.addPet("F", 1");
shelter.addPet("C", 2");
…
std::vector<std::string> names;
shelter.preOrderVisit([&](Pet *pet){ names.push_back(pet->name); });
A more advanced option would be to add iterators, so you can use a range-for loop. It would allow you to write code like this:
ShelterBST shelter;
…
for (Pet* pet: shelter.preOrder()) {
std::cout << "Name: [" << pet->name << "] Age: [" << pet->age << "]\n";
} | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
c++, c++11, binary-search-tree
Unit tests
For the unit tests, ideally you would only need to use public functions to test the functionality of your class. With the above changes you can already test if the search functionality and traversal work without needing access to private functions. However, if you really want to be able to access private members in the tests, then one way is to make a test class or function and declare that as a friend inside ShelterBST. That way, the test class has access to the private internals of any ShelterBST object.
There are lots of unit test libraries for C++. You would typically use one of those that fits your needs. The more powerful libraries make both writing tests and running them easier.
What about the move constructor?
I see you wrote a copy constructor and copy assignment operator, but what about the move constructor and move assignment operator? It would be nice to implement those as well.
Use '\n' instead of std::endl
Prefer to use '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually unnecessary and negatively impacts performance.
Avoid obsolete and non-standard functions
usleep() is neither C nor C++. It's a POSIX function which has been deprecated in 2001. If you are writing in C, then use the POSIX nanosleep() or clock_nanosleep() functions. However, in C++11 the standard way to sleep is to use std::this_thread::sleep_for(). | {
"domain": "codereview.stackexchange",
"id": 44806,
"lm_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, binary-search-tree",
"url": null
} |
python, python-3.x, dependency-injection, crud
Title: A practice program to manipulate a database table using dependency injection
Question: I am learning dependency injection and trying to use this pattern on practice. I am trying to write simple program where the user can write something to database, delete row and clear all rows from db. So is it right realization of dependency injection?
import os
from enum import Enum
import pymysql
class Properties(Enum):
ID = 0
NAME = 1
class ConsoleManager:
def print_line(self) -> None:
print('-----------------\n')
return None
def print_data(self, data) -> None:
for row in data:
print(f"{row[Properties.ID.value]}\t|\t{row[Properties.NAME.value]}")
return None
class DatabaseManager:
def __init__(self, connection) -> None:
self.connection = connection
self.cursor = connection.cursor()
return None
def get_count_abobas(self) -> int:
self.cursor.execute('SELECT COUNT(*) FROM abobas')
count = self.cursor.fetchone()[0]
self.connection.commit()
return count
def insert_id_and_name(self, count, name) -> None:
sql = f'INSERT INTO abobas (id, abobas.aboba_name) VALUES ({count + 1}, \'{name}\')'
self.cursor.execute(sql)
self.connection.commit()
return None
def select_and_get_all_rows(self) -> tuple:
sql = "SELECT * FROM abobas ORDER BY id"
self.cursor.execute(sql)
result = self.cursor.fetchall()
self.connection.commit()
return result
def delete_by_name(self, name) -> None:
sql = f"DELETE FROM abobas WHERE aboba_name = '{name}'"
self.cursor.execute(sql)
self.connection.commit()
return None
def clear_table(self) -> None:
sql = 'DELETE FROM abobas'
self.cursor.execute(sql)
self.connection.commit()
return None | {
"domain": "codereview.stackexchange",
"id": 44807,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, dependency-injection, crud",
"url": null
} |
python, python-3.x, dependency-injection, crud
self.connection.commit()
return None
def update_id(self) -> None:
count = self.get_count_abobas()
for i in range(1, count + 1):
sql = f'UPDATE abobas SET id = {i} WHERE id > {i - 1} LIMIT 1'
self.cursor.execute(sql)
return None
class ConsoleService:
def __init__(self, console_manager, database_manager) -> None:
self.console_manager = console_manager
self.database_manager = database_manager
@staticmethod
def console_output(func):
def wrap(*args):
args[0].console_manager.print_line()
func(*args)
args[0].console_manager.print_line()
return wrap
@console_output
def write_to_db(self) -> None:
name = input("Enter name: ")
count = self.database_manager.get_count_abobas()
self.database_manager.insert_id_and_name(count, name)
print("Row successfully added to the table.")
@console_output
def read_from_file(self) -> None:
print('id\t|\tname')
self.console_manager.print_line()
result = self.database_manager.select_and_get_all_rows()
self.console_manager.print_data(result)
@console_output
def delete_by_name(self) -> None:
name = input('Enter the name to delete: ')
self.database_manager.delete_by_name(name)
self.database_manager.update_id()
print(f"An element with name {name} was successfully deleted.")
@console_output
def clear_all(self) -> None:
self.database_manager.clear_table()
print('Table is now clear.')
def main():
connection = pymysql.connect(
host='localhost',
user='sqluser',
password='password',
database='abobadb'
)
console_manager = ConsoleManager()
database_manager = DatabaseManager(connection)
console_service = ConsoleService(console_manager, database_manager) | {
"domain": "codereview.stackexchange",
"id": 44807,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, dependency-injection, crud",
"url": null
} |
python, python-3.x, dependency-injection, crud
while True:
os.system('cls||clear')
console_service.read_from_file()
print('Choose the option:\n\t1. Write to db.\n\t2. Delete by name.\n\t3. Clear all elements.')
choice = int(input("Enter your choice: "))
if choice == 1:
console_service.write_to_db()
elif choice == 2:
console_service.delete_by_name()
elif choice == 3:
console_service.clear_all()
else:
break
connection.close()
return None
if __name__ == '__main__':
main()
Also you can check my code and give me some advices in order to make my code clear and readable.
I have tried to implement dependency injection using classes DatabaseManager, ConsoleManager and ConsoleService.
Answer: Congrats, you nailed dependency injection! Although for a case where it is really useful you would need several implementations of e.g. ConsoleManager that you can choose from, or several instances of DatabaseManager that use the same dependency. Otherwise it may be hard to see the actual benefits of DI.
As for the code itself:
MySql databases come with an auto-generated id, so you're essentially making a second one. Not saying that it's bad, especially for an exercise like this, just keep that feature in mind when designing a scheme for a real database.
There is no need to return None as it's returned implicitly (and no, explicit return doesn't make the code more readable, if that was the concern).
Nitpick: method name print_line is associated with "printing the text and then a \n character (a new line)", so something like draw_horizontal_line would fit better.
print_data will print something like
9 | Lupa
10 | Pupa | {
"domain": "codereview.stackexchange",
"id": 44807,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, dependency-injection, crud",
"url": null
} |
python, python-3.x, dependency-injection, crud
if strings in the first column have different width. As you can see vertical lines are not aligned. Python has some built-in methods of dealing with this.
get_count_abobas doesn't need to commit as it's not changing anything. update_id, on the other hand, does!
Overall very clean code, keep it up! | {
"domain": "codereview.stackexchange",
"id": 44807,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, dependency-injection, crud",
"url": null
} |
python, beginner, python-3.x, array
Title: Automate the boring stuff with python - Character picture grid
Question: Character Picture Grid
Say you have a list of lists where each value in the inner lists is a one-character string, like this:
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
You can think of grid[x][y] as being the character at the x- and y-coordinates of a “picture” drawn with text characters. The (0, 0) origin will be in the upper-left corner; the x-coordinates increase going right, and the y-coordinates increase going down.
Copy the previous grid value, and write code that uses it to print the image.
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
My solution:
def logic_grid(grid):
for x in range(6):
for y in range(9):
if y < 8:
print(grid[y][x], end='')
else:
print(grid[y][x])
def main():
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
start = logic_grid(grid)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 44808,
"lm_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, beginner, python-3.x, array",
"url": null
} |
python, beginner, python-3.x, array
if __name__ == '__main__':
main()
Answer: In Python, you rarely need to iterate using indexes. Iterate directly
over the values themselves, not their indexes. [The latter is what programmers
working in poorer languages have to do.]
Question the assignment. In my opinion, the function should not
take a grid and print it. Rather, it should return the grid as a string. The
latter is more flexible and more in line with the general principle of
organizing programs around data-oriented, side-effect-free functions.
Don't hard-code the function to one specific grid. A key purpose of
functions is to generalize behavior so it can be reused. If the function
hardcodes the grid's dimensions, that generality disappears.
Python iterables can be joined together into strings. This is a basic
operation. Take advantage of it.
def main():
# Printing happens out at this level.
grid = [...]
print(grid_to_str(grid))
def grid_to_str(grid):
# No side effects here. Just data in and data out.
# As noted by RootTwo, we have to transpose the grid.
return '\n'.join(
''.join(row)
for row in zip(*grid)
)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 44808,
"lm_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, beginner, python-3.x, array",
"url": null
} |
object-oriented, rust
Title: Complex numbers implementation in Rust
Question: I am learning object oriented programming in Rust. I created my own struct for complex numbers. Could you please review and answer my questions:
Is it possible to implement C++-like default constructor? I want to replace let c0 = my_math::Complex::default(); with let c0: Complex;.
Why should I implement PartialEq instead of Eq?
Why should I implement type Output = Complex;? I already have -> Complex. | {
"domain": "codereview.stackexchange",
"id": 44809,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "object-oriented, rust",
"url": null
} |
object-oriented, rust
mod my_math {
use std::fmt;
use std::ops;
use std::cmp::PartialEq;
pub struct Complex {
// Complex numbers (real, image * i)
pub real: i32,
pub imaginary: i32
}
impl Complex {
pub fn new(real: i32, imaginary: i32) -> Complex {
Complex {real: real, imaginary: imaginary}
}
}
impl Default for Complex {
fn default() -> Self {
Complex { real: 0, imaginary: 0}
}
}
impl fmt::Display for Complex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {}i)", self.real, self.imaginary)
}
}
impl ops::Add<Complex> for Complex {
type Output = Complex;
fn add(self, rhs: Complex) -> Complex {
Complex {real: rhs.real + self.real, imaginary: rhs.imaginary + self.imaginary}
}
}
impl ops::Sub<Complex> for Complex {
type Output = Complex;
fn sub(self, rhs: Complex) -> Complex {
Complex {real: self.real - rhs.real, imaginary: self.imaginary - rhs.imaginary}
}
}
impl ops::Mul<Complex> for Complex {
type Output = Complex;
fn mul(self, rhs: Complex) -> Self::Output {
Complex {
real: self.real * rhs.real - self.imaginary * rhs.imaginary,
imaginary: self.real * rhs.imaginary + self.imaginary * rhs.real
}
}
}
impl PartialEq for Complex {
fn eq(&self, other: &Self) -> bool {
self.real == other.real && self.imaginary == other.imaginary
}
}
}
fn main() {
let c0 = my_math::Complex::default();
assert!(c0.real == 0); | {
"domain": "codereview.stackexchange",
"id": 44809,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "object-oriented, rust",
"url": null
} |
object-oriented, rust
fn main() {
let c0 = my_math::Complex::default();
assert!(c0.real == 0);
assert!(c0.imaginary == 0);
let c1 = my_math::Complex{real: 1, imaginary: 10};
let c2 = my_math::Complex::new(2, 20);
let c3 = c1 + c2;
let c3_expected = my_math::Complex::new(3, 30);
assert!(c3 == c3_expected);
println!("{}", c3);
} | {
"domain": "codereview.stackexchange",
"id": 44809,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "object-oriented, rust",
"url": null
} |
object-oriented, rust
Answer: Derive PartialEq (and possibly Eq too) and Default instead of manually implementing them
#[derive(PartialEq, Default)]
pub struct Complex {
// Complex numbers (real, image * i)
pub real: i32,
pub imaginary: i32
}
This simplifies the code.
Remove use std::cmp::PartialEq;
It's redundant - PartialEq is in the prelude.
Always #[derive(Debug)] for your types
This lets them be printed in a programmer-convienent format.
Implement Clone and Copy for Complex
#[derive(Clone, Copy)]
pub struct Complex {
// Complex numbers (real, image * i)
pub real: i32,
pub imaginary: i32
}
This lets Complex be copied when needed, and as a bonus, implementing Copy permits some optimizations with standard library types.
Use assert_eq!() when appropriate
Replace assert!(x == y) with assert_eq!(x, y). This prints x and y in case the assert fails. This requires them to implement Debug.
Implement Eq too
I don't know why you decided you should not implement it; you should implement it wherever you can.
Format your code with rustfmt
This makes your code follow the official Rust style.
Use derive_more
This is not necessary (I for one would not do that), but if you're fine with introducing a dependency, you can avoid the manual implementation of the ops
and even new with derive_more:
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Default,
derive_more::Constructor,
derive_more::Add,
derive_more::Sub,
)]
pub struct Complex {
// Complex numbers (real, image * i)
pub real: i32,
pub imaginary: i32,
}
Change the comment inside Complex to be a doc comment
This will document the struct better.
/// Complex numbers (real, image * i)
pub struct Complex {
pub real: i32,
pub imaginary: i32,
}
Use struct field init shorthand
If you don't use derive_more for new(), instead of specifying field: field just say field:
pub fn new(real: i32, imaginary: i32) -> Complex {
Complex { real, imaginary }
} | {
"domain": "codereview.stackexchange",
"id": 44809,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "object-oriented, rust",
"url": null
} |
object-oriented, rust
Don't specify RHS's type
It is defaulted to the same type as the implementing type, so no need to specify it.
impl ops::Mul for Complex { ... }
Final code
The code with all changes including derive_more:
mod my_math {
use std::fmt;
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Default,
derive_more::Constructor,
derive_more::Add,
derive_more::Sub,
)]
/// Complex numbers (real, image * i)
pub struct Complex {
pub real: i32,
pub imaginary: i32,
}
impl fmt::Display for Complex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {}i)", self.real, self.imaginary)
}
}
impl ops::Mul for Complex {
type Output = Complex;
fn mul(self, rhs: Complex) -> Self::Output {
Complex {
real: self.real * rhs.real - self.imaginary * rhs.imaginary,
imaginary: self.real * rhs.imaginary + self.imaginary * rhs.real,
}
}
}
}
fn main() {
let c0 = my_math::Complex::default();
assert_eq!(c0.real, 0);
assert_eq!(c0.imaginary, 0);
let c1 = my_math::Complex {
real: 1,
imaginary: 10,
};
let c2 = my_math::Complex::new(2, 20);
let c3 = c1 + c2;
let c3_expected = my_math::Complex::new(3, 30);
assert_eq!(c3, c3_expected);
println!("{}", c3);
}
The code with all changes not including derive_more:
mod my_math {
use std::fmt;
use std::ops;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
/// Complex numbers (real, image * i)
pub struct Complex {
pub real: i32,
pub imaginary: i32,
}
impl Complex {
pub fn new(real: i32, imaginary: i32) -> Complex {
Complex { real, imaginary }
}
} | {
"domain": "codereview.stackexchange",
"id": 44809,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "object-oriented, rust",
"url": null
} |
object-oriented, rust
impl fmt::Display for Complex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({}, {}i)", self.real, self.imaginary)
}
}
impl ops::Add for Complex {
type Output = Complex;
fn add(self, rhs: Complex) -> Complex {
Complex {
real: rhs.real + self.real,
imaginary: rhs.imaginary + self.imaginary,
}
}
}
impl ops::Sub for Complex {
type Output = Complex;
fn sub(self, rhs: Complex) -> Complex {
Complex {
real: self.real - rhs.real,
imaginary: self.imaginary - rhs.imaginary,
}
}
}
impl ops::Mul for Complex {
type Output = Complex;
fn mul(self, rhs: Complex) -> Self::Output {
Complex {
real: self.real * rhs.real - self.imaginary * rhs.imaginary,
imaginary: self.real * rhs.imaginary + self.imaginary * rhs.real,
}
}
}
}
fn main() {
let c0 = my_math::Complex::default();
assert_eq!(c0.real, 0);
assert_eq!(c0.imaginary, 0);
let c1 = my_math::Complex {
real: 1,
imaginary: 10,
};
let c2 = my_math::Complex::new(2, 20);
let c3 = c1 + c2;
let c3_expected = my_math::Complex::new(3, 30);
assert_eq!(c3, c3_expected);
println!("{}", c3);
}
``` | {
"domain": "codereview.stackexchange",
"id": 44809,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "object-oriented, rust",
"url": null
} |
c++, beginner, linked-list
Title: Hackerrank delete a node
Question: I have been learning c++ for a few weeks now and I attempted this problem on Hackerrank Delete a node. I am aware of a similar post Delete a linked list node but the code seems more of a C structure than a C++ structure. Please feel free to suggest areas of Improvement and shorter way of writing this if any exists. Here is excerpt of the question
You’re given the pointer to the head node of a linked list and the
position of a node to delete. Delete the node at the given position
and return the head node. A position of 0 indicates head, a position
of 1 indicates one node away from the head and so on. The list may
become empty after you delete the node.
Input Format You have to complete the Node* Delete(Node* head, int position) method which takes two arguments - the head of the
linked list and the position of the node to delete. You should NOT
read any input from stdin/console. The position will always be at least 0
and less than the number of the elements in the list.
Output Format Delete the node at the given position and return the head of the updated linked list. Do NOT print anything to
stdout/console.
Sample Input
1 --> 2 --> 3 --> NULL, position = 0 1 --> NULL , position = 0
Sample Output
2 --> 3 --> NULL NULL
/*
Delete Node at a given position in a linked list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* Delete(Node *head, int position)
{
// Complete this method
Node *temp = head;
if(position == 0){
head = head->next;
return head;
}
Node *temp2 = head;
for(int i = 0 ; i < position-1; i++){
temp2 = temp2->next;
}
temp = temp2->next->next;
temp2->next = temp;
return head;
}
Answer: A few comments: | {
"domain": "codereview.stackexchange",
"id": 44810,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, linked-list",
"url": null
} |
c++, beginner, linked-list
Answer: A few comments:
It is cleaner to define the position parameter as unsigned or
std::size_t as it cannot be negative. Same applies to the for loop counter.
There is a memory leak, as you don't do delete on the removed
node.
Names like temp and temp2 are not reader-friendly. How about
current_node? Speaking of which, the assignment to temp2 is redundant.
The code should validate that we don't go beyond the end of the list. We can of course assume that invalid index cannot be passed to the function, but it's a dangerous assumption that does not lead to defensive code.
While we're on the parameter validation topic; if we get passed an empty list (i.e. head == NULL), there will again be undefined behaviour irrespective of the value of position.
If we delete the last node, the code will behave in an undefined manner (most likely crash). Consider that temp2->next will be NULL in that case, which means that temp2->next->next won't be a happy statement.
Speaking of last comment, do you have unit tests in place? If so, it'd be good to have edge cases covered (delete first node, delete last node, empty list etc.)
Hope this helps. | {
"domain": "codereview.stackexchange",
"id": 44810,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, linked-list",
"url": null
} |
c++, c++17, binary-tree
Title: leetcode 530. In-order traversal of a binary search tree (C++17) | {
"domain": "codereview.stackexchange",
"id": 44811,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, binary-tree",
"url": null
} |
c++, c++17, binary-tree
Question: Given a binary search tree, the problem requires calculating the minimum absolute difference between any two keys in the tree. Given the binary search property, the minimum difference must be between in-order neighbors.
I am basically a C++ beginner and this was my attempt at writing "idiomatic" and readable C++17. I am looking for feedback regarding where my code falls short in this aspect.
My solution, along with a description of the TreeNode struct, is as follows. The main idea is to have a textbook-looking in-order traversal along with a visitor that builds the in-order array. Kind of expected this pattern to make the in-order traversal subroutine more generic. Finally, I find the minimum difference using the build in-order array.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
template <class Visitor>
void inorder_traversal(TreeNode *root, Visitor visit) {
if (root->left != nullptr) {
inorder_traversal(root->left, visit);
}
visit(root->val);
if (root->right != nullptr) {
inorder_traversal(root->right, visit);
}
return;
}
public:
int getMinimumDifference(TreeNode* root) {
using T = decltype(root->val);
vector<T> inorder;
auto visit = [&](T val) {
inorder.push_back(val);
return;
};
inorder_traversal(root, visit);
adjacent_difference(inorder.begin(), inorder.end(), inorder.begin());
auto cmp = [](T a, T b) {
return abs(a) < abs(b);
};
return *min_element(inorder.begin()+1, inorder.end(), cmp);
}
}; | {
"domain": "codereview.stackexchange",
"id": 44811,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, binary-tree",
"url": null
} |
c++, c++17, binary-tree
Optionally, is it possible to make this more performant while making few compromises on readability?
Some notes regarding the leetcode platform:
the solution class was already given as a template.
most standard library headers are included by default along with using namespace std;
Answer: Use std::invoke() to call the visitor
Visitor can be anything: a regular function, a lambda, or even a pointer to member function. The latter cannot be called by writing visit(root->val). To be able to support those, use std::invoke(); it will automatically do the right thing depending on the type of Visitor:
std::invoke(visit, root->val);
Pass visit by reference
You are passing Visitor by value. The problem is that it doesn't work well if you pass in a mutable lambda. For example, what if I want the visitor to skip every other node? You could do that by writing:
auto visit = [&, skip = false](T val) mutable {
if (!skip) {
inorder.push_back(val);
}
skip = !skip;
};
But if you pass visit by value, then a copy is made every time inorder_traversal() is called recursively. So for example, in the outermost call to inorder_traversal() you will have:
void inorder_traversal(TreeNode *root, Visitor visit) {
if (root->left != nullptr) {
inorder_traversal(root->left, visit); // skip = false
}
visit(root->val); // skip = false before the call, true after it returns
if (root->right != nullptr) {
inorder_traversal(root->right, visit); // skip = true
}
} | {
"domain": "codereview.stackexchange",
"id": 44811,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, binary-tree",
"url": null
} |
c++, c++17, binary-tree
If you pass visit by reference, then you won't have that problem.
It doesn't matter for getMinimumDifference() of course, but it's a good excercise to make the traversal function as generic as possible.
Pass by const reference or pointer where appropriate
I see you make no assumptions about decltype(root->val), even though the LeetCode site says it will be an int. Writing more generic code is great though, but then consider that T might be a type that is large and expensive to copy. However, your visitor function takes a T val parameter, which will potentially make a copy every time it is called. That might be inefficient, and perhaps even impossible if T is const. So it's better to pass it by const reference:
auto visit = [&](const T& val) {
…
};
In real life you would also pass root as a const pointer, but this was part of LeetCode's template, so then you are stuck with it being non-const.
Use a single pass algorithm
You are going over all the data three times: once to make a std::vector out of the tree, the second time to calculate the adjacent differences, and the third time to find the minimum of the differences. However, you could write a visitor that remembers the previous value it visited, so it can calculate the difference, and then it can also check that against a running minimum value:
T minimum;
T previous;
bool first = true;
auto visit = [&](const T& val) {
if (!first) {
minimum = std::min(minimum, abs(val - previous));
} else {
first = false;
}
previous = val;
};
inorder_traversal(root, visit);
return minimum; | {
"domain": "codereview.stackexchange",
"id": 44811,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, binary-tree",
"url": null
} |
c++, c++17, binary-tree
inorder_traversal(root, visit);
return minimum;
This also avoids having to allocate a std::vector to hold intermediate results, so you'll use a lot less memory as well.
Make it even more generic
T is the type of root->val. However, if you subtract a T from a T, is the result also a T? That's not necessarily the case: consider having a tree of std::chrono::time_points. The difference between those has type std::chrono::duration. And maybe the overload of abs() that works on the difference type returns yet another type. So in my example above, I should actually have written:
decltype(abs(root->val - root->val)) minimum;
Also note that the return value of getMinimumDifference() should be of the same type as minimum, which you can easily do by just making it auto.
Your function can return negative values
In your code, the vector inorder may contain negative values. While the lambda cmp calls abs(), the call to min_element() will still return a reference to an element in inorder, so it can return a negative value. My example above doesn't have this issue. You can fix your code by adding one more call to abs().
LeetCode is not idiomatic
I am basically a C++ beginner and this was my attempt at writing "idiomatic" and readable C++17.
I know you have to conform to the template LeetCode give you in order for your submission to run there, but the problem is that this template is far from idiomatic C++. In particular, if you were not bound by those restrictions, you would: | {
"domain": "codereview.stackexchange",
"id": 44811,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, binary-tree",
"url": null
} |
c++, c++17, binary-tree
Not use a class Solution, but rather just have a stand-alone function getMinimumAbsoluteDifference() that would return the desired result.
You would not use using namespace std. While it looks very handy, the problem is that you don't know everything that is being pulled into the global namespace. If you have multiple using namespace statements, it gets even harder. In header files you wouldn't use this at all, but in source files the proper thing to do is pull in only specifically what you need: using std::vector; using std::adjacent_difference; and so on. Or just write std::. | {
"domain": "codereview.stackexchange",
"id": 44811,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++17, binary-tree",
"url": null
} |
recursion, rust, tail-recursion
Title: tail recursive directory traversal in Rust
Question: Please evaluate and help me understand if my attempted implementation of a tail recursive directory traversal function is actually tail recursive or not. I wrote this from my understanding that a tail recursion happens if the recursive call is the last thing done by a function. The output of traversal matches the nested directory structure I had while testing, but I am not sure if this really qualifies as a tail recursive function because the one example which I could find in google (factorial), it uses an accumulator while I do not use it because I cannot figure out where to use it either if needed one.
use std::fs;
fn traverse_directory(directory: &str, filenames: &mut Vec<String>) {
if let Ok(entries) = fs::read_dir(directory) {
entries.for_each(|entry| {
if let Ok(entry) = entry {
let path = entry.path();
if path.is_file() {
filenames.push(path.file_name().unwrap().to_string_lossy().into_owned());
} else if path.is_dir() {
return traverse_directory(&path.to_string_lossy(), filenames)
}
}
});
}
}
fn main() {
let mut list = Vec::new();
traverse_directory("/tmp", &mut list);
println!("{:?}", list);
}
If this is not tail recursive, can someone kindly explain why it is not, and how this could be made one?
I wrote this in Rust because I was following an algorithm tutorial made for Rust programming language, but my question is language agnostic.
Thank you. | {
"domain": "codereview.stackexchange",
"id": 44812,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "recursion, rust, tail-recursion",
"url": null
} |
recursion, rust, tail-recursion
Answer: This is Not Tail-Recursive, Because You Recurse from a Closure
The return traverse_directory(...) statement would be tail-recursive from traverse_directory, but it is being called from a closure. That’s equivalent to calling from a named helper function. The function and the anonymous closure within it could still be mutually-recursive if the closure were tail-called, and get most of the same optimizations, but that is not the case. It is called from a for_each, and must create a new stack frame each time so that the loop can resume.
(I deleted my original first paragraph, because your use of return from a closure is correct, just not tail-recursion.)
Rust Does Not Guarantee Tail-Call Optimization Anyway
Tail-recursive algorithms in Rust might compile to unoptimized calls that eat up the stack, and you will not be warned when this happens. I’ve generally had good results with functions that have moved or dropped all their local values that aren’t references when they tail-recurse, and therefore have no need to keep anything alive during the tail-call and drop it after, but this will not be reliable in Rust, unless the language changes.
Indeed, testing with Godbolt shows that this call is not optimized as a tail-call.
Graydon Hoare has called his announcement “one of the saddest posts ever written on the subject,” and later said that this was one of the times he was outvoted on the design.
The List Should be the Return Value
It does not make much sense to require the caller to pass in &mut Vec::new() so the function can fill it. Just create the Vec yourself and pass it back. This allows callers to chain and compose this function, and is one less thing that can go wrong with the public API. | {
"domain": "codereview.stackexchange",
"id": 44812,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "recursion, rust, tail-recursion",
"url": null
} |
recursion, rust, tail-recursion
If I were writing a tail-recursive function with an accumulator in a functional language, I would probably write the version with the accumulator as a private helper, have the public function call it with the accumulator set to 0/an empty list/whatever, and return the folded value. This keeps the benefits of immutable data, but in a language like Haskell, it’s also the only real option.
In Rust, it can sometimes be an optimization to pass around references instead of moving parameters, but that is not as true for an efficiently-moveable type like Vec. If the compiler is able to optimize out tail-recursion, it is also able to optimize out a move from a parameter to itself.
Refactor with Either a for Loop or an Iterator
If You Use a for Loop
This is the simplest solution. Create a new mut Vec<String>. For each element in the list, either push the name of the regular file to the result Vec, or append the list returned by a recursive call to the function.
If You Use Iterators
As an alternative to for_each, you could write a quasi-functional solution here. Write a helper function that turns a DirEntry into either a sequence of all files within a recursive descent of the directory, or a singleton of its filename. Then, do a flat_map over all sequences generated by the directory entries.
Iterators often lead to elegant, fluent code, but here you have to pick your poison. Each directory item adds either no names (if invalid), one name (if it is a regular file or symlink) or at least one but possibly more (if it is a directory). That means you will have to convert the result of all three cases into some common type. One of them, a recursive call, will return a Vec<String>.
You can therefore: | {
"domain": "codereview.stackexchange",
"id": 44812,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "recursion, rust, tail-recursion",
"url": null
} |
recursion, rust, tail-recursion
Represent all three cases as a Vec<String>, whose length might be 0 or 1, and do a lot of tiny heap allocations for all the singletons.
Convert all three cases into a Box<dyn Iterator<Item = String>> and use runtime polymorphism, creating many tiny objects on the heap.
Convert all three cases into a &[String] without using the heap, but now be forced to clone each borrowed &String.
An implementation that does the first of these (which should be simpler and have less overhead than the other two):
use std::fs::{self, DirEntry};
pub fn traverse_directory(directory: &str) -> Vec<String> {
fn dirent_helper(entry: DirEntry) -> Vec<String> {
let filetype = entry.file_type().expect("Invalid file type");
if filetype.is_file() || filetype.is_symlink() {
vec!{entry.path().to_str().expect("Invalid filename").to_string()}
} else if filetype.is_dir() {
traverse_directory(entry.path().to_str().expect("Invalid directory"))
} else {
Vec::new()
}
}
fs::read_dir(directory)
.expect("Error reading directory")
.flat_map(|entry| dirent_helper(entry.expect("Invalid directory entry")))
.collect()
}
pub fn main() {
println!("{:?}", traverse_directory("."));
}
For simplicity, this panics on any error (including not having read permission on any directory), but you can change that behavior to return a std::io::Result (perhaps with the ? operator) or silently ignore them and return an empty list. It also does not return the names of empty directories, which you might want it to.
You Could Also fold
Since you have a sequence of DirEntry objects and want to accumulate a list of pathnames, a better way to do that might be as a fold that appends to the accumulator. This mixes in some non-functional operations in Rust (since Vec::append and Vec::push are implemented as side-effect functions on mut data).
use std::fs::{self, DirEntry}; | {
"domain": "codereview.stackexchange",
"id": 44812,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "recursion, rust, tail-recursion",
"url": null
} |
recursion, rust, tail-recursion
pub fn traverse_directory(directory: &str) -> Vec<String> {
fn dirent_helper(mut list: Vec<String>, entry: DirEntry) -> Vec<String> {
let filetype = entry.file_type().expect("Invalid file type");
if filetype.is_file() || filetype.is_symlink() {
list.push(entry.path().to_str().expect("Invalid filename").to_string())
} else if filetype.is_dir() {
list.append(&mut traverse_directory(
entry.path().to_str().expect("Invalid directory")))
}
list
}
fs::read_dir(directory)
.expect("Error reading directory")
.map(|entry| entry.expect("Invalid directory entry"))
.fold(Vec::new(), dirent_helper)
}
pub fn main() {
println!("{:?}", traverse_directory("."));
}
This is a nearly-zero-cost abstraction for what you were doing. (See for yourself on Godbolt.) The path that does not recursively descend compiles to a loop with no temporary objects created on the heap. All the gory details stay inside the function, hidden from the caller. However, there is one unnecessary move of list per iteration, costing four instructions on X86-64. (This is a missed optimization: since dirent_helper is a local function that cannot be called from anywhere else, the compiler could have passed list in the same registers it used for the return value, and could then have modified it in-place.)
Don’t Shadow so Many Names
You re-use entry something like three times in a row. This is confusing to a maintainer, and also runs the risk of a typo making the compiler think it should use an earlier version. | {
"domain": "codereview.stackexchange",
"id": 44812,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "recursion, rust, tail-recursion",
"url": null
} |
c#, beginner, console
Title: unit converter (3 days of C#)
Question: I am new to programming. I picked up a C# course from freeCodeCamp.org a few days ago and today I created my first code from scratch. I know probably it's not the best optimized but it works. Some things still don't make sense to me completely but I hope in the future it will all click.
However, I am making this post to try to reach to more experienced C# developers to see what I could've done better.
Thank you for your time!
namespace UnitConverter
{
internal class Program
{
static void Main(string[] args)
{
string firstMeasure;
string secondMeasure;
double MeasureValue;
bool tryAgain = true;
string playAgain;
bool valueIsGood = false;
bool valueIsGood2 = false;
bool valueIsGood3 = false;
string restart; | {
"domain": "codereview.stackexchange",
"id": 44813,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
while (tryAgain)
{
Console.WriteLine("--------------");
Console.WriteLine("UNIT CONVERTER");
Console.WriteLine("--------------");
Console.WriteLine("");
Console.WriteLine("Choose your first measurement");
Console.WriteLine("km - kilometers");
Console.WriteLine("m - meters");
Console.WriteLine("cm - centimeters");
Console.Write("Choose: ");
do
{
firstMeasure = Console.ReadLine();
firstMeasure = firstMeasure.ToUpper();
if (firstMeasure == "km".ToUpper() || firstMeasure == "cm".ToUpper() || firstMeasure == "m".ToUpper())
{
Console.Write("Value in " + firstMeasure + ": ");
valueIsGood = true;
}
else
{
Console.WriteLine("Incorrect measurement");
Console.Write("Choose: ");
}
} while (!valueIsGood);
while (!double.TryParse(Console.ReadLine(), out MeasureValue))
{
Console.WriteLine("This is not a number!");
Console.Write("Choose: ");
}
Console.WriteLine("Choose your second measurement");
Console.WriteLine("km - kilometers");
Console.WriteLine("m - meters");
Console.WriteLine("cm - centimeters");
Console.Write("Choose: "); | {
"domain": "codereview.stackexchange",
"id": 44813,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
do
{
secondMeasure = Console.ReadLine();
secondMeasure = secondMeasure.ToUpper();
if (secondMeasure == "km".ToUpper() || secondMeasure == "cm".ToUpper() || secondMeasure == "m".ToUpper())
{
valueIsGood2 = true;
}
else
{
Console.WriteLine("Incorrect measurement");
Console.Write("Choose: ");
}
} while (!valueIsGood2); | {
"domain": "codereview.stackexchange",
"id": 44813,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
if (secondMeasure == "km".ToUpper() || secondMeasure == "cm".ToUpper() || secondMeasure == "m".ToUpper())
{
if (firstMeasure == "km".ToUpper() && secondMeasure == "km".ToUpper())
{
double result = MeasureValue * 1;
Console.WriteLine("RESULT: " + MeasureValue + firstMeasure + " is " + result + secondMeasure);
}
else if (firstMeasure == "km".ToUpper() && secondMeasure == "m".ToUpper())
{
double result = MeasureValue * 1000;
Console.WriteLine("RESULT: " + MeasureValue + firstMeasure + " is " + result + secondMeasure);
}
else if (firstMeasure == "km".ToUpper() && secondMeasure == "cm".ToUpper())
{
double result = MeasureValue * 100000;
Console.WriteLine("RESULT: " + MeasureValue + firstMeasure + " is " + result + secondMeasure);
}
else if (firstMeasure == "m".ToUpper() && secondMeasure == "km".ToUpper())
{
double result = MeasureValue / 1000;
Console.WriteLine("RESULT: " + MeasureValue + firstMeasure + " is " + result + secondMeasure);
}
else if (firstMeasure == "m".ToUpper() && secondMeasure == "m".ToUpper())
{
double result = MeasureValue * 1;
Console.WriteLine("RESULT: " + MeasureValue + firstMeasure + " is " + result + secondMeasure);
}
else if (firstMeasure == "m".ToUpper() && secondMeasure == "cm".ToUpper())
{ | {
"domain": "codereview.stackexchange",
"id": 44813,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
{
double result = MeasureValue * 100;
Console.WriteLine("RESULT: " + MeasureValue + firstMeasure + " is " + result + secondMeasure);
}
else if (firstMeasure == "cm".ToUpper() && secondMeasure == "km".ToUpper())
{
double result = MeasureValue / 100000;
Console.WriteLine("RESULT: " + MeasureValue + firstMeasure + " is " + result + secondMeasure);
}
else if (firstMeasure == "cm".ToUpper() && secondMeasure == "m".ToUpper())
{
double result = MeasureValue / 100;
Console.WriteLine("RESULT: " + MeasureValue + firstMeasure + " is " + result + secondMeasure);
}
else if (firstMeasure == "cm".ToUpper() && secondMeasure == "cm".ToUpper())
{
double result = MeasureValue * 1;
Console.WriteLine("RESULT: " + MeasureValue + firstMeasure + " is " + result + secondMeasure);
}
} | {
"domain": "codereview.stackexchange",
"id": 44813,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
do
{
Console.WriteLine("Try again? - Y/N");
restart = Console.ReadLine();
restart = restart.ToUpper();
if (restart == "Y")
{
valueIsGood3 = true;
}
else if (restart == "N")
{
Console.WriteLine("Thank you for using the calculator!");
Console.WriteLine("Exiting in...");
for (int i = 5; i >= 1; i--)
{
Console.WriteLine(i);
int milliseconds = 1000;
Thread.Sleep(milliseconds);
}
valueIsGood3 = true;
tryAgain = false;
} else
{
Console.WriteLine("Incorrect answer.");
Console.WriteLine("Options: Y or N");
valueIsGood3 = false;
tryAgain = true;
}
} while (!valueIsGood3);
}
}
}
}
Answer: First of all congratulation, you are on a good way to become a software developer.
The solution itself is far from perfect but it is a good start.
In this post I would like to focus on two things: methods and variable scopes.
Methods can help you to better organize your code and reuse the same logic in multiple places
Variable scope can help you to minimize the chance to access an unrelated variable or forgot to set a related one (for example for the next iteration) | {
"domain": "codereview.stackexchange",
"id": 44813,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
Extracting the measure unit asking logic
static string AskForMeasureUnit()
{
Console.WriteLine("Choose your first measurement");
Console.WriteLine("km - kilometers");
Console.WriteLine("m - meters");
Console.WriteLine("cm - centimeters");
Console.Write("Choose: ");
do
{
string measureUnit = Console.ReadLine().ToLower();
if (measureUnit == "km" || measureUnit == "cm" || measureUnit == "m")
{
return measureUnit;
}
Console.WriteLine("Incorrect measurement");
Console.Write("Choose: ");
} while (true);
}
In order to get the firstMeasure and secondMeasure you have repeated the exact same code
I've moved that logic into an AskForMeasureUnit method to be able to reuse it
I've changed your .ToUpper to .ToLower since your string constants ("cm", "m", "km") are already in lower case
I've also changed your do-while loop to run indefinitely (while(true)) until an acceptable user input is provided
At that point I've used the return measureUnit; to break out from the loop
With the above method in our hand we can rewrite the first half of the while(tryAgain)'s body like this:
Console.WriteLine("--------------");
Console.WriteLine("UNIT CONVERTER");
Console.WriteLine("--------------");
Console.WriteLine("");
string firstMeasure = AskForMeasureUnit();
Console.Write("Value in " + firstMeasure + ": ");
double measuredValue;
while (!double.TryParse(Console.ReadLine(), out measuredValue))
{
Console.WriteLine("This is not a number!");
Console.Write("Choose: ");
}
string secondMeasure = AskForMeasureUnit();
With this change you don't need to declare the following variables on the top of your Main: firstMeasure, secondMeasure, MeasureValue, valueIsGood and valueIsGood2 | {
"domain": "codereview.stackexchange",
"id": 44813,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
Extracting the conversion logic
static double PerformConversion(string firstMeasure, string secondMeasure, double measureValue)
{
if (firstMeasure == "m" && secondMeasure == "cm")
{
return measureValue * 100;
}
if (firstMeasure == "cm" && secondMeasure == "m")
{
return measureValue / 100;
}
if (firstMeasure == "km" && secondMeasure == "m")
{
return measureValue * 1_000;
}
if (firstMeasure == "m" && secondMeasure == "km")
{
return measureValue / 1_000;
}
if (firstMeasure == "km" && secondMeasure == "cm")
{
return measureValue * 100_000;
}
if (firstMeasure == "cm" && secondMeasure == "km")
{
return measureValue / 100_000;
}
return measureValue; //firstMeasure == secondMeasure
}
Since your Console.ReadLine statement is the same in each and every case you don't need to repeat it
The branches should focus on the differences only
I've used digit separator (_) to improve legibility of the numbers
I've used multiple return statements to avoid the usage of else if
As you can see this method does not have any local variable
With the above method in our hand we can continue the main logic after the string secondMeasure = AskForMeasureUnit(); line like this
var result = PerformConversion(firstMeasure, secondMeasure, measuredValue);
Console.WriteLine("RESULT: " + measuredValue + firstMeasure + " is " + result + secondMeasure);
Extracting the should retry asking logic
static bool AskForRetry()
{
do
{
Console.WriteLine("Try again? - Y/N");
var restart = Console.ReadLine().ToUpper();
if(restart != "Y" && restart != "N")
{
Console.WriteLine("Incorrect answer.");
Console.WriteLine("Options: Y or N");
continue;
}
return restart == "Y";
} while (true);
} | {
"domain": "codereview.stackexchange",
"id": 44813,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
return restart == "Y";
} while (true);
}
I've simplified a bit your code by having only a single branch inside the infinite loop
The loop runs until it receives a valid input
The countdown logic could remain inside the main code
tryAgain = AskForRetry();
}
Console.WriteLine("Thank you for using the calculator!");
Console.WriteLine("Exiting in...");
for (int i = 5; i >= 1; i--)
{
Console.WriteLine(i);
int milliseconds = 1000;
Thread.Sleep(milliseconds);
}
For the sake of completeness here is the entire code:
static void Main(string[] args)
{
bool tryAgain = true;
while (tryAgain)
{
Console.WriteLine("--------------");
Console.WriteLine("UNIT CONVERTER");
Console.WriteLine("--------------");
Console.WriteLine("");
string firstMeasure = AskForMeasureUnit();
Console.Write("Value in " + firstMeasure + ": ");
double measuredValue;
while (!double.TryParse(Console.ReadLine(), out measuredValue))
{
Console.WriteLine("This is not a number!");
Console.Write("Choose: ");
}
string secondMeasure = AskForMeasureUnit();
var result = PerformConversion(firstMeasure, secondMeasure, measuredValue);
Console.WriteLine("RESULT: " + measuredValue + firstMeasure + " is " + result + secondMeasure);
tryAgain = AskForRetry();
}
Console.WriteLine("Thank you for using the calculator!");
Console.WriteLine("Exiting in...");
for (int i = 5; i >= 1; i--)
{
Console.WriteLine(i);
int milliseconds = 1000;
Thread.Sleep(milliseconds);
}
}
static string AskForMeasureUnit()
{
Console.WriteLine("Choose your first measurement");
Console.WriteLine("km - kilometers");
Console.WriteLine("m - meters");
Console.WriteLine("cm - centimeters");
Console.Write("Choose: "); | {
"domain": "codereview.stackexchange",
"id": 44813,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c#, beginner, console
do
{
string measureUnit = Console.ReadLine().ToLower();
if (measureUnit == "km" || measureUnit == "cm" || measureUnit == "m")
{
return measureUnit;
}
Console.WriteLine("Incorrect measurement");
Console.Write("Choose: ");
} while (true);
}
static double PerformConversion(string firstMeasure, string secondMeasure, double measureValue)
{
if (firstMeasure == "m" && secondMeasure == "cm")
{
return measureValue * 100;
}
if (firstMeasure == "cm" && secondMeasure == "m")
{
return measureValue / 100;
}
if (firstMeasure == "km" && secondMeasure == "m")
{
return measureValue * 1_000;
}
if (firstMeasure == "m" && secondMeasure == "km")
{
return measureValue / 1_000;
}
if (firstMeasure == "km" && secondMeasure == "cm")
{
return measureValue * 100_000;
}
if (firstMeasure == "cm" && secondMeasure == "km")
{
return measureValue / 100_000;
}
return measureValue; //firstMeasure == secondMeasure
}
static bool AskForRetry()
{
do
{
Console.WriteLine("Try again? - Y/N");
string restart = Console.ReadLine().ToUpper();
if (restart != "Y" && restart != "N")
{
Console.WriteLine("Incorrect answer.");
Console.WriteLine("Options: Y or N");
continue;
}
return restart == "Y";
} while (true);
} | {
"domain": "codereview.stackexchange",
"id": 44813,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console",
"url": null
} |
c++, performance, c++20, priority-queue
Title: Priority Queue (With raise priority operation) using Vector
Question: Here I have implemented a priority queue, with the addition of the raise_priority (also known as reduce key) operation. The reason I have effectively reimplemented std::priority_queue is because the STL implementation does not have a raise_priority operation, nor can it be implemented (No access to the underlying container). That being said, the part I am mostly concerned about in terms of performance is the raise_priority operation.
template<typename K, typename T, typename C = std::less<K>>
requires std::predicate<C, K, K>
class PriorityVectorQueue {
std::vector<std::pair<K, T>> heap;
private:
inline void bubble(size_t index) {
while (index > 0 && C()(heap[(index - 1) / 2].first, heap[index].first)) {
std::swap(heap[index], heap[(index - 1) / 2]);
index = (index - 1) / 2;
}
}
inline void sink(size_t index) {
size_t size = heap.size();
while (2 * index + 1 < size) {
size_t child = 2 * index + 1;
if (child + 1 < size && C()(heap[child].first, heap[child + 1].first)) {
++child;
}
if (C()(heap[index].first, heap[child].first)) {
std::swap(heap[index], heap[child]);
index = child;
} else {
break;
}
}
}
public:
inline PriorityVectorQueue() : heap() { | {
"domain": "codereview.stackexchange",
"id": 44814,
"lm_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, priority-queue",
"url": null
} |
c++, performance, c++20, priority-queue
};
/**
* @brief Insert a new element into the PriorityQueue
*/
inline void insert(K key, T elem) {
heap.emplace_back(key, elem);
bubble(heap.size() - 1);
};
/**
* @brief Construct a new element from the given arguments in the PriorityQueue
*/
template<typename... Args>
requires std::constructible_from<T, Args...>
inline void emplace(K key, Args&&... args) {
// Should I be forwarding the key as a tuple?
heap.emplace_back(std::piecewise_construct, std::forward_as_tuple(key), std::forward_as_tuple(args...));
bubble(heap.size() - 1);
}
/**
* @brief Access the top element from the PriorityQueue
*/
inline const T& top() const {
return heap.front().second;
}
/**
* @brief Remove the top element from the PriorityQueue
*/
inline void pop() {
heap.front() = heap.back();
heap.pop_back();
sink(0);
}
/**
* @brief Re-key a previously inserted key into the
*/
template<typename I = std::equal_to<T>>
requires std::predicate<I, T, T>
inline void raise_priority(K new_key, T value) {
// TODO: Is there a better way to do this?
auto it = std::find_if(heap.cbegin(), heap.cend(), [&value](const auto& entry) {
return I()(entry.second, value);
});
if (it != heap.cend()) {
size_t index = std::distance(heap.cbegin(), it);
heap[index].first = new_key;
bubble(index);
}
}
template<typename I, typename... Args>
requires std::predicate<I, T, Args...> && std::constructible_from<T, Args...>
inline void raise_priority(K new_key, Args&&... args) {
// TODO: Is there a better way to do this?
auto it = std::find_if(heap.cbegin(), heap.cend(), [&args...](const auto& entry) {
return I()(entry.second, std::forward<Args>(args)...);
}); | {
"domain": "codereview.stackexchange",
"id": 44814,
"lm_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, priority-queue",
"url": null
} |
c++, performance, c++20, priority-queue
if (it != heap.cend()) {
size_t index = std::distance(heap.cbegin(), it);
heap[index].first = new_key;
bubble(index);
}
}
template<typename I, typename... Args>
requires std::predicate<I, T, T> && std::constructible_from<T, Args...>
inline void raise_priority(K new_key, Args&&... args) {
raise_priority<I>(new_key, { std::forward<Args>(args)... });
}
inline bool empty() const {
return heap.empty();
}
};
```
Answer: It's not a drop-in replacement
The reason I have effectively reimplemented std::priority_queue is because the STL implementation does not have a raise_priority operation | {
"domain": "codereview.stackexchange",
"id": 44814,
"lm_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, priority-queue",
"url": null
} |
c++, performance, c++20, priority-queue
But in the process you have changed the interface in other ways. It would be nicer if it was a drop-in replacement for std::priority_queue with just the added raise_priority() member function (and perhaps add a lower_priority() as well).
First, add a template parameter Container, so the user can use something other than std::vector if so desired. You might want to add a requires clause that this Container supports random access and has push_back() and related member functions.
Second, don't store key/value pairs in the container, but just T, and remove K. C (which I would rename to Compare for clarity) should then work on Ts. Note that the caller can always set T to be a std::pair<Key, Value>, and pass a Compare that just compares the Key part, but now it's no longer the responsibility of your class. The same goes for I (which I would rename to Equal), which the caller can set to just compare the Value part if so desired.
The only issue with this is if you want to do better than \$O(N)\$ to find an entry in the queue. harold suggested using a std::unordered_map to get \$O(1)\$ lookups. This might require passing a custom hash function and equality comparison function for the map to index on the value part.
Member functions missing are: push() (you have insert(), but it doesn't have an overload for r-value references), size(), swap(), and soon also push_range().
What about duplicate values?
Consider pushing two elements with the same value to the queue:
PriorityVectorQueue<int, std::string> queue;
queue.emplace(1, "foo");
queue.emplace(2, "foo"); | {
"domain": "codereview.stackexchange",
"id": 44814,
"lm_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, priority-queue",
"url": null
} |
c++, performance, c++20, priority-queue
This is perfectly fine for most of the functionality of your priority queue. However, if you want to raise the priority of one of them, you have a problem: the call to std::find_if() will just find the first entry in the heap and change the priority of that one. Note that depending on what other elements are in the queue, there is no guarantee at all which key the one it will pick has!
Maybe the caller really wants to allow duplicate values, but it also knows the exact key/value pair it wants to raise the priority of. However, your interface does not allow it to specify that. If you don't explicitly store a std::pair<K, T> to begin with, your class won't have that issue.
Unnecessary use of inline
There is no need to mark member functions inline if they are defined inside the class declaration, they will then already be implicitly inline.
No need to add an explicit constructor
heap should have a default constructor, so there is no need to explicitly construct it yourself. Since that was the only thing your constructor did, you can completely remove it.
Incomplete Doxygen documentation
You added some comments that look like they are in the Doxygen format. However, several member functions are missing comments completely, and none of them have any @param and/or @return descriptions. If you want to do this properly, you should add all of that. Run the Doxygen tools with warnings enabled on your source, and fix all the warnings it reports.
Consider using std::push_heap() and std::pop_heap()
You implemented your own bubble() and sink() operations to maintain the heap property, but the standard library comes with std::push_heap() and std::pop_heap() that you could have used. | {
"domain": "codereview.stackexchange",
"id": 44814,
"lm_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, priority-queue",
"url": null
} |
python
Title: Aggregating Python Exceptions
Question: I wanted to be able to run a series of Python functions and capture every exception that happens. The solution uses a AggregateException class and tries to leverage Python scoping in order to aggregate a sequence of Exceptions raised.
The Solution
class AggregateException(Exception):
def __init__(self, errors: List[Exception], error_count: int = 0) -> None:
self.errors = errors
self.error_count = error_count
@classmethod
def aggregate(cls, *steps: Callable[[], None]) -> None:
errors: List[Exception] = []
for step in steps:
try:
step()
except Exception as e:
errors.append(e)
if errors:
raise cls(errors=errors, error_count=len(errors))
Usage
from typing import Callable, List
class DomainSpecificException(Exception):
...
class AggregateException(Exception):
def __init__(self, errors: List[DomainSpecificException], error_count: int = 0) -> None:
self.errors = errors
self.error_count = error_count
@classmethod
def aggregate(cls, *steps: Callable[[], None]) -> None:
errors: List[Exception] = []
for step in steps:
try:
step()
except Exception as e:
errors.append(e)
if errors:
raise cls(errors=errors, error_count=len(errors))
def main():
def foo():
# stuffz that could go wrong...
raise DomainSpecificException("Something went wrong")
def bar():
# more stuffz that could go wrong...
raise DomainSpecificException("Oh no!")
try:
AggregateException.aggregate(foo, bar)
except AggregateException as err:
print(err.errors)
if __name__ == "__main__":
main()
Output
[DomainSpecificException('Something went wrong'), DomainSpecificException('Oh no!')] | {
"domain": "codereview.stackexchange",
"id": 44815,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Output
[DomainSpecificException('Something went wrong'), DomainSpecificException('Oh no!')]
Answer: Some simplification is called-for.
Drop the idea of an AggregateException that throws the collection of exceptions, and instead make a context manager ExceptionAggregator.
You have domain exceptions - good! Only pay attention to those and not all Exceptions.
Don't keep an error_count; that's redundant.
Write unit tests.
The following no longer needs callables, though - if your callables have any significant amount of code in them - you should keep the functions you've defined and just call them from context management scope.
Suggested
from types import TracebackType
from typing import Optional, Type
class DomainSpecificException(Exception):
pass
class ExceptionAggregator:
def __init__(self) -> None:
self.errors: list[DomainSpecificException] = []
def __enter__(self) -> None:
pass
def __exit__(
self,
exc_type: Optional[Type[Exception]],
exc_val: Optional[Exception],
exc_tb: Optional[TracebackType],
) -> bool:
if exc_type is DomainSpecificException:
self.errors.append(exc_val)
return True
return False
def test():
agg = ExceptionAggregator()
with agg:
pass
assert agg.errors == []
try:
with agg:
raise ValueError("Something went more wrong")
raise AssertionError()
except ValueError:
pass
assert agg.errors == []
with agg:
raise DomainSpecificException("Something went wrong")
assert len(agg.errors) == 1
assert isinstance(agg.errors[0], DomainSpecificException)
if __name__ == "__main__":
test() | {
"domain": "codereview.stackexchange",
"id": 44815,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python, console, mvp
Title: Implementing Model-View-Presenter in a console program
Question: I'm designing a board game with my wife, and am writing a console based program that can track and analyze the statistics of playtests to see if the game is balanced, what the dominant strategies are, etc.
My first goal is to write a console based program for our own use, and maybe add a GUI on top later (which would be a good occasion to learn something like PySide). After that, I'd like to make a more user friendly app-version of the stats-tracker so that other people can track stats on their phones during open playtesting (which would be great to learn about app development). I'd like to automatically track stats from a Tabletop Simulator mod as well (I have some experience with Lua and TTS modding, but would be a good way to learn more) and maybe eventually, I could even develop some tools to help other board game designers with their playtesting. I know that this is all rather ambitious (especially since I'm not that experienced!) but I think this can be a project that can help me learn a lot of valuable things.
I've been trying to learn how to apply Model-View-Presenter to structure my program, and this is my first attempt at it. Right now, it's just the player select screen, and admittedly, there's a large amount of boilerplate just for that screen. But I think the MVP can help keeping the program structured as it grows. I tried to apply some of the advice I got in this thread. I have the following questions: | {
"domain": "codereview.stackexchange",
"id": 44816,
"lm_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, console, mvp",
"url": null
} |
python, console, mvp
Has the Model-View-Presenter been implemented well? Are the responsibilities divided up as they should? I decided to link the view with the presenter through a simple callback method, is this a good idea?
Are the classes structured in a logical way and are the methods readable? I generally try to adhere to the Single Responsibility Principle, and find it relatively intuitive for functions, but find it harder for classes. Main area of concern is the Presenter class: I've already split out the logic for formatting the player table, but the class is still quite large. Is this a problem?
I'm still rather inexperienced at exception handling, has it been dealt with correctly?
How detailed should the docstrings be? I used ChatGPT to generate some of the docstrings as I find this difficult to do, and decided to use ChatGPT's more detailed docstrings for the main methods, and wrote my own less detailed docstrings for the "sub-methods". Is this the right way to go?
Any other advice and feedback is also very welcome!
#model.py
from collections.abc import Iterable
from sortedcontainers import SortedSet
# In the final implementation, this should connect up to a database.
class Model:
def __init__(self, player_names: Iterable):
self._player_names = SortedSet(player_names)
self._selected_players = SortedSet()
@property
def amount_all_players(self) -> int:
"""Returns the total number of players."""
return len(self._player_names)
@property
def amount_selected_players(self) -> int:
"""Returns the total number of selected players."""
return len(self._selected_players)
def get_slice_all_players(self, begin: int = None, end: int = None) -> list:
"""Returns a slice of the player list from the given beginning index up to,
but not including, the given end index."""
return self._player_names[begin:end] | {
"domain": "codereview.stackexchange",
"id": 44816,
"lm_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, console, mvp",
"url": null
} |
python, console, mvp
def get_selected_players(self) -> set:
"""Returns set of selected players."""
return set(self._selected_players)
def get_player_by_index(self, player_index: int) -> str:
"""Returns the player name at the given index. Raises IndexError if index is out of range."""
try:
return self._player_names[player_index]
except IndexError:
raise IndexError(f"player index {player_index} out of range")
def get_index_by_name(self, player_name: str) -> int:
"""Returns the index of the player with the given name. Raises ValueError if player not found."""
try:
return self._player_names.index(player_name)
except ValueError:
raise ValueError(f"player {player_name} not found")
def players_binary_search(self, search: str) -> int:
"""Performs a binary search on the player names."""
return self._player_names.bisect_left(search)
def index_startswith(self, index: int, search: str) -> bool:
"""Checks whether the player name at the given index starts with the search string."""
return True if self._player_names[index].startswith(search) else False
def add_new_player(self, player_name: str) -> None:
"""Adds a new player with the given name. Raises ValueError if player already exists."""
if player_name in self._player_names:
raise ValueError(f"player '{player_name}' already exists")
else:
self._player_names.add(player_name) | {
"domain": "codereview.stackexchange",
"id": 44816,
"lm_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, console, mvp",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.