text stringlengths 1 2.12k | source dict |
|---|---|
python, beginner, python-3.x, machine-learning, neural-network
def get_predictions(self):
self.predictions = np.argmax(self.A2, 0)
def get_accuracy(self, Y):
self.accuracy = np.sum(self.predictions == Y) / Y.size
def gradient_descent(self, epochs):
for i in range(epochs):
self.forward_prop()
self.backward_prop()
self.update_parameters()
if not i % 10:
self.get_predictions()
self.get_accuracy(self.Y)
self.print_status(i)
return self.weights
def print_status(self, i):
print(
f"Iteration: {i}, Prediction: {self.predictions}, Data: {self.Y}, Accuracy: {self.accuracy}"
)
def make_predictions(self, X):
self.X = X
self.forward_prop()
self.get_predictions()
groups = (
("weights", ("W1", "b1", "W2", "b2")),
("corrections", ("Z1", "A1", "Z2", "A2")),
("deltas", ("dW1", "db1", "dW2", "db2")),
)
def add_property(group, name, i):
setattr(Neural_Network, name, property(lambda self: getattr(self, group)[i]))
for group, names in groups:
for i, name in enumerate(names):
add_property(group, name, i)
if __name__ == "__main__":
DATA = pd.read_csv("C:/Users/Xeni/Desktop/data.csv")
DATA = np.array(DATA)
M, N = DATA.shape
np.random.shuffle(DATA)
MINV = 1 / M
def get_xy(start, end):
y, *x = DATA[start:end].T[:N]
return y, np.array(x) / 255
Y_DEV, X_DEV = get_xy(0, 4200)
Y_TEST, X_TEST = get_xy(4200, 12600)
Y_TRAIN, X_TRAIN = get_xy(12600, M)
def sqrt_inv(n):
return (1 / n) ** 0.5
L = N - 1
TEN_ONE, SQRT_INV_L = (10, 1), sqrt_inv(L)
PARAMETERS = (
((10, L), SQRT_INV_L),
(TEN_ONE, sqrt_inv(10)),
((10, 10), sqrt_inv(20)),
(TEN_ONE, SQRT_INV_L),
)
nn = Neural_Network(X_TRAIN, Y_TRAIN, 0.10)
nn.gradient_descent(120)
nn.make_predictions(X_DEV)
nn.get_accuracy(Y_DEV)
print(nn.accuracy) | {
"domain": "codereview.stackexchange",
"id": 44751,
"lm_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, machine-learning, neural-network",
"url": null
} |
array, functional-programming, apl, composition
Title: Dyalog APL dyadic operator deriving ambivalent function to pair two function results
Question: I'm writing a small utility operator which applies two functions to an argument pair and strands the results. The pair can either be given as two arguments or as a single argument with two elements. Either way, the left operand is applied to the left value and the right operand to the right value:
_n_β{βΊββ’ β (a b)ββΊ β΅ β (βΊβΊ a)(β΅β΅ b)}
Here is example usage for computing the factorial and the negation:
4 !_n_- 10
16 Β―10
!_n_- 4 10
16 Β―10
And here's the reverse and the unique:
3 1 4 1 5β½_n_βͺ2 7 1 8
βββββββββββ¬ββββββββ
β5 1 4 1 3β2 7 1 8β
βββββββββββ΄ββββββββ
β½_n_βͺ(3 1 4 1 5)(2 7 1 8)
βββββββββββ¬ββββββββ
β5 1 4 1 3β2 7 1 8β
βββββββββββ΄ββββββββ
However, this seems like a lot of plumbing for what is essentially a trivial operator. Can it be done more elegantly?
Answer: If you allow Behind, then _n_β{βΊββ£ β βΊ βΊβΊβ,ββ΅β΅/β€,β΅} is arguably aesthetically nicer. However, this will just blindly concatenate left and right arguments, so if we need higher-ranked ones to stay separate, then the less pretty _n_β{βΊββ£ β βΊ βΆβ,β₯βββΉ/β€,β₯ββ΅} variation is probably needed. | {
"domain": "codereview.stackexchange",
"id": 44752,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, functional-programming, apl, composition",
"url": null
} |
concurrency, clojure
Title: Client <> Query <> Subquery Bookkeeping
Question: Context
I am making a system, where different clients issue queries
A query is resolved by issuing a set of subqueries
I have an invalidation-worker, which gets notified when subqueries go stale
Goal
When a subquery goes stale, I want to notify the clients which have made this subquery
Solution
To do this, I am thinking of keeping a mapping. Here's a rough solution you can play with in the REPL:
(ns play
(:require [clojure.core.async :as a :refer [go <! go-loop >!]]))
(def recordings (atom {}))
(defn record-subquery! [client-id query-n subquery-n]
(swap! recordings update subquery-n
(fn [prev]
(let [prev (or prev #{})]
(conj prev [client-id query-n])))))
(defn go-subquery [client-id query-n subquery-n]
(go
(<! (a/timeout (rand-int 2000)))
(record-subquery! client-id query-n subquery-n)
{:client-id client-id
:query-n query-n
:subquery-n subquery-n}))
(defn go-query [client-id query-n]
(go
(let [subquery-ns (range query-n (+ query-n 5))]
{:client-id client-id
:query-n query-n
:subqueries (->> subquery-ns
(map (partial go-subquery client-id query-n))
a/merge
(a/into [])
<!)})))
(comment
(go (prn (<! (go-query :a 1)))))
(def client-chans {:a (a/chan)
:b (a/chan)})
(defn client-worker [client-id query-chan]
(go-loop []
(when-some [q (<! query-chan)]
(prn (format "queried id = %s q = %s" client-id (<! (go-query client-id q))))
(recur))))
(def invalidation-chan (a/chan))
(defn invalidation-broadcaster []
(go (loop []
(<! (a/timeout 1500))
(when (>! invalidation-chan (rand-int 10))
(recur))))) | {
"domain": "codereview.stackexchange",
"id": 44753,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "concurrency, clojure",
"url": null
} |
concurrency, clojure
(defn invalidation-worker [chan]
(go-loop []
(when-some [sq-id (<! chan)]
(let [subs (->> sq-id (@recordings))]
(prn (format "invalidating sq-id = %s subs = %s" sq-id subs))
(doseq [[client-id query-n] subs]
(>! (client-id client-chans) query-n))
(recur)))))
(comment
(do (client-worker :a (:a client-chans))
(client-worker :b (:b client-chans))
(invalidation-worker invalidation-chan)
(invalidation-broadcaster))
(a/close! invalidation-chan)
(go (>! (:a client-chans) 1)))
Problem with the solution
I am a bit sad that record-subquery! is nested under go-subquery. This makes go-query stateful. I do it though to avoid the following race condition:
T0: go-query starts
T1: subquery-1 completes
T2: subquery-1 is invalidated
T3: subquery-2 completes
T4: go-query completes
In this scenario, we would miss the T2 update.
Would you do this differently?
Answer: invariant
You didn't write down any invariants,
and the problem statement was not entirely clear.
Here's what I heard.
We return valid query results,
built up from sub-queries that are time consuming.
Each sub-query may be invalidated at any time,
which affects the overall result.
This sounds
racy
to me, as invalidation messages can be sent at any time
right up until a query result is about to be returned.
The strongest promise the current code could make is to
say that immediately before returning it checked for invalidations
and found an empty queue.
stronger promise
Suppose the channel marks all incoming messages with a timestamp or
Lamport clock.
And it returns a similar counter when reporting that
zero messages remain. Now we can sensibly describe the validity
of a query result by annotating it with that counter.
There may be subsequent invalidation messages, but they
will be marked with counter values greater than
the one in our valid result. | {
"domain": "codereview.stackexchange",
"id": 44753,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "concurrency, clojure",
"url": null
} |
concurrency, clojure
queue depth
Consider specifying a "large" value for the channel size
so that invalidators are unlikely to block.
The current default size of 1 invites lock-step
progress between producer and consumer.
post-processing
Consider performing all (time consuming!) sub-queries unconditionally,
and then doing (quick) validity checks afterward, in the interest
of simplicity.
The idea would be to go through a tight validation loop
which can exit as soon as it sees that the channel is empty. | {
"domain": "codereview.stackexchange",
"id": 44753,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "concurrency, clojure",
"url": null
} |
python, performance, neural-network
Title: Feed forward neural network
Question: I have made a basic neural network in python. The idea is the neural network can have any structure you want, not just the standard layers where every neuron is connected to every neuron in the next layer.
from numpy import exp
class Feed_forward_network:
"""
Feed_forward_network
inputs: the number of inputs, int
outputs: the number of outputs, int
neuron_data: the neuron data, list of tuples|None
the first inputs of neuron_data needs to be None
each item in neuron_data is data about the neuron
tuple[0]: the activation function of the neuron, function(float) -> float
tuple[1]: the bias of the neuron, float
tuple[2]: the connections of the neuron, list of tuples
each item in connections is data about the connection
tuple[0]: the neuron the connection is to
tuple[1]: the weight of the connection
"""
def __init__(self, inputs: int, outputs: int, neuron_data):
if outputs > len(neuron_data):
raise RuntimeError("outputs < len(neuron_data)")
self.inputs = inputs
self.outputs = outputs
self.neuron_data = neuron_data
self.neuron_values = [None]*(len(neuron_data))
def activate(self, inputs):
if self.inputs != len(inputs):
raise RuntimeError("self.inputs != len(inputs)")
self.neuron_values = [None]*len(self.neuron_values)
for i in range(len(inputs)):
self.neuron_values[i] = inputs[i]
return tuple([self.calculate_neuron(i+self.inputs) for i in range(self.outputs)])
def calculate_neuron(self, neuron):
if neuron < self.inputs:
return self.neuron_values[neuron]
neuron_value = self.neuron_values[neuron]
if neuron_value == None:
neuron_data = self.neuron_data[neuron]
self.neuron_values[neuron] = 0 # avoid RecursionError | {
"domain": "codereview.stackexchange",
"id": 44754,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, neural-network",
"url": null
} |
python, performance, neural-network
self.neuron_values[neuron] = 0 # avoid RecursionError
value = neuron_data[0](sum([self.calculate_neuron(conn)*weight for conn, weight in neuron_data[2]]) * neuron_data[1])
self.neuron_values[neuron] = value
return value
return neuron_value
def sigmoid(x: float) -> float:
return 1 / (1 + exp(-(x)))
if __name__ == "__main__":
ffn = Feed_forward_network(2, 1, [None, None, (sigmoid, 1.0, [(0, 1.0), (1, 1.0), (3, 1.0)]), (sigmoid, 1.0, [(0, 1.0), (1, 1.0), (3, 1.0)])])
print(ffn.activate([1, 1]))
print(ffn.neuron_values)
I am mainly looking for performance improvements so here is the output when profiled (I made a for loop that repeats the if __name__ == "__main__" bit 100 times because they were just all 0.000 otherwise):
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.000 0.000 <string>:1(__new__)
100 0.001 0.000 0.001 0.000 <string>:20(__init__)
100 0.001 0.000 0.009 0.000 <string>:28(activate)
1 0.000 0.000 0.000 0.000 <string>:3(Feed_forward_network)
100 0.000 0.000 0.008 0.000 <string>:37(<listcomp>)
700/100 0.002 0.000 0.008 0.000 <string>:39(calculate_neuron)
200/100 0.001 0.000 0.005 0.000 <string>:50(<listcomp>)
200 0.005 0.000 0.005 0.000 <string>:58(sigmoid)
Answer: Thanks @J_H. Here is a revised version of my code:
from numpy import exp
class FeedForwardNetwork:
"""
FeedForwardNetwork
==================
- num_inputs: the number of inputs, int
- num_outputs: the number of outputs, int
- neuron_data: the neuron data, list of tuples|None | {
"domain": "codereview.stackexchange",
"id": 44754,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, neural-network",
"url": null
} |
python, performance, neural-network
The first num_outputs of neuron_data are ouput neurons
------------------------------------------------------
Each item in neuron_data is data about the neuron
-------------------------------------------------
- tuple[0]: the activation function of the neuron, function(float) -> float
- tuple[1]: the bias of the neuron, float
- tuple[2]: the connections of the neuron, list of tuples
Each item in connections is data about the connection
-----------------------------------------------------
- tuple[0]: the neuron the connection is to
- tuple[1]: the weight of the connection
"""
def __init__(self, num_inputs: int, num_outputs: int, neuron_data: tuple):
if num_outputs > len(neuron_data):
raise RuntimeError("outputs < len(neuron_data)")
self.num_inputs = num_inputs
self.num_outputs = num_outputs
self.neuron_data = neuron_data
self.neuron_values = [None]*(len(neuron_data))
self.inputs = [None]*num_inputs
def activate(self, inputs):
if self.num_inputs != len(inputs):
raise RuntimeError("self.num_inputs != len(inputs)")
self.neuron_values = [None]*len(self.neuron_values)
for i in range(len(inputs)):
self.inputs[i] = inputs[i]
return tuple([self.calculate_neuron(i) for i in range(self.num_outputs)])
def calculate_neuron(self, neuron):
if neuron < 0:
return self.inputs[neuron]
neuron_value = self.neuron_values[neuron]
if neuron_value is not None:
return neuron_value
current_neuron_data = self.neuron_data[neuron]
self.neuron_values[neuron] = 0 # avoid RecursionError
value = current_neuron_data[0](sum([self.calculate_neuron(conn)*weight for conn, weight in current_neuron_data[2]]) * current_neuron_data[1])
self.neuron_values[neuron] = value
return value | {
"domain": "codereview.stackexchange",
"id": 44754,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, neural-network",
"url": null
} |
python, performance, neural-network
def sigmoid(x: float) -> float:
return 1 / (1 + exp(-(x)))
if __name__ == "__main__":
ffn = FeedForwardNetwork(2, 1, [(sigmoid, 1.0, [(-1, 1.0), (-2, 1.0), (1, 1.0)]), (sigmoid, 1.0, [(-1, 1.0), (-2, 1.0), (1, 1.0)])])
print(ffn.activate([1, 1]))
print(ffn.neuron_values)
reorganised the calculate_neuron() functions if logic again
renamed inputs and outputs to num_inputs and num_outputs
renamed neuron_data to current_neuron_data
reorganized how the neuron_data and neuron_values are used
changed docstring | {
"domain": "codereview.stackexchange",
"id": 44754,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, neural-network",
"url": null
} |
regex, elisp
Title: Multiple regexp replace in string
Question: I made a function that prompts me for values of variables (formatted %^{var1}) it found in a string and fills in said values.
(defun fill-var-in-string (STRING)
"Find variables in a string, prompt for a value and fill in STRING."
(let ((filled STRING))
(while (string-match "%^{\\([^}]*\\)}" STRING (match-end 0))
(setq filled (replace-regexp-in-string (format "%%^{%s}" (match-string 1 STRING))
(read-string (format "%s: " (match-string 1 STRING)))
filled)))
filled))
(message "filled in: %s" (fill-var-in-string "(%^{size}, %^{center})"))
It works, I'm wondering if I did it the lisp way. I did not make it interactive since for now I only will call this programmatically in org-mode files.
Answer: Style-wise, it looks odd to see the function argument named in all-caps. Standard convention is to use lower-case (but still upcase it in the doc-string).
Trying to run the code, it immediately failed:
Lisp error: (args-out-of-range "(%^{size}, %^{center})" 455)
string-match("%^{\\([^}]*\\)}" "(%^{size}, %^{center})" 455)
(while (string-match "%^{\\([^}]*\\)}" STRING (match-end 0)) (setq filled (replace-regexp-in-string (format "%%^{%s}" (match-string 1 STRING)) (read-string (format "%s: " (match-string 1 STRING))) filled)))
(let ((filled STRING)) (while (string-match "%^{\\([^}]*\\)}" STRING (match-end 0)) (setq filled (replace-regexp-in-string (format "%%^{%s}" (match-string 1 STRING)) (read-string (format "%s: " (match-string 1 STRING))) filled))) filled)
fill-var-in-string("(%^{size}, %^{center})") | {
"domain": "codereview.stackexchange",
"id": 44755,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "regex, elisp",
"url": null
} |
regex, elisp
This is clearly becase (match-end 0) could have any value at entry. I think we need another variable (start-pos):
(defun fill-var-in-string (string)
"Find variables in a string, prompt for a value and fill in STRING."
(let ((filled string)
(start-pos 0))
(while (string-match "%^{\\([^}]*\\)}" string start-pos)
(setq filled (replace-regexp-in-string (format "%%^{%s}" (match-string 1 string))
(read-string (format "%s: " (match-string 1 string)))
filled)
start-pos (match-end 0)))
filled))
We can simplify a little, because (format "%%^{%s}" (match-string 1 string)) is exactly what we just found, so we can replace all that with (match-string 0 string):
(defun fill-var-in-string (string)
"Find variables in a string, prompt for a value and fill in STRING."
(let ((filled string)
(start-pos 0))
(while (string-match "%^{\\([^}]*\\)}" string start-pos)
(setq filled (replace-regexp-in-string (match-string 0 string)
(read-string (format "%s: " (match-string 1 string)))
filled)
start-pos (match-end 0)))
filled))
I'm not convinced that we should be matching an empty name - I would use + rather than * in the regular expression there.
There's a subtle failure case. If the user provides a string that matches a replacement format, then it might get subsequently filled in (if it's a replacement we have yet to process). To avoid this, we shouldn't start replacing until we have read all the replacement strings - we'll need to populate an alist mapping variables to values, and then go through the string performing the replacements as a second phase. | {
"domain": "codereview.stackexchange",
"id": 44755,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "regex, elisp",
"url": null
} |
javascript, algorithm, array, functional-programming
Title: Recursive Factorial Calculation in JavaScript
Question:
function factorial(nb) {
let tab = [];
if (nb > 0) {
tab.push(nb);
tab = tab.concat(factorial(nb - 1));
}
return tab;
}
// Calculate factorial for number 3
const array = factorial(3);
// Calculate the final factorial value by reducing the array
const factorialValue = array.reduce((accumulator, currentValue) => {
return accumulator * currentValue;
}, 1);
// Output the factorial value
console.log(factorialValue);
// Result 6
The given code defines a function factorial that calculates the factorial of a number. It takes a single parameter nb, representing the number for which the factorial is calculated. The function recursively generates an array tab containing the factorial values by pushing each number from nb down to 1.
After defining the factorial function, the code calls it with the argument 3 and assigns the returned array to the variable array.
Then, the code calculates the final factorial value by using the reduce method on the array. The reduce method multiplies each element in the array together, starting from an initial value of 1. The result is stored in the variable factorialValue.
Finally, the code logs the factorialValue to the console.
Overall, the code accurately calculates the factorial of a given number. However, there are some areas where improvements could be made.
I'm seeking suggestions for improvements in the code to make it more efficient and reduce the execution time. Any tips or alternative solutions would be greatly appreciated. | {
"domain": "codereview.stackexchange",
"id": 44756,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, array, functional-programming",
"url": null
} |
javascript, algorithm, array, functional-programming
Answer: Review
Your code uses too much memory.
There is no need to store all the integers of the factorial. You can just keep a running product.
JavaScript and recursion
JavaScript is not a good language to write recursive code in. It has a very limited call stack size. Not only that each call to a function needs a new function context to be created and push to the heap, this makes recursive JS code very memory hungry (and slower than alternatives iterators).
Your function
Your function named factorial does not calculate the factorial, rather it creates an array of factorial divisors. Functions should always do what the name implies.
Storing the array means that the storage complexity of your code is \$O(n)\$ (including the following two examples)
The function below creates an array of factorial divisors using a recursive function.
function factorialArray(n, values = []) {
if (n > 0) {
values.push(values.length + 1);
factorialArray(n - 1, values);
}
return values;
}
Or using a non recursive function
function factorialArray(n, values = []) {
while (n-- > 0) {
values.push(values.length + 1);
}
return values;
}
There are many more ways to create an array of integers from 1 to n, but for this task you don't need any arrays, you just need to keep the running product.
This will reduce the storage complexity to an ideal of \$O(1)\$
Rewrite
The following function calculates the factorial for positive integers.
Keeping the running product starting at the largest integer and stepping down to the second last value 2 (as there is no need to multiply the last value by 1).
It uses Math.max to cover the special case of \$0! = 1\$
It uses a while loop to iterate over the divisors, and n (the input argument) is used as the loop counter.
It has a processing complexity of \$O(n)\$ and storage complexity of \$O(1)\$
It can calculate the factorial upto 49! at which point it fails due to javascripts Number limitations. | {
"domain": "codereview.stackexchange",
"id": 44756,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, array, functional-programming",
"url": null
} |
javascript, algorithm, array, functional-programming
function factorial(n) {
var result = Math.max(1, n);
while (n-- > 2) { result *= n; }
return result;
}
Use BigInt
JavaScripts Number limits the max usable integer to Number.MAX_SAFE_INTEGER meaning that the largest factorial you can calculate using Number is 49!.
However JavaScript also has BigInt which allows you to calculate factorials upto any value (the only limit is device memory and processing time)
Note that complexity and storage are much greater when using BigInt.
Example using BigInt
function factorial(n) {
var result = BigInt(Math.max(1, n));
n = BigInt(n);
while (n-- > 2n) { result *= n; }
return result;
}
outputEl.textContent = "957! = " + factorial(957);
code {
max-width: 100%;
word-wrap: break-word;
}
<code id="outputEl"></code> | {
"domain": "codereview.stackexchange",
"id": 44756,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, algorithm, array, functional-programming",
"url": null
} |
c++, beginner
Title: Simple Model of Library, Books, Checkout, Patrons and Fees
Question: This is an exercise I solved in the PPP book in C++. If there's a better way I could have done something, please tell me. (No main() and Date (just year)) Thank you!
For context here is the exercise:
This exercise and the next few require you to design and implement a Book class, such as you can imagine as part of software for a
library. Class Book should have members for the ISBN, title, author,
and copyright date. Also store data on whether or not the book is
checked out. Create functions for returning those data values. Create
functions for checking a book in and out. Do simple validation of data
entered into a Book; for example, accept ISBNs only of the form
n-n-n- x where n is an integer and x is a digit or a letter. Store an
ISBN as a string.
Add operators for the Book class. Have the == operator check whether the ISBN numbers are the same for two books. Have != also
compare the ISBN numbers. Have a << print out the title, author, and
ISBN on separate lines.
Create an enumerated type for the Book class called Genre. Have the types be fiction, nonfiction, periodical, biography, and children.
Give each book a Genre and make appropriate changes to the Book
constructor and member functions.
Create a Patron class for the library. The class will have a userβs name, library card number, and library fees (if owed). Have
functions that access this data, as well as a function to set the fee
of the user. Have a helper function that returns a Boolean (bool)
depending on whether or not the user owes a fee. | {
"domain": "codereview.stackexchange",
"id": 44757,
"lm_label": 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",
"url": null
} |
c++, beginner
Create a Library class. Include vectors of Books and Patrons. Include a struct called Transaction. Have it include a Book, a
Patron, and a Date from the chapter. Make a vector of
Transactions. Create functions to add books to the library, add
patrons to the library, and check out books. Whenever a user checks
out a book, have the library make sure that both the user and the book
are in the library. If they arenβt, report an error. Then check to
make sure that the user owes no fees. If the user does, report an
error. If not, create a Transaction, and place it in the vector of
Transactions. Also write a function that will return a vector that
contains the names of all Patrons who owe fees.
My solution:
Book.hpp:
#include <array>
#include <string>
#include <stdexcept>
class Book {
public:
enum class Genre {
fiction,
nonfiction,
periodical,
biography,
children,
genre_size
};
public:
// Book() = default; Doesn't make logical sense to have a default constructor here.
Book(const std::string& isbn, const std::string& title, const std::string& author, std::size_t copyRightYear, Genre genre);
const std::string& getIsbn() const { return m_isbn; }
const std::string& getTitle() const { return m_title; }
const std::string& getAuthor() const { return m_author; }
std::size_t getCopyRightYear() const { return m_copyRightYear; }
const std::string& getGenre() const {
static const std::array<std::string, static_cast<std::size_t>(Genre::genre_size)> genres {
"fiction",
"nonfiction",
"periodical",
"biography",
"children"
};
return genres.at(static_cast<std::size_t>(m_genre));
}
void bookCheckIn();
void bookCheckOut();
bool isCheckedOut() const { return m_isCheckedOut; }
private:
bool validateIsbn(const std::string &isbn) const; // n-n-n-x where n is an integer and x is a digit or a letter | {
"domain": "codereview.stackexchange",
"id": 44757,
"lm_label": 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",
"url": null
} |
c++, beginner
private:
std::string m_isbn;
std::string m_title;
std::string m_author;
std::size_t m_copyRightYear;
Genre m_genre;
bool m_isCheckedOut{};
};
bool operator==(const Book& lhs, const Book& rhs);
bool operator!=(const Book& lhs, const Book& rhs);
std::ostream& operator<<(std::ostream& os, const Book& book);
Book.cpp
#include "Book.hpp"
#include <iostream>
#include <algorithm>
#include <cctype>
Book::Book(const std::string& isbn, const std::string& title, const std::string& author, std::size_t copyRightYear, Genre genre)
: m_isbn{ isbn },
m_title{ title },
m_author{ author },
m_copyRightYear{ copyRightYear },
m_genre{ genre },
m_isCheckedOut{ true }
{
if (!validateIsbn(isbn))
throw std::runtime_error{"Book::Book(): Invalid isbn."};
}
void Book::bookCheckIn() {
if (!isCheckedOut()) {
std::cout << "You have not checked out any book.\n";
return;
}
m_isCheckedOut = false;
}
void Book::bookCheckOut() {
if (isCheckedOut()) {
std::cout << "You already checked out a book.\n";
return;
}
m_isCheckedOut = true;
}
bool Book::validateIsbn(const std::string& isbn) const {
if (isbn.length() != 7)
return false;
for (int i{}; i < 7; i += 2) {
char currentChar{ isbn[i] };
if (!isdigit(currentChar) && !isalpha(currentChar))
return false;
}
if (isbn[1] != '-' || isbn[3] != '-')
return false;
char lastChar{ isbn[6] };
if (!isdigit(lastChar) && !isalpha(lastChar))
return false;
return true;
}
bool operator==(const Book& lhs, const Book& rhs) {
return lhs.getIsbn() == rhs.getIsbn();
}
bool operator!=(const Book& lhs, const Book& rhs) {
return !(lhs == rhs);
} | {
"domain": "codereview.stackexchange",
"id": 44757,
"lm_label": 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",
"url": null
} |
c++, beginner
bool operator!=(const Book& lhs, const Book& rhs) {
return !(lhs == rhs);
}
std::ostream& operator<<(std::ostream& os, const Book& book) {
os << "Title: " << book.getTitle() << '\n'
<< "Author: " << book.getAuthor() << '\n'
<< "ISBN: " << book.getIsbn() << '\n'
<< "Is checked out? " << std::boolalpha << book.isCheckedOut() << '\n';
return os;
}
Patron.hpp
#include "Book.hpp"
#include <ostream>
class Patron {
public:
// Patron() = default; again no need for a default constructor here
Patron(const std::string& name, const std::string& libraryCardNumber);
const std::string& getName() const { return m_name; }
const std::string& getCardNumber() const { return m_libraryCardNumber; }
double getFees() const { return m_libraryFees; }
void setFees(double fees);
bool owesLibraryFees() const { return m_libraryFees > 0.0; }
private:
std::string m_name;
std::string m_libraryCardNumber;
double m_libraryFees{};
};
std::ostream& operator<<(std::ostream& os, const Patron& patron);
Patron.cpp
#include "Patron.hpp"
#include <stdexcept>
Patron::Patron(const std::string& name, const std::string& libraryCardNumber)
: m_name{ name }, m_libraryCardNumber{ libraryCardNumber } { }
void Patron::setFees(double fee) {
if (fee <= 0.0)
throw std::runtime_error{"setFee(double fee): parameter fee was <= 0.0."};
m_libraryFees = fee;
}
std::ostream& operator<<(std::ostream& os, const Patron& patron) {
os << "Name: " << patron.getName() << '\n'
<< "library Card Number: " << patron.getCardNumber() << '\n'
<< "Fees: " << '$' << patron.getFees() << '\n';
return os;
}
Library.hpp
#include "Book.hpp"
#include "Patron.hpp"
#include <iostream>
#include <vector>
class Library {
public:
struct Transaction {
Book book;
Patron patron;
};
public:
Library() = default; | {
"domain": "codereview.stackexchange",
"id": 44757,
"lm_label": 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",
"url": null
} |
c++, beginner
public:
Library() = default;
void addBook();
void addPatron();
void checkBookOut();
const Book& getBook(const std::string& title) const;
const Patron& getPatron(const std::string& libraryCardNumber) const;
const std::vector<std::string> getPatronsWithFees() const;
private:
Book::Genre parseGenre(const std::string &genre) const;
bool checkPatron(const std::string& name, const std::string& cardNumber) const;
bool checkBook(const std::string& book) const;
private:
std::vector<Book> m_books;
std::vector<Patron> m_patrons;
std::vector<Transaction> m_transactions;
};
Library.cpp
#include "Library.hpp"
#include <iostream>
Book::Genre Library::parseGenre(const std::string& genre) const {
Book::Genre parsedGenre;
if (genre == "fiction")
parsedGenre = Book::Genre::fiction;
else if (genre == "nonfiction")
parsedGenre = Book::Genre::nonfiction;
else if (genre == "periodical")
parsedGenre = Book::Genre::periodical;
else if (genre == "biography")
parsedGenre = Book::Genre::biography;
else if (genre == "children")
parsedGenre = Book::Genre::children;
else {
throw std::runtime_error("Invalid genre: " + genre);
}
return parsedGenre;
}
bool Library::checkPatron(const std::string& name, const std::string& cardNumber) const {
for (const auto& patron : m_patrons) {
if (patron.getName() == name && patron.getCardNumber() == cardNumber) return true;
}
return false;
}
bool Library::checkBook(const std::string& book) const {
for (const auto& b : m_books) {
if (b.getTitle() == book && !b.isCheckedOut()) return true;
}
return false;
}
void Library::addBook() {
std::cout << "Please enter a book in the database...\n";
std::cout << "Enter the isbn: ";
std::string isbn;
std::cin >> isbn;
std::cin.ignore(); | {
"domain": "codereview.stackexchange",
"id": 44757,
"lm_label": 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",
"url": null
} |
c++, beginner
std::cout << "Enter the title: ";
std::string title;
std::getline(std::cin, title);
std::cout << "Enter the author: ";
std::string author;
std::getline(std::cin, author);
std::cout << "Enter the copy right year: ";
std::size_t copyRightYear{};
std::cin >> copyRightYear;
std::cout << "Enter genre: ";
std::string genre;
std::cin >> genre;
m_books.emplace_back(isbn, title, author, copyRightYear, parseGenre(genre));
}
void Library::addPatron() {
std::cout << "Please enter a Patron in the database...\n";
std::cout << "Enter your name: ";
std::string name;
std::getline(std::cin, name);
std::cout << "Enter library card number: ";
std::string libraryCardNumber;
std::cin >> libraryCardNumber;
m_patrons.emplace_back(name, libraryCardNumber);
}
void Library::checkBookOut() {
std::cout << "Enter your name and your library card number: ";
std::string name, libraryCardNumber;
std::getline(std::cin, name);
std::getline(std::cin, libraryCardNumber);
if (!checkPatron(name, libraryCardNumber))
throw std::runtime_error{"checkBookOut(): person doesn't exist in the database."};
std::cout << "Enter book title: ";
std::string title;
std::getline(std::cin, title);
if(!checkBook(title))
throw std::runtime_error{"checkBookOut(): book doesn't exist in the database."};
Book book{ getBook(title) };
book.bookCheckOut();
const Patron& patron{ getPatron(libraryCardNumber) };
if (patron.owesLibraryFees())
throw std::runtime_error{"checkBookOut(): patron owns fees."};
m_transactions.push_back({ book, patron });
}
const Book& Library::getBook(const std::string& title) const {
for (const auto& book : m_books)
if (book.getTitle() == title)
return book;
} | {
"domain": "codereview.stackexchange",
"id": 44757,
"lm_label": 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",
"url": null
} |
c++, beginner
const Patron& Library::getPatron(const std::string& libraryCardNumber) const {
for (const auto& patron : m_patrons)
if (patron.getCardNumber() == libraryCardNumber)
return patron;
}
const std::vector<std::string> Library::getPatronsWithFees() const {
std::vector<std::string> names;
names.reserve(m_patrons.size());
for (const auto& patron : m_patrons) {
if (patron.owesLibraryFees())
names.emplace_back(patron.getName());
}
return names;
}
Answer: Overall impression: very competent for a C++ beginner.
Minor: "copyright" is a single word in English, so the spelling of m_copyRightYear with capital R looks odd and can cause frustration.
std::size_t seems a strange choice to represent a year, since it's not a count of things. int or perhaps short would be better.
With the functions that return references to members, there is a danger of creating a dangling reference if the calling code holds the result for longer than the Book object is alive. That doesn't seem to be the case in this program as it stands, but future changes need to have awareness of that constraint (e.g. as the vector moves its members around).
I'm not a big fan of the genres array in getGenre(), nor the genre_size member in the enumeration. I normally implement such functions using switch (with compiler warnings set to complain if any enum value isn't handled).
In modern C++, we don't need to write operator!= because it can be synthesised from operator==.
This error message should go to std::cerr:
if (!isCheckedOut()) {
std::cout << "You have not checked out any book.\n";
return;
}
And it's a misleading message (you haven't checked out this book; you may have other books checked out).
We have implemented our own find() here:
for (const auto& patron : m_patrons) {
if (patron.getName() == name && patron.getCardNumber() == cardNumber) return true;
}
return false; | {
"domain": "codereview.stackexchange",
"id": 44757,
"lm_label": 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",
"url": null
} |
c++, beginner
If we define a Patron::operator==(), we could use a standard <algorithms> function here. | {
"domain": "codereview.stackexchange",
"id": 44757,
"lm_label": 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",
"url": null
} |
c++, datetime
Title: Date Checking in C++
Question: I am working on one of my assignments (Hash Tables) for my Data Structures class(1st year), the assignment focuses on OOP and understanding of Hash Tables.
Restrictions:
Usage of raw pointers
C++11 standard
Have to use vectors for my HashTable (can't use std::map)
The goal of this assignment is to make a Covid-19 table, which is capable of reading data from a .csv file and filling the table with those. Besides that, there is supposed to be a UI that allows the user to enter entries manually.
Is this a good (low-level) OOP design? I am not familiar with Polymorphism, Inheritance, and so on just yet. Style tips are always welcome.
run.cpp
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
#include <fstream>
#include <chrono>
#include <ctime>
#include <iomanip>
#include <algorithm>
#include <limits>
#include <thread>
#include <stdexcept>
#include <cctype>
#include <cassert>
#include <atomic>
#include "run.h"
#include "CovidDB.h"
#define LOG
/** 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.
*/
/** @todo
* test and assert
* Clarify what to print
* Make the output neater
*/
/** @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
}; | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
/**
* @brief Displays the menu for user interaction.
*/
void menu() {
std::cout << "\n*** Welcome to the COVID-19 Data Base ***\n\n"
<< "[1]\tCreate a Hash Table with the WHO file\n"
<< "[2]\tAdd a Data entry\n" //segfault
<< "[3]\tGet a Data entry\n"
<< "[4]\tRemove a Data entry\n" //segfault if no entry
<< "[5]\tDisplay HasH Table\n"
<< "[6]\tLog Data [covid_db.log]\n"
<< "[7]\tLog Memory [valgrind.log]\n"
<< "[8]\tQuit\n";
}
/**
* @brief Takes a string and returns a boolean indicating the validity of the month.
*
* @param month The input month as a string.
* @return True if the month is valid, false otherwise.
*/
bool valid_month(std::string month) {
if(month.length() != 1 and month.length() != 2) {
return false;
} else if (std::stoi(month) > 13) {
return false;
} else if (std::stoi(month) < 1) {
return false;
}
return true;
}
/**
* @brief Takes a string and returns a boolean indicating the validity of the day.
*
* @param day The input day as a string.
* @return True if the day is valid, false otherwise.
*/
bool valid_day(std::string day) {
if(day.length() != 1 and day.length() != 2) {
return false;
} else if (std::stoi(day) > 31) {
return false;
} else if (std::stoi(day) < 1) {
return false;
}
return true;
}
/**
* @brief Takes a string reference and returns a boolean indicating the validity of the year.
*
* @param year The input year as a string reference.
* @return True if the year is valid, false otherwise.
*/
bool valid_year(std::string &year) {
if(year.length() == 4) {
year = year[2] + year [3];
return true;
} else if(year.length() != 2) {
return false;
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
/**
* @brief Takes a string reference as an argument and returns a string.
*
* @param date The input date as a string reference.
* @return The processed date as a string.
* IMPORTANT: @invariant user does not enter a word input
*/
//{
/** @bug FIX: future dates weren't getting rejected */
//}
std::string get_date(std::string &date) {
std::string month = "\0";
std::string day = "\0";
std::string year = "\0";
bool is_valid = false;
while (!is_valid) {
std::cout << "[FORMAT: mm/dd/yy][Enter a Date]: ";
std::getline(std::cin, date);
std::size_t month_loc = date.find("/");
std::string month_prev = date.substr(0, month_loc);
if (month_prev[0] == '0') {
month = month_prev[1]; // if preceding 0 -> trim
} else {
month = month_prev; // if single digit -> keep
}
std::string s_str = date.substr(month_loc + 1);
std::size_t day_loc = s_str.find("/");
std::string day_prev = s_str.substr(0, day_loc);
if (day_prev[0] == '0') {
day = day_prev[1];
} else {
day = day_prev;
}
year = s_str.substr(day_loc + 1);
is_valid = valid_day(day) && valid_month(month) && valid_year(year);
//{
/** @brief
* c_ stands for current
* e_ satnds for entered
*/
//}
if (is_valid) {
try {
std::time_t now = std::time(nullptr);
std::tm* c_time = std::localtime(&now);
int c_day = c_time->tm_mday;
int c_month = c_time->tm_mon + 1; // Month is zero-based
int c_year = c_time->tm_year % 100; // Last two digits of the year
const int e_day = std::stoi(day);
const int e_month = std::stoi(month);
const int e_year = std::stoi(year); | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
if (e_year > c_year) {
is_valid = false; // Date is in the future
throw std::invalid_argument("\n[Invalid]\n");
} else if (e_year == c_year) {
if (e_month > c_month) {
is_valid = false; // Date is in the future
throw std::invalid_argument("\n[Invalid]\n");
} else if (e_month == c_month) {
if (e_day > c_day) {
is_valid = false; // Date is in the future
throw std::invalid_argument("\n[Invalid]\n");
}
}
} else {
return month + "/" + day + "/" + year;
}
} catch (const std::exception& error) {
std::cout << error.what();
is_valid = false;
}
}
}
return month + "/" + day + "/" + year;
}
/**
* @brief Takes a string reference as an argument and returns a string.
*
* @param country The input country as a string reference.
* @return The processed country as a string.
*/
std::string get_country(std::string& country) {
while(true) {
std::cout << "[Enter a country]: ";
std::cin >> country;
std::cin.ignore();
try {
//{
//Using lambda expression to check is the input is not numeric
//}
if (!std::all_of(country.begin(), country.end(), [](char c){ return std::isalpha(c); })) {
throw std::invalid_argument("[Input must be a string]\n");
}
std::atomic<bool> is_all_lowercase(false);
is_all_lowercase.store(std::all_of(country.begin(), country.end(), [](char c){ return std::islower(c); }));
if (is_all_lowercase) {
country[0] = std::toupper(country[0]);
std::transform(country.begin()+1, country.end(), country.begin()+1, [](char c){ return std::tolower(c); });
} else {
return country;
}
} catch (const std::exception& e) {
std::cerr << "\nError: " << e.what() << '\n';
country = ""; // Reset the input
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
/**
* @brief Takes an integer reference as an argument and returns an integer.
*
* @param cases The input Covid cases as an integer reference.
* @return The processed Covid cases as an integer.
*/
int get_covid_cases(int &cases) {
typedef std::numeric_limits<int> IntLimits;
const int INT_MAX = IntLimits::max();
std::cout << "[Enter cases]: ";
std::cin >> cases;
try {
if(cases < 0) {
throw std::invalid_argument("[Cases cannot be negative!]");
}
if(cases > INT_MAX) {
throw std::invalid_argument("[Integer overflow!]");
} else {
return cases;
}
} catch (const std::exception& e) {
std::cerr << "\nError: " << e.what() << std::endl;
return 0;
}
return 0;
}
/**
* @brief Takes an integer reference as an argument and returns an integer.
*
* @param deaths The input Covid deaths as an integer reference.
* @return The processed Covid deaths as an integer.
*/
int get_covid_deaths(int &deaths) {
typedef std::numeric_limits<int> IntLimits;
const int INT_MAX = IntLimits::max();
while(true) {
std::cout << "[Enter deaths]: ";
std::cin >> deaths;
try {
if(deaths < 0) {
throw std::invalid_argument("[Cases cannot be negative!]");
}
if(deaths > INT_MAX) {
throw std::invalid_argument("[Integer overflow!]");
} else {
return deaths;
}
} catch (const std::exception& e) {
std::cerr << "\nError: " << e.what() << std::endl;
return 0;
}
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
/**
* @brief Prompts the user to enter a valid intiger coresponding to one of the valus in the menu
* the user is prompted to enter the input again if it's not a number
*
* @return The processed input as an integer.
*/
int get_input() {
int const MIN = 1;
int const MAX = 8;
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 8]");
}
else {
return choice;
}
}
catch (const std::exception& error) {
std::cout << error.what() << std::endl;
std::cout << "[Re-enter]: ";
}
}
}
/** @name goodbye()
* @brief The function prompts the user goodbye
* @remark Handles UI
* @return void-type
*/
void goodbye() {
std::cout << "\n\nGoodbye!\n\n";
}
/**
* @brief Takes a DataEntry* pointer and several arguments (country, date, cases, deaths)
* to set the data.
*
* @param data A pointer to a DataEntry object.
* @param country The country associated with the data.
* @param date The date associated with the data.
* @param cases The number of Covid cases associated with the data.
* @param deaths The number of Covid deaths associated with the data.
*/
void set_data(DataEntry* data, std::string country, std::string date, int cases, int deaths) {
data->set_country(get_country(country));
data->set_date(get_date(date));
data->set_c_cases(get_covid_cases(cases));
data->set_c_deaths(get_covid_deaths(deaths));
} | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
/**
* @brief Executes the main logic of the program in a while(true) loop.
*/
void run() {
/** DECLARATIONS: */
std::cout << std::endl << std::endl << std::flush;
CovidDB data_base;
DataEntry *data = new DataEntry; //#2 allocation (new DataEntry)
std::string country = "\n";
std::string date = "\0";
int cases = 0;
int deaths = 0;
/** DECLARATIONS: */
while(true) {
menu();
switch(get_input()) {
case OPID::ID_1: {
data_base.add_covid_data(COVID_FILE);
break;
}
case OPID::ID_2: {
set_data(data, country, date, cases, deaths);
bool added = data_base.add(data);
if(added) {
std::cout << "\n[Record added]\n";
} else {
std::cout << "\n[Failed to add the entry]\n";
}
break;
}
case OPID::ID_3: {
data_base.fetch_data(data, get_country(country));
break;
}
case OPID::ID_4: {
data_base.remove(get_country(country));
break;
}
case OPID::ID_5: {
data_base.display_table();
break;
}
case OPID::ID_6: {
#ifdef LOG
data_base.log();
#else
std::cout << "\n[Define [LOG macro in run.cpp] to run]\n";
#endif // LOG
break;
}
case OPID::ID_7: {
#ifdef LOG
data_base.log_memory();
std::exit(EXIT_SUCCESS);
#else
std::cout << "\n[Define [LOG macro in run.cpp] to run]\n";
#endif
break;
}
case OPID::ID_8: {
goodbye();
//delete data; //
std::exit(EXIT_SUCCESS);
break;
}
default: {
/** @note do nothing...*/
}
}
}
std::cout << std::endl << std::endl << std::flush;
}
run.h
#include <string>
#include "CovidDB.h"
/** DOCUMENTATION:
* @author Jakob Balkovec
* @file run.cpp [Source Code]
* @note Header file for helper functions
* @remark this file defines a set of helper functions that most get or check parameters
*/
#pragma once | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
#pragma once
/** @brief
* @name get_date: Takes a string reference as an argument and returns a string
* @name get_country: Takes a string reference as an argument and returns a string.
* @name get_country: Takes a string reference as an argument and returns a string.
* @name get_coivd_cases: Takes an integer reference as an argument and returns an integer.
* @name get_covid_deaths: Takes an integer reference as an argument and returns an integer.
*/
std::string get_date(std::string &date);
std::string get_country(std::string &country);
int get_coivd_cases(int &cases);
int get_covid_deaths(int &deaths);
/** @brief
* @name set_data: Takes a DataEntry* pointer and several arguments
* @param (country, date, cases, deaths)
* to set the data.
*/
void set_data(DataEntry* data, std::string country, std::string date, int cases, int deaths);
/** @brief
* @name get_input: Takes no arguments and returns an integer.
* @name goodbye: Takes no arguments and returns void.
* @name menu: Takes no arguments and returns void.
* @name run: Takes no arguments and returns void.
*/
int get_input();
void goodbye();
void menu();
void run();
/** @brief
* @name valid_month: Takes a string and returns a boolean indicating the validity of the month.
* @name valid_day: Takes a string and returns a boolean indicating the validity of the day.
* @name valid_year: Takes a string reference and returns a boolean indicating the validity of */
bool valid_month(std::string);
bool valid_day(std::string);
bool valid_year(std::string &year); | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
/**
* @brief
* @name show_last_compiled
* @param file Name of the file that is being compiled
* @param date Date of when the file was last compiled
* @param time Time of when the file was last compiled
* @param author Author of the code
* @note all params are arrays of chars
*/
inline void show_last_compiled(const char* file, const char* date, const char* time, const char* author) {
std::cout << "\n[" << file << "] " << "Last compiled on [" << date << "] at [" << time << "] by [" << author << "]\n" << std::endl;
}
main.cpp
#include "CovidDB.h"
#include "run.h"
#define AUTHOR "Jakob" //define a macro
/**
* @brief The entry point of the program.
* @return [EXIT_SUCESS], the exit status of the program.
*/
int main() {
show_last_compiled(__FILE__, __DATE__, __TIME__, AUTHOR);
run();
return EXIT_SUCCESS;
}
MakeFile
CC = g++
CFLAGS = -Wall -Werror -std=c++11 -pedantic -O3
SRCS = run.cpp CovidDB.cpp main.cpp
OBJS = $(SRCS:.cpp=.o)
TARGET = main
all: $(TARGET)
$(TARGET): $(OBJS)
$(CC) $(CFLAGS) $(OBJS) -o $(TARGET)
%.o: %.cpp
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -f $(OBJS) $(TARGET)
CovidDB.h
#include <iostream>
#include <string>
#include <vector>
#pragma once
static std::string const COVID_FILE = "WHO-COVID-data.csv";
/** DOCUMENTATION:
* @author Jakob Balkovec
* @file CovidDB.h [Header file]
* @note Header file for DataEntry and CovidDB class
*
* @brief This assigment focuses on using multiple operations regarding HasHTables such as:
* - Insertion
* - Printing
* - Hashing
* - Deletion
* - [File reading]
*
* Those operations were implemented using a DataEntry and a CovidDB class
*/ | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
/**
* @class DataEntry
* @brief DataEntry class represents a single entry of COVID-19 data
* for a particular date and country.
* @note This class is immutable once created.
*/
class DataEntry final {
private:
std::string date;
std::string country;
int c_cases;
int c_deaths;
public:
DataEntry();
/** @note mutators and acessors*/
inline void set_date(std::string set_date) { this->date = set_date;};
inline void set_country(std::string set_country) { this->country = set_country;};
inline void set_c_deaths(int set_c_deaths) { this->c_deaths = set_c_deaths;};
inline void set_c_cases(int set_c_cases) { this->c_cases = set_c_cases;};
inline int get_c_cases() { return c_cases;};
inline int get_c_deaths() { return c_deaths;};
inline std::string get_date() { return date;};
inline std::string get_country() { return country;};
};
/**
* @brief A hash table implementation to store Covid-19 data by country
* @class CovidDB
* @note The hash table size is fixed at 17.
*/
class CovidDB final {
private:
int size = 17;
std::vector<std::vector<DataEntry*>> HashTable;
public:
inline CovidDB() {
HashTable.resize(size);
}
inline void clear() {
for (auto& row : HashTable) {
for (auto& entry : row) {
delete entry;
}
row.clear();
}
HashTable.clear();
HashTable.shrink_to_fit();
///@link https://stackoverflow.com/questions/12587774/destructor-not-being-called
}
inline ~CovidDB() { //handles memory
clear();
std::cout << "\nDESTROYED\n";
}
/** @note Copy constructor */
CovidDB(const CovidDB& other) {
size = other.size;
HashTable.resize(size);
for (int i = 0; i < size; ++i) {
for (const auto& entry : other.HashTable[i]) {
HashTable[i].push_back(new DataEntry(*entry));
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
/** @note Move constructor */
CovidDB(CovidDB&& other) noexcept { //noexcept is necessray -> doesn't throw errors
size = other.size;
HashTable = std::move(other.HashTable);
other.size = 0;
}
/** @note Overloaded assigment operator*/
CovidDB& operator=(const CovidDB& other) {
if (this == &other) {
return *this; // Self-assignment, no work needed
}
// clear the data and resources
for (auto& row : HashTable) {
for (auto& entry : row) {
delete entry;
}
row.clear();
}
HashTable.clear();
HashTable.shrink_to_fit();
// copy the data from the other object
size = other.size;
HashTable.resize(size);
for (int i = 0; i < size; ++i) {
for (const auto& entry : other.HashTable[i]) {
HashTable[i].push_back(new DataEntry(*entry));
}
}
return *this;
}
DataEntry* get(std::string country);
void fetch_data(DataEntry* set, std::string country);
bool add(DataEntry* entry);
void add_covid_data(std::string const COVID_FILE);
int hash(std::string country);
void remove(std::string country);
void display_table();
void log();
void log_memory();
};
CovidDB.h
/** DOCUMENTATION:
* @author Jakob Balkovec
* @file CovidDB.cpp [Driver Code]
* @note Driver code for A4
*
* @brief This assigment focuses on using multiple operations regarding HasHTables such as:
* - Insertion
* - Printing
* - Hashing
* - Deletion
* - [File reading]
*
* Those operations were implemented using a DataEntry and a CovidDB class
*/
#include <string>
#include <cstring>
#include <sstream>
#include <iostream>
#include <fstream>
#include <cassert>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <thread>
#include <cmath>
#include <cstdlib>
#include <unistd.h>
#include <atomic>
#include <sys/types.h>
#include <sys/wait.h>
#include "CovidDB.h"
#define LOG
//#define WAIT | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
#include "CovidDB.h"
#define LOG
//#define WAIT
/**
* @brief Constructs an object of DataEntry type with default parameters
* @return DataEntry Object
*/
DataEntry::DataEntry() {
this->date = "\0";
this->country = "\0";
this->c_cases = 0;
this->c_deaths = 0;
}
/**
* @brief Hashfunction that creates a hash
* @param country std::string entry -> country in the CSV file
* @return Hash
*/
int CovidDB::hash(std::string country) {
int sum = 0;
int count = 0;
for (char c : country) {
sum = sum + ((count + 1) * c);
count++;
}
return sum % size; //returns the hash
}
/**
* @brief Inserts one data entry into the hash table.
* @param entry The DataEntry object to be added
* @return true if record is added, false if record is rejected (date < than current date)
*/
bool CovidDB::add(DataEntry* entry) {
time_t now = time(0);
tm* ltm = localtime(&now);
// DATE FORMAT: mm/dd/yy
std::string current_date_str = std::to_string(1 + ltm->tm_mon) + "/" + std::to_string(ltm->tm_mday) + "/" + std::to_string(ltm->tm_year % 100);
std::istringstream iss(current_date_str);
std::tm current_date = {};
iss >> std::get_time(¤t_date, "%m/%d/%y");
std::tm entry_date = {};
std::istringstream iss2(entry -> get_date());
iss2 >> std::get_time(&entry_date, "%m/%d/%y");
if (mktime(¤t_date) > mktime(&entry_date)) {
std::cout << "[Record rejected]" << std::endl;
return false;
}
int index = hash(entry -> get_country());
assert(index < 17 and index >= 0);
if (HashTable[index].empty()) {
HashTable[index].push_back((entry));
} else {
bool added = false;
for (DataEntry* existing_entry : HashTable[index]) { | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
std::atomic<bool> valid(false);
valid.store(hash(existing_entry->get_country()) == hash(entry->get_country()) &&
existing_entry->get_country() == entry->get_country());
if (valid) {
existing_entry->set_date(entry -> get_date());
existing_entry->set_c_cases(existing_entry->get_c_cases() + entry->get_c_cases());
existing_entry->set_c_deaths(existing_entry->get_c_deaths() + entry->get_c_deaths());
added = true;
delete entry;
break;
}
}
if (!added) {
HashTable[index].push_back(entry);
}
}
return true;
}
/**
* @brief Retrieves a data entry with the specific country name
* @param country The country to search for
* @return The DataEntry object with the matching country name, or NULL if no such entry exists
*/
DataEntry* CovidDB::get(std::string country) {
int index = hash(country);
assert(index < 17);
for (DataEntry* entry : HashTable[index]) {
if (entry->get_country() == country) {
return entry;
}
}
return nullptr;
} | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
/**
* @brief Fetches the data entry for a specific country and assigns it
* to the provided DataEntry pointer.
*
* @param set A pointer to a DataEntry object where the fetched data will be assigned.
* @param country The name of the country to fetch data for.
* @return void
*/
void CovidDB::fetch_data(DataEntry* set, std::string country) {
set = get(country);
if(set == nullptr) {
std::cout << "\n[No entry found for: \"" << country << "\"]\n";
return; //if nullptr don't derefernece
}
char const SPACE = ' ';
std::cout << std::flush;
std::cout << "\n[Date: " << set -> get_date() << "]," << SPACE
<< "[Country: " << set -> get_country() << "]," << SPACE
<< "[Cases: " << set -> get_c_cases() << "]," <<SPACE
<< "[Deaths: " << set -> get_c_deaths() << "]" << SPACE
<< std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
/**
* @brief Removes the data entry with the specific country name
* @param country The country to remove
*/
void CovidDB::remove(std::string country) {
int index = hash(country);
for (auto it = HashTable[index].begin(); it != HashTable[index].end(); ++it) {
if ((*it)->get_country() == country) {
delete *it;
HashTable[index].erase(it);
return;
}
}
std::cout << "\n[No entry found for: " << country << "]" << std::endl;
}
/**
* @brief Prints the contents of the hash table using
* nested for each loops
*/
//{
// @bug when adding 2 entires with the same hash -> SIGSEV
//}
void CovidDB::display_table() {
char const STICK = '|';
bool is_empty = true;
/** @note guard against printing an empty table*/
for(const auto& vec : HashTable) { //if 1D is empty
if(!vec.empty()) {
is_empty = false;
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
if(is_empty) {
std::cout << "\n[Data Base is empty]\n";
return;
}
/** @note guard against printing an empty table*/
std::cout << "\n[Printing Data Base]\n|\n";
for (int i = 0; i < 3; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
std::cout << STICK << std::endl;
}
std::cout << std::flush; //flush buffer
std::string const SPACE = " ";
for(std::vector<DataEntry*> vec : HashTable) {
for(DataEntry* entry : vec) {
if (entry != nullptr) { //guard against dereferencing nullptr
std::cout << std::flush;
std::cout << "[Date: " << entry -> get_date() << "]," << SPACE
<< "[Country: " << entry -> get_country() << "]," << SPACE
<< "[Cases: " << entry -> get_c_cases() << "]," << SPACE
<< "[Deaths: " << entry -> get_c_deaths() << "]"
<< std::endl;
#ifdef WAIT
std::this_thread::sleep_for(std::chrono::milliseconds(100));
#endif //WAIT
}
}
}
std::cout << std::endl;
return;
}
/**
* @brief Logs the contents of the hash table using
* nested for each loops and writes them to a .log file
*/
void CovidDB::log() {
#ifdef LOG
add_covid_data(COVID_FILE); //add data and log
std::ofstream covid_file;
covid_file.open("covid_db.log");
if (covid_file.is_open()) {
covid_file << std::flush; | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
if (covid_file.is_open()) {
covid_file << std::flush;
std::string const SPACE = " ";
covid_file << "\n\n****************************** COIVD DATA LOG ******************************\n\n\n";
for (auto& vec : HashTable) {
for (auto& entry : vec) {
if (entry != nullptr) {
covid_file << "[Date: " << entry->get_date() << "]," << SPACE
<< "[Country: " << entry->get_country() << "]," << SPACE
<< "[Cases: " << entry->get_c_cases() << "]," << SPACE
<< "[Deaths: " << entry->get_c_deaths() << "]"
<< std::endl;
}
}
}
covid_file.close();
} else {
covid_file << "\n[Error opening the file covidDB.log]\n";
std::exit(EXIT_FAILURE);
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "\n------ [Log avalible] ------\n\n";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::exit(EXIT_SUCCESS);
return;
}
#else
std::cout << "\n[Define [LOG macro in CovidDB.cpp] to run]\n";
#endif // LOG
/**
* @brief Reads a CSV file containing COVID data and adds the data to the database.
* @param COVID_FILE The name of the CSV file to read.
* @return void
*/
void CovidDB::add_covid_data(std::string const COVID_FILE) {
std::ifstream file(COVID_FILE);
/** @note measure timne it takes to fetch and process data*/
std::chrono::steady_clock::time_point startTime;
std::chrono::steady_clock::time_point endTime; | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
startTime = std::chrono::steady_clock::now(); //start stopwatch
if (!file) {
std::cout << "\n[File ERROR]\n " << COVID_FILE << std::endl;
std::exit(EXIT_FAILURE);
}
std::cout << std::flush;
std::cout << "\n[Fetching Data]\n";
std::cout << std::flush;
std::string line;
std::getline(file, line); // skip header line
std::string latest_date_str = "11/02/22"; // initialize to an old date
std::tm latest_date = {};
std::istringstream iss(latest_date_str);
iss >> std::get_time(&latest_date, "%m/%d/%y");
while (std::getline(file, line)) {
std::stringstream ss(line);
std::string country, date_str, cases_str, deaths_str;
std::getline(ss, date_str, ',');
std::getline(ss, country, ',');
std::getline(ss, cases_str, ',');
std::getline(ss, deaths_str, ',');
int cases = std::stoi(cases_str);
int deaths = std::stoi(deaths_str);
std::tm entry_date = {};
std::istringstream iss2(date_str);
iss2 >> std::get_time(&entry_date, "%m/%d/%y");
if (mktime(&entry_date) > mktime(&latest_date)) {
latest_date_str = date_str;
latest_date = entry_date;
}
DataEntry* entry = new DataEntry(); //#1 allocation
entry->set_country(country);
entry->set_date(latest_date_str);
entry->set_c_cases(cases);
entry->set_c_deaths(deaths);
add(entry);
}
file.close();
endTime = std::chrono::steady_clock::now(); //stop stopwatch
std::chrono::duration<double> elapsedSeconds = endTime - startTime;
/** @note static cast it to an int and round up*/
auto elapsedSecondsCount = static_cast<int>(std::round(elapsedSeconds.count()));
std::cout << std::flush; //flush isotream buffer
std::cout << "|\n|\n|\n[Data Fetched] [Elapsed Time: " << elapsedSecondsCount << "s]\n" << std::flush;
return;
} | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
/**
* @brief logs memory by running valgrind
*/
void CovidDB::log_memory() {
#ifdef LOG
std::cout << "\n[NOTE]: Please quit the program right after it re-runs with \"Valgrind\"\n";
std::this_thread::sleep_for(std::chrono::seconds(4));
std::string command = "valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --num-callers=20 -s --log-file=valgrind.log ./main";
std::system(command.c_str());
}
#else
std::cout << "\n[Define [LOG macro in CovidDB.cpp] to run]\n";
#endif
``` | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
Answer: Don't ignore the 2 most significant digits of the year, you are re-introducing the Y2K bug. The year can be off by a full century but the code will accept the date.
The get_date() function is way to complex (does too much). The helper functions that you have are about the right size, add some more helper functions. Test the users input in a function, only return from that function when the input is valid.
Rather than using std::endl output lines should be terminated with "\n" for performance reasons. Using std::endl means that you are flushing the output buffer after the output. This is generally not necessary, it also adds a system call to the output.
Rather than call std::exit() in the run() function it is better to return to the main() function. std::exit() should only be used in error cases where there is no possibility of recovery from the error. When writing operating system code always avoid calling std::exit(), it really isn't good to shut down the system.
The enum names could be improved, names like OPID::ID_8: really don't provide self documenting code.
Updated Review 5/28/2023
I have left the previous review comments because they are still valid. The following is based on the updated question with the additional code added.
General Observations
As far as Object Oriented Programming goes, you should learn SOLID.
SOLID is 5 object oriented design principles. SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. This will help you design your objects and classes better. | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
The Single Responsibility Principle - A class should only have a single responsibility, that is, only changes to one part of the software's specification should be able to affect the specification of the class.
The Openβclosed Principle - states software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.
The Liskov Substitution Principle - Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.
The Interface segregation principle - states that no client should be forced to depend on methods it does not use.
The Dependency Inversion Principle - is a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are reversed, thus rendering high-level modules independent of the low-level module implementation details.
You might want to implement the hash table as a separate class with it's own header and C file.
Based on the current code, it is questionable whether this program actually works as intended. If it does not then the question is off-topic for Code Review.
DRY Code
There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.
The following code is repeated in 2 functions, int get_covid_cases() and int get_covid_deaths():
typedef std::numeric_limits<int> IntLimits;
const int INT_MAX = IntLimits::max();
Rather than defining INT_MAX as a constant in 2 different functions define it as a constant for the entire file:
static constexpr int COVID_INT_MAX { std::numeric_limits<int>::max() }; | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
I changed the name of INT_MAX to COVID_INT_MAX to avoid an issue with my compiler (Visual Studio 2022). INT_MAX is already defined in my compiler.
Possible Logic Issues in run.cpp
Both int get_covid_cases(int &) and int get_covid_deaths(int &) have some other common issues:
Both functions return a value in two ways, one in a return value and one in a parameter passed by reference.
It isn't clear that either function needs the try{} catch(){} block.
The prompt in both functions is missing the type of input that is needed (integer).
The while (true) loop in int get_covid_deaths() is not working as expected. The loop will always exit on the first iteration whether the value is correct or not.
In the case of the return methodology pick one, either return a value from the function or alter the parameter value but not both. The code that is calling these functions expects a return value, which is the choice you should make. This is the calling code:
void set_data(DataEntry* data, std::string country, std::string date, int cases, int deaths) {
data->set_country(get_country(country));
data->set_date(get_date(date));
data->set_c_cases(get_covid_cases(cases));
data->set_c_deaths(get_covid_deaths(deaths));
}
The set_data() function in it's current implementation does not need the arguments for country, date, cases or deaths because values of the arguments are never used.
void set_data(DataEntry* data) {
data->set_country(get_country());
data->set_date(get_date());
data->set_c_cases(get_covid_cases());
data->set_c_deaths(get_covid_deaths());
} | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
Magic Numbers
There are Magic Numbers in the function bool CovidDB::add(DataEntry* entry) function (0 and 17), it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.
Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
Assert Statements
The assert() macro is a great debugging tool, but it is only a debugging tool, assert statements are not implemented in the resulting code when debugging is turned off (if the -g flag isn't used).
Inline Function Declarations
In the early days of C++ programming declaring a function as inline was a way to optimize code, this is no longer the case. The C++ compiler uses inline only as a recommendation and may ignore it. The -O2 and -O3 optimization flags produce more optimized code than a programmer generally can. Inline functions can only be inlined if they fit into the cache memory.
Only Include What Is Necessary
The include mechanism used in C++ actually includes the code from the include file, this can lead to increased compile / build times. It is better for many reasons to only include what is necessary to compile.
I have altered run.cpp, run.h and main.cpp to only include what is necessary:
main.cpp
#include <iostream>
#include "run.h"
static void show_last_compiled(const char* file, const char* date, const char* time, const char* author) {
std::cout << "\n[" << file << "] " << "Last compiled on [" << date << "] at [" << time << "] by [" << author << "]\n" << std::endl;
}
#define AUTHOR "Jakob" //define a macro
/**
* @brief The entry point of the program.
* @return [EXIT_SUCESS], the exit status of the program.
*/
int main() {
show_last_compiled(__FILE__, __DATE__, __TIME__, AUTHOR);
run();
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
c++, datetime
run.h
#pragma once
void run();
** Top of run.cpp **
#include <string>
#include <iostream>
#include <vector>
#include <chrono>
#include <algorithm>
#include <limits>
#include <stdexcept>
#include <atomic>
#include "run.h"
#include "CovidDB.h"
#define LOG
Please note there was a lot of code reduction. | {
"domain": "codereview.stackexchange",
"id": 44758,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, datetime",
"url": null
} |
python
Title: Assign unique slugs to set of people. Slugs are as short as possible. (New elements only added to ensure uniqueness.)
Question: I have a Python function that will terminate when some condition is fulfilled.That could happen after the first (easy) step. But more steps (of increasing complexity) may follow.
Below is the simplified example function find_slugs.
For each person in database it finds a slug, which is unique and as short as possible.
To avoid code repetition it was necessary to create the subfunction maybe_finish.
It checks if the slugs are already unique, and returns the result if they are.
Otherwise it prepares the next step by creating blocks_to_refine, and returns None.
Between the steps are conditional returns, contracted to one line:
if maybe_result := maybe_finish(): return maybe_result
In three lines it would look like this:
maybe_result = maybe_finish()
if maybe_result is not None:
return maybe_result
Repeating this line does not seem like an elegant solution to me.
(It is essentially repeating three lines of code again and again.)
I would be interested in different approaches to this example problem.
For the given list of people the result is {0: 'JohnSpam85a', 1: 'JohnSpam85b', 2: 'JohnEggs91', 3: 'JohnEggs92', 4: 'EmmaFish95a', 5: 'EmmaFish95b', 6: 'MaryBeer', 7: 'MaryWine', 8: 'Owen', 9: 'Ruth'}. For the first three it is {0: 'JohnSpam85a', 1: 'JohnSpam85b', 2: 'JohnEggs'}. For the last three {7: 'Mary', 8: 'Owen', 9: 'Ruth'}.
from collections import defaultdict | {
"domain": "codereview.stackexchange",
"id": 44759,
"lm_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
database = {
0: {'name1': 'John', 'name2': 'Spam', 'born': '1985'}, # JohnSpam85a
1: {'name1': 'John', 'name2': 'Spam', 'born': '1985'}, # JohnSpam85b
2: {'name1': 'John', 'name2': 'Eggs', 'born': '1991'}, # JohnEggs91
3: {'name1': 'John', 'name2': 'Eggs', 'born': '1992'}, # JohnEggs92
4: {'name1': 'Emma', 'name2': 'Fish', 'born': '1995'}, # EmmaFish95a
5: {'name1': 'Emma', 'name2': 'Fish', 'born': '1995'}, # EmmaFish95b
6: {'name1': 'Mary', 'name2': 'Beer', 'born': '2000'}, # MaryBeer
7: {'name1': 'Mary', 'name2': 'Wine', 'born': '2000'}, # MaryWine
8: {'name1': 'Owen', 'name2': 'Wine', 'born': '2000'}, # Owen
9: {'name1': 'Ruth', 'name2': 'Milk', 'born': '2000'} # Ruth
}
alphabetical_letters = ['a', 'b', 'c', 'd']
def find_slugs():
def maybe_finish():
# A block is a list of numbers with (currently) the same slug.
slug_to_block = defaultdict(list)
for number, slug in number_to_slug.items():
slug_to_block[slug].append(number)
if len(slug_to_block) == len(database):
return number_to_slug
nonlocal blocks_to_refine
blocks_to_refine = []
for block in slug_to_block.values():
if len(block) > 1:
blocks_to_refine.append(block)
##################################################################
blocks_to_refine = None # created and updated in `maybe_finish`
number_to_slug = dict() # result
# step 1: start with first name
for number, table_row in database.items():
number_to_slug[number] = table_row['name1']
if maybe_result := maybe_finish(): return maybe_result
# step 2: add last name
for block in blocks_to_refine:
for number in block:
number_to_slug[number] += database[number]['name2']
if maybe_result := maybe_finish(): return maybe_result | {
"domain": "codereview.stackexchange",
"id": 44759,
"lm_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
if maybe_result := maybe_finish(): return maybe_result
# step 3: add year of birth
for block in blocks_to_refine:
for number in block:
number_to_slug[number] += database[number]['born'][2:4]
if maybe_result := maybe_finish(): return maybe_result
# step 4: append letter to year of birth
for block in blocks_to_refine:
for i, number in enumerate(block):
number_to_slug[number] += alphabetical_letters[i]
return number_to_slug
Answer: The following is my improvement of the code by 301_Moved_Permanently.
The crucial feature in that answer was the return of a generator by find_duplicates.
But (as mentioned by Matthieu M.) it is not efficient, to check all slugs for duplicates. Instead, the function should refine the duplicates from the last step. That requires using the generator twice: First in the for-loop to append the slugs, and then in the next call of find_duplicates. As generators can only be used once, it is doubled with itertools.tee.
import itertools
from collections import defaultdict
from string import ascii_lowercase as alphabet
flatten = itertools.chain.from_iterable
def double_generator(gen): return itertools.tee(gen, 2)
def find_duplicates(number_to_slug, dup_gen_to_refine=None):
slug_to_numbers = defaultdict(list)
if dup_gen_to_refine is not None:
for number in flatten(dup_gen_to_refine):
slug = number_to_slug[number]
slug_to_numbers[slug].append(number)
else:
for number, slug in number_to_slug.items():
slug_to_numbers[slug].append(number)
for block in slug_to_numbers.values():
if len(block) > 1:
yield block
def find_slugs(database):
number_to_slug = {} # result
# step 1: start with first name
for number, table_row in database.items():
number_to_slug[number] = table_row['name1'] | {
"domain": "codereview.stackexchange",
"id": 44759,
"lm_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
# step 2: add last name
dup_gen = find_duplicates(number_to_slug)
dup_gen_to_append, dup_gen_to_refine = double_generator(dup_gen)
for number in flatten(dup_gen_to_append):
number_to_slug[number] += database[number]['name2']
# step 3: add year of birth
dup_gen = find_duplicates(number_to_slug, dup_gen_to_refine)
dup_gen_to_append, dup_gen_to_refine = double_generator(dup_gen)
for number in flatten(dup_gen_to_append):
number_to_slug[number] += database[number]['born'][2:4]
# step 4: append letter to year of birth
dup_gen = find_duplicates(number_to_slug, dup_gen_to_refine)
dup_gen_to_append, dup_gen_to_refine = double_generator(dup_gen)
for block in dup_gen_to_append:
for letter, number in zip(alphabet, block):
number_to_slug[number] += letter
return number_to_slug
This does not look very elegant, as there is some code duplication in each step.
I tried looping through a list of functions, as suggested by FMc, but for some reason that comes with some cost in performance. (That is fun4. It is not shown here, but on Pastebin.)
I used the following code to generate a database with 112750 rows:
from string import ascii_uppercase as alphabet
db_list = []
for a, b in product(range(5), range(5)):
row = {'name1': alphabet[a], 'name2': alphabet[b], 'born': '2000'}
for _ in range(10):
db_list.append(row)
for a, b, c in product(range(5, 20), range(5, 20), range(100)):
row = {'name1': alphabet[a], 'name2': alphabet[b], 'born': str(1900 + c)}
db_list.append(row)
for i, j in product(range(300), range(300)):
row = {'name1': str(i) + 'x', 'name2': str(j) + 'y', 'born': '2000'}
db_list.append(row)
long_database = {}
for i, row in enumerate(db_list):
long_database[i] = row
The following code is to measure the performance of each approach:
(I modified all functions to take database as an argument, and to use ascii_lowercase.)
from timeit import timeit | {
"domain": "codereview.stackexchange",
"id": 44759,
"lm_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
number_of_repetitions = 100
for i, fun in enumerate([fun0, fun1, fun2, fun3, fun4, fun5]):
long_time = timeit(lambda: fun(database), number=number_of_repetitions)
short_time_str = round(long_time / number_of_repetitions, 3)
print(f'fun{i} took {short_time_str} seconds')
This is the result:
fun0 took 0.125 seconds # my initial code
fun1 took 0.189 seconds # answer by FMc
fun2 took 0.129 seconds # answer by 301_Moved_Permanently
fun3 took 0.104 seconds # this answer
fun4 took 0.136 seconds # like fun1 and fun3 (on Pastebin)
fun5 took 0.102 seconds # improvement by 301_Moved_Permanently (on Pastebin)
fun5 uses with and a class with __enter__ and __exit__. It can be found on Pastebin. | {
"domain": "codereview.stackexchange",
"id": 44759,
"lm_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
} |
javascript
Title: Palindrome test in JavaScript function
Question: I hope you will tell me tips to ask good questions regarding checking my code. Here it's the code and thanks in advance!
const checkPalindrome = str => {
str = str.toLowerCase()
let reverse = str.split('').reverse().join('');
return reverse === str ? true : false;
}
console.log(checkPalindrome('Madam'));
Answer: There isn't much to review here; you did a good job! You've provided the canonical solution to this problem. However, here is slightly revised version of your code with some semantic modifications:
const checkPalindrome = (str) => str.toLowerCase() === str.toLowerCase().split("").reverse().join("");
console.log(checkPalindrome('Madam'));
Some notes:
In JavaScript, you should use double quotes instead of single quotes whenever possible.
The ternary expression ... ? true : false is redundant; the statement preceding the ternary operator will automatically evaluate to one of these values in this order.
Since this function is so small, you don't really need to define the reverse variable; it is very obvious what is happening, especially as the .reverse() method is being called.
Similarly, you can simply chain the toLowerCase() method to each reference of str, instead of redefining that variable.
There should be a space between the definition of checkPalindrome and the console log.
Good job! | {
"domain": "codereview.stackexchange",
"id": 44760,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
c++, overloading, constrained-templates, c++23
Title: Is there a more idiomatic way than this to use template-generic C++23 multidimensional array subscripts?
Question: C++23 is going to add multidimensional array subscript operators to the language, yippee!
Alas, I have not yet come across a way to adapt them to types where the number of dimensions is templated, so I came up with this, using variadic templates, fold expression and concepts:
#include <cstddef>
#include <concepts>
// version with static bounds on the dimensions
template <typename T, std::size_t... DIMS>
struct vec {
template <std::convertible_to<std::size_t>... Is>
requires (sizeof...(Is) == sizeof...(DIMS))
T operator[](Is... indices) { return {}; }
};
// version with only the number of dimensions specified (unbounded)
template <typename T, std::size_t D>
struct nvec {
template <std::convertible_to<std::size_t>... Is>
requires (sizeof...(Is) == D)
T operator[](Is... indices) { return {}; }
};
int main() {
vec<int, 3, 2, 4> foo;
vec<int, 1, 1> bar;
vec<int, 91'000> baz;
vec<int> bung;
nvec<int, 4> bogget;
return foo[2, 3, 1] + bar[0, 1] + baz[120] + bung[] + bogget[1, 2, 3, 4];
}
Note that the actual implementation in both cases is stubbed out (I suppose in practice, I will probably use fold expressions to resolve the indices to the correct location in the 1-D array that actually backs the storage for the things, probably with some bounds-checking for the case of vec<> which has static bounds for all dimensions).
I dunno, this feels slightly unwieldy, but this is the most succinct thing I could come up with that allows template-variadic dimensions. There isn't a more concise way now, is there? | {
"domain": "codereview.stackexchange",
"id": 44761,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, overloading, constrained-templates, c++23",
"url": null
} |
c++, overloading, constrained-templates, c++23
Answer: Yes, this is a perfectly fine way to do it, and it is very concise. It might be instructive to compare this to std::mdspan: its operator[] has a similar overload that takes a parameter pack of indices. However, your code is not doing anything useful. The real question is: how do you convert from multi-dimensional indices into a single offset into the underlying buffer? This should look something like:
template <typename T, std::size_t... DIMS>
struct vec {
template <std::convertible_to<std::size_t>... Is>
requires (sizeof...(Is) == sizeof...(DIMS))
T operator[](Is... indices) {
// Cheat to be able to use a regular for-loop.
static constexpr std::array dims_array{DIMS...};
std::array index_array{indices...};
std::size_t offset = 0;
// The compiler should unroll this.
for (std::size_t i = 0; i < sizeof...(DIMS); ++i) {
offset *= dims_array[i];
offset += index_array[i];
}
return data[offset];
}
private:
static constexpr std::size_t size = (DIMS * ...);
std::vector<T> data{size};
};
It becomes even more complex if you allow for different strides and/or layouts, like std::mdspan does. This complexity is alledgedly one of the reasons why they decided to postpone the proposed std::mdarray to C++26. | {
"domain": "codereview.stackexchange",
"id": 44761,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, overloading, constrained-templates, c++23",
"url": null
} |
python, beginner, python-3.x, strings, formatting
Title: Comma Code - Automate the Boring Stuff with Python
Question: Below is my code for the Comma Code problem from Chapter 4 of Automate the Boring Stuff with Python. Is there anything I can do to make it cleaner?
Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list of values 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 passed to it.
The output of this program could look something like this:
apples, bananas, tofu, and cats
import sys
spam = ['apples', 'bananas', 'tofu', 'cats']
def print_list(list):
for item in list:
if len(list) == 1:
print(list[0])
elif item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
print_list(spam)
Answer: You've got an odd bug with your code.
Given the 8th menu item from the greasy spoon cafΓ©:
spam = ["Spam", "Spam", "Spam", "egg", "Spam"]
You will get:
and Spam
and Spam
and Spam
egg, and Spam
since you are not testing whether you are at the last item in your list, but rather if the current item is the same as the last item in the list.
Testing for a length 1 list should not be done inside the loop of all items; it should be done exactly once, outside the loop. Ie (but still with the above bug):
if len(list) == 1: # Test outside of loop
print(list[0])
else:
for item in list:
if item != list[-1]:
print(item + ', ', end='')
else:
print('and ' + list[-1])
Want you really want to do is print all but the last item in the list one way, and the last item a different way:
# If there are more than 1 items in the list...
if len(list) > 1: | {
"domain": "codereview.stackexchange",
"id": 44762,
"lm_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, formatting",
"url": null
} |
python, beginner, python-3.x, strings, formatting
# Print all but the last item, with a comma & space after each
for item in list[:-1]:
print(item + ', ', end='')
# with "and " printed at the very end, just before ...
print("and ", end='')
# print the last (or only) item in the list.
print(list[-1])
although this still assumes at least one item in the list.
Alternately, you could join() all but the last item, and then add ", and " along with the final item.
msg = list[-1]
if len(list) > 1:
msg = ", ".join(list[:-1]) + ", and " + msg
print(msg)
You are doing import sys, but not using sys anywhere. You can remove the import. | {
"domain": "codereview.stackexchange",
"id": 44762,
"lm_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, formatting",
"url": null
} |
java
Title: BigNumber/BigFraction implementation in Java
Question: I have created a BigFraction alternative to BigInteger and BigDecimal. Name for this class is not quite hammered down yet.
I recently finished a class that taught us about OOP and documentation. We learned about Preconditions and Postconditions, LSP, State Representation, and more. I built this project to show (some of) the fruits of my effort. Special attention was placed to make sure this class was well-documented, as Javadoc was a very big part of that class too.
I welcome and invite any and all input/criticism/comments/etc. Please do not pull punches or limit/exclude for brevity -- I want all feedback and intend to read every word.
Finally, here is the GitHub for it, in case the commit history assists in providing feedback. Nothing is there that hasn't been pasted here (barring some git config files and the jGRASP project containing this code).
https://github.com/davidalayachew/BigNumber
Thank you for your time and help!
BigInteger.java
import java.math.BigInteger;
import java.util.Objects;
/** If you know BigInteger and BigDecimal, think of this as BigFraction. This class is immutable. */
public final class BigNumber
{
/**
*
* The numerator.
*
* Can be any whole number.
* Must always contain the negative symbol if the whole "BigNumber" is negative.
* Cannot be null;
*
*/
private final BigInteger numerator;
/**
*
* The denominator.
*
* Can be any whole number except for zero.
* Must always be unsigned.
* Cannot be null.
*
*/
private final BigInteger denominator;
/**
*
* Constructor.
*
* @param param the new number.
*
*/
public BigNumber(long param)
{
this(BigInteger.valueOf(param), BigInteger.ONE);
} | {
"domain": "codereview.stackexchange",
"id": 44763,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
/**
*
* Constructor.
*
* @param param the new number.
* @throws NullPointerException if parameter is null
*
*/
public BigNumber(BigInteger param)
{
Objects.requireNonNull(param, "parameter cannot be null");
this.numerator = param;
this.denominator = BigInteger.ONE;
}
/**
*
* Constructor.
*
* @param numerator the numerator.
* @param denominator the denominator.
* @throws NullPointerException if numerator or denominator is null
* @throws IllegalArgumentException if denominator is 0
*
*/
public BigNumber(BigInteger numerator, BigInteger denominator)
{
Objects.requireNonNull(numerator, "numerator cannot be null");
Objects.requireNonNull(denominator, "denominator cannot be null");
if (denominator.intValue() == 0)
{
throw new IllegalArgumentException("denominator cannot be 0");
}
this.numerator = isPositive(denominator) ? numerator : numerator.negate();
this.denominator = denominator.abs();
}
/**
*
* Constructor.
*
* @param param the new number.
* @throws NullPointerException if parameter is null
*
*/
public BigNumber(BigNumber param)
{
this(Objects.requireNonNull(param, "BigNumber cannot be null").numerator, param.denominator);
}
/**
*
* Returns the (signed) numerator.
*
* @return the numerator.
*
*/
public BigInteger getNumerator()
{
return this.numerator;
}
/**
*
* Returns the (unsigned) denominator.
*
* @return the denominator.
*
*/
public BigInteger getDenominator()
{
return this.denominator;
} | {
"domain": "codereview.stackexchange",
"id": 44763,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
/**
*
* Returns an equivalent BigNumber, but with the sign changed from positive to negative, or vice versa.
*
* @return a BigNumber that has had its sign flipped
*
*/
public BigNumber negate()
{
return this.multiply(-1);
}
/**
*
* Returns true if positive.
*
* @return the result
*
*/
public boolean isPositive()
{
return isPositive(this.numerator);
}
/**
*
* Returns true if num is >0.
*
* @param num the number we are checking the sign of
* @return boolean result
*
*/
private static boolean isPositive(BigInteger num)
{
return num.signum() > 0;
}
/**
*
* Method to simplify the numerator and denominator before creating a BigNumber from them.
*
* Numerator cannot be null.
* Denominator cannot be null.
* Denominator cannot be 0.
*
* @param numerator the numerator
* @param denominator the denominator
* @return the simplified BigNumber
*
*/
private static BigNumber simplify(BigInteger numerator, BigInteger denominator)
{
final var gcd = numerator.gcd(denominator);
return new BigNumber(numerator.divide(gcd), denominator.divide(gcd));
}
/**
*
* Standard add function.
*
* @param param the number to add.
* @return The answer.
*
*/
public BigNumber add(long param)
{
return this.add(new BigNumber(param));
} | {
"domain": "codereview.stackexchange",
"id": 44763,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
/**
*
* Standard add function.
*
* @param param the number to add.
* @return The answer.
* @throws NullPointerException if parameter is null
*
*/
public BigNumber add(BigNumber param)
{
Objects.requireNonNull(param, "parameter cannot be null");
BigInteger resultNumerator;
BigInteger resultDenominator;
if (this.denominator.equals(param.getDenominator()))
{
resultNumerator = this.numerator.add(param.getNumerator());
resultDenominator = BigInteger.ONE;
}
else
{
//our goal here is to end up with a shared denominator
//So, in order to accomplish that, we will need to do
//that cross multiplication thing that you do to end
//up with the same denominator
BigInteger numerator1 = this.numerator.multiply(param.denominator);
BigInteger numerator2 = param.numerator.multiply(this.denominator);
resultNumerator = numerator1.add(numerator2);
resultDenominator = param.getDenominator().multiply(this.getDenominator());
}
//simplify before we return. We don't want to waste memory when the number can be simplified into something smaller.
return simplify(resultNumerator, resultDenominator);
}
/**
*
* Standard subtract function.
*
* @param param the number to subtract from this.
* @return The answer.
*
*/
public BigNumber subtract(long param)
{
return this.add(new BigNumber(param * -1));
}
/**
*
* Standard subtract function.
*
* @param param the number to subtract from this.
* @return The answer.
*
*/
public BigNumber subtract(BigNumber param)
{
Objects.requireNonNull(param, "BigNumber cannot be null");
return this.add(param.negate());
} | {
"domain": "codereview.stackexchange",
"id": 44763,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
/**
*
* Standard multiply function.
*
* @param param the number to multiply.
* @return The answer.
*
*/
public BigNumber multiply(long param)
{
return this.multiply(new BigNumber(param));
}
/**
*
* Standard multiply function.
*
* @param param the number to multiply.
* @return The answer.
* @throws NullPointerException if parameter is null
*
*/
public BigNumber multiply(BigNumber param)
{
Objects.requireNonNull(param, "parameter cannot be null");
BigInteger resultNumerator = this.numerator.multiply(param.numerator);
BigInteger resultDenominator = this.denominator.multiply(param.denominator);
return simplify(resultNumerator, resultDenominator);
}
/**
*
* Standard divide function.
*
* @param param the number to divide this by.
* @return The answer.
* @throws IllegalArgumentException if param == 0
*
*/
public BigNumber divide(long param)
{
if (param == 0) {
throw new IllegalArgumentException("param cannot be 0"); }
return this.divide(new BigNumber(param));
}
/**
*
* Standard divide function.
*
* @param param the number to divide this by.
* @return The answer.
* @throws NullPointerException if parameter is null
* @throws IllegalArgumentException if param == 0
*
*/
public BigNumber divide(BigNumber param)
{
Objects.requireNonNull(param, "parameter cannot be null");
if (param.numerator.equals(BigInteger.ZERO)) {
throw new IllegalArgumentException("param cannot be 0"); }
return this.multiply(new BigNumber(param.denominator, param.numerator));
}
/** {@inheritDoc} */
public String toString()
{
return this.numerator + " / " + this.denominator;
}
}
Answer: Terminology | {
"domain": "codereview.stackexchange",
"id": 44763,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
}
Answer: Terminology
* Can be any whole number except for zero.
* Must always be unsigned.
* Cannot be null.
Personally I would say that it must be strictly positive. Not just because it's shorter, but I think it's more correct terminology: BigInteger is always signed, because that's a property of the type (it has a sign, always), but some instances of BigInteger are positive and that is what's required here.
That also applies to the other use of "unsigned" in another comment.
BigInteger.intValue()
Note that intValue returns the low 32 bits of the BigInteger. If the full value was zero, then the low 32 bits are also zero of course. But there are more cases in which the low 32 bits are zero even though the full value is not, namely every non-zero multiple of 232.
So this has a bug:
if (denominator.intValue() == 0)
{
throw new IllegalArgumentException("denominator cannot be 0");
}
Namely rejecting some denominators that aren't zero, but whose low 32 bits are zero. This likely won't be detected by unit tests, unless they are specifically aimed at it.
negate
Surely there's a simpler thing to do than multiplying by -1
public BigNumber negate()
{
return this.multiply(-1);
}
Negating a long may not actually negate it
In this code:
public BigNumber subtract(long param)
{
return this.add(new BigNumber(param * -1));
}
There is a bug that happens only when param == Long.MIN_VALUE.
There are two values for which x * -1 == x when x is a long: 0 of course, but also Long.MIN_VALUE. This edge case is pretty typical to miss.
The correct thing to do is converting the value of param either into a BigInteger or straight into a BigNumber and then negating that.
Adding fractions with equal denominators
if (this.denominator.equals(param.getDenominator()))
{
resultNumerator = this.numerator.add(param.getNumerator());
resultDenominator = BigInteger.ONE;
}
Consider that 1/3 + 1/3 is supposed to be 2/3 | {
"domain": "codereview.stackexchange",
"id": 44763,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
rust
Title: Create bash ranges from integer sequences
Question: The following code is meant to generate ranges from arbitrary integer sequences and print them in a bash-like syntax:
main.rs
use ranges::Ranges;
use std::io::stdin;
use std::ops::RangeInclusive;
fn main() {
println!(
"{}",
Ranges::from(read_integers())
.map(range_to_bash_literal)
.collect::<Vec<_>>()
.join(" ")
)
}
fn read_integers() -> impl Iterator<Item = i64> {
stdin()
.lines()
.take_while(|line| line.is_ok())
.map(|line| line.unwrap())
.flat_map(|line| {
line.split_ascii_whitespace()
.map(str::to_owned)
.collect::<Vec<_>>()
})
.map(|line| line.parse::<i64>())
.take_while(|result| result.is_ok())
.map(|result| result.unwrap())
}
fn range_to_bash_literal(range: RangeInclusive<i64>) -> String {
if range.start() == range.end() {
range.start().to_string()
} else {
format!("{{{}..{}}}", range.start(), range.end())
}
}
lib.rs
use std::ops::RangeInclusive;
/// Generate ranges from integer sequences
///
/// # Examples
///
/// ```
/// use std::ops::RangeInclusive;
/// use ranges::Ranges;
///
/// let sequence: Vec<i64> = vec![1, 2, 3, 6, 7, 9, 9, 9, 11, 20, 21, 22, 24, 23, 22];
/// let target: Vec<RangeInclusive<i64>> = vec![1..=3, 6..=7, 9..=9, 9..=9, 9..=9, 11..=11, 20..=22, 24..=22];
/// let ranges: Vec<RangeInclusive<i64>> = Ranges::from(sequence.into_iter()).collect();
///
/// assert_eq!(ranges, target);
/// ```
#[derive(Debug)]
pub struct Ranges<T>
where
T: Iterator<Item = i64>,
{
numbers: T,
start: Option<i64>,
}
#[derive(Eq, PartialEq)]
enum Order {
Descending,
Ascending,
}
impl<T> Ranges<T>
where
T: Iterator<Item = i64>,
{
pub fn new(numbers: T) -> Self {
Self {
numbers,
start: None,
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44764,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
impl<T> Iterator for Ranges<T>
where
T: Iterator<Item = i64>,
{
type Item = RangeInclusive<i64>;
fn next(&mut self) -> Option<Self::Item> {
let mut order: Option<Order> = None;
let mut end: Option<i64> = None;
loop {
match self.numbers.next() {
None => {
return match self.start {
None => None,
Some(start) => {
self.start = None; | {
"domain": "codereview.stackexchange",
"id": 44764,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
match end {
None => Some(start..=start),
Some(end) => Some(start..=end),
}
}
}
}
Some(next) => match self.start {
None => {
self.start = Some(next);
}
Some(start) => match &order {
None => {
if next == end.unwrap_or(start) + 1 {
end = Some(next);
order = Some(Order::Ascending);
} else if next == end.unwrap_or(start) - 1 {
end = Some(next);
order = Some(Order::Descending);
} else {
self.start = Some(next);
return Some(start..=end.unwrap_or(start));
}
}
Some(order) => {
if (order == &Order::Ascending && next == end.unwrap_or(start) + 1)
|| (order == &Order::Descending && next == end.unwrap_or(start) - 1)
{
end = Some(next)
} else {
self.start = Some(next);
return Some(start..=end.unwrap_or(start));
}
}
},
},
}
}
}
}
impl<T> From<T> for Ranges<T>
where
T: Iterator<Item = i64>,
{
fn from(value: T) -> Self {
Self::new(value)
}
}
Usage
$ echo 1 2 3 4 5 6 7 8 9 10 11 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 40 | ~/.cargo/bin/ranges
{1..11} {13..38} 40 | {
"domain": "codereview.stackexchange",
"id": 44764,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
How may I improve the code?
Answer: main.rs
Overall, main.rs looks pretty good, except for performance. There's a lot of intermediaries.
The biggest culprit here is the range_to_bash_literal function, which allocates a new String every single time. Using a custom BashRange structure would allow you to implement the Display trait for it with the same logic as range_to_bash_literal:
impl fmt::Display for BashRange {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
if self.start == self.end {
write!(f, "{}", self.start)
} else {
write!(f, "{{{}..{}}}", self.start, self.end)
}
}
}
Then, we can eliminate the collection into a Vec by using for or for_each, and printing fragments.
And of course, you'll want to buffer stdin/stdout, as otherwise reading/writing can be a bit slowish.
All in all, this means:
fn main() -> Result<(), Box<dyn Error>> {
let mut stdout = io::BufWriter::new(io::stdout().lock());
let mut separator = "";
BashRanges::from(read_integrals())
.try_for_each(|bash| {
let result = write!(stdout, "{separator}{bash}");
separator = " ";
result
})?;
Ok(())
}
And the start of read_integrals will need an io::BufReader::new(io::stdin().lock()).
lib.rs
lib.rs is not quite as idiomatic as it good be, and honestly the logic is hard to follow between the state and the levels of nesting.
Make copyable objects Copy
The Order enum could derive quite a few more traits, in particular Debug (always), and because it's a simple enum: Copy.
If a type is copyable, small, and non-public, there's no reason NOT to make it Copy. Then you don't have to be careful about references, you can just copy it without issues, making your code easier.
Minimally constrain structures
The Ranges structure can exist whether T is an Iterator, or not.
Hence, its definition should be:
struct Ranges<T> {
numbers: T,
start: Option<i64>,
} | {
"domain": "codereview.stackexchange",
"id": 44764,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
This makes it easier to implement operations that care nothing about iterating T, for example equality, display, ...
Different types of loops
Rust has 3 types of loops: loop, while, and for, in decreasing order of freedom.
In general, it's better to use the loop with the least amount of freedom, as it means your readers get higher level semantics and don't need to dive deeper into the iteration structure itself.
In your case, you should be using for:
impl<T> Iterator for Ranges<T>
where
T: Iterator<Item = i64>,
{
type Item = RangeInclusive<i64>;
fn next(&mut self) -> Option<Self::Item> {
let mut order: Option<Order> = None;
let mut end: Option<i64> = None;
for next in &mut self.numbers {
// Former "Some" case logic.
}
// Former "None" case logic.
}
}
Short-circuiting is cool, and so are the APIs.
In Rust, the ? operator will get the value inside an Option or Result, or return from the current function.
Hence, the former "self.start == None" block can be rewritten from:
match self.start {
None => None,
Some(start) => {
self.start = None;
match end {
None => Some(start..=start),
Some(end) => Some(start..=end),
}
}
}
let start = self.start?;
Some(start..=end.unwrap_or(start)) | {
"domain": "codereview.stackexchange",
"id": 44764,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
let start = self.start?;
Some(start..=end.unwrap_or(start))
Note: the assignment self.start = None is pointless whenever self.numbers is a "fused" iterator, which is most of them. If really you want to handle non-fused ones, self.start.take() is better than your current match + assign.
end is weird
Your end variable is declared as an Option, yet every time it's used, it ends up being end.unwrap_or(start).
This means, then, than effectively there's always a good value for it, in all cases it's used. This suggests, thus, than a better way to structure the code should exist. We'll see it later.
Use sub-functions
The logic to determine whether orders match (or not) is scattered throughout next, instead you can create a constructor for Order:
impl Order {
fn new(current: i64, next: i64) -> Option<Order> {
if next == current + 1 {
Some(Order::Ascending)
} else if next == current - 1 {
Some(Order::Descending)
} else {
None
}
}
}
Use if let or let else over match when dealing with Option or Result.
Similar advice to loop: match is the most open-ended form of pattern matching. Instead, when possible, you can use more "constraining" forms, to guide the reader.
Thus, let's rewrite the for loop body:
for next in &mut self.numbers {
let Some(start) = self.start else {
self.start = Some(next);
continue
};
...
}
match on several items at once, to "group" logic.
Matching on tuples is perhaps one of my favorite ways. It cuts down your match + 5 if cases to:
for next in self.numbers {
let Some(start) = self.start else {
self.start = Some(next);
continue
};
let current = end.unwrap_or(start);
let new_order = Order::new(current, next); | {
"domain": "codereview.stackexchange",
"id": 44764,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
let current = end.unwrap_or(start);
let new_order = Order::new(current, next);
match (order, new_order) {
(None, Some(_)) => {
end = Some(next);
order = new_order;
}
(Some(left), Some(right)) if left == right => {
end = Some(next);
}
(_, _) => {
self.start = Some(next);
return Some(start..=current);
}
}
}
Simplicity & Performance
At the moment, the optional self.start in Ranges causes quite a bit of branching.
Looking closer at the state transitions, though, one can observe that it will be set from the first number of numbers, and from then be set until numbers runs out.
This suggests that a simple modification of the constructor of Ranges could simplify the iterator by making Ranges slightly eager:
impl<T> Ranges<T>
where
T: Iterator<Item = i64>,
{
pub fn new(mut numbers: T) -> Self {
let start = numbers.next();
Self { numbers, start }
}
}
Now, we don't need to re-check whether there's a first number at every iteration, as long as self.start not None there was one, and self.start being None will mean we're done.
And because self.start being None means we're done, we can check it first things in next, and otherwise we have a value to initialize end with, and do away with all the end.unwrap_or(start).
This gives us:
impl<T> Iterator for Ranges<T>
where
T: Iterator<Item = i64>,
{
type Item = RangeInclusive<i64>;
fn next(&mut self) -> Option<Self::Item> {
let start = self.start?;
let mut order: Option<Order> = None;
let mut end = start;
for next in &mut self.numbers {
let new_order = Order::new(end, next); | {
"domain": "codereview.stackexchange",
"id": 44764,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
for next in &mut self.numbers {
let new_order = Order::new(end, next);
match (order, new_order) {
(None, Some(_)) => {
end = next;
order = new_order;
}
(Some(left), Some(right)) if left == right => {
end = next;
}
(_, _) => {
self.start = Some(next);
return Some(start..=end);
}
}
}
// Just one last item for the road, and from then on
// calling `next` will return `None`.
self.start = None;
Some(start..=end)
}
}
A lot more concise, no?
Disclaimer: not tested, so... the conciseness may hide defects! | {
"domain": "codereview.stackexchange",
"id": 44764,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
c++, beginner, c++11, hash-map, homework
Title: Covid Data Base Hash Map in C++
Question: This is a follow up question to Date Checking in C++
I have these two function prototypes:
void CovidDB::add_covid_data(std::string const COVID_FILE)
void CovidDB::add_rehashed_data(std::string const COVID_FILE)
both essentially do the same thing except that one re_hashes the data before logging it to a .log file. I've heard about function pointers but was never really comfortable using them. Is there an STL container or something that would help me in this case?
Is the stuff I am doing with defining "random" macros such as LOG or WAIT bad practice?
I would like to know if there is anything that needs significant improvement, and if there is any other way of documenting code. One of my professors introduced me to doxygen but I found that it takes me a lot longer than just
// {
// desc:
// pre:
// post:
// }
I would also be very grateful if someone could point me on how to log errors without creating a logging class. Is there a library for that?
Edit: I am very familiar with Python, but I was forced to start using C++ in Data Structures (class I am taking right now), that's why I added the beginner tag.
Here is the full code:
run.h
#include <string>
#include "CovidDB.h"
/** DOCUMENTATION:
* @author Jakob Balkovec
* @file run.cpp [Source Code]
* @note Header file for helper functions
* @remark this file defines a set of helper functions that most get or check parameters
*/
#pragma once | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
#pragma once
/** @brief
* @name get_date: Takes a string reference as an argument and returns a string
* @name get_country: Takes a string reference as an argument and returns a string.
* @name get_country: Takes a string reference as an argument and returns a string.
* @name get_coivd_cases: Takes an integer reference as an argument and returns an integer.
* @name get_covid_deaths: Takes an integer reference as an argument and returns an integer.
*/
std::string get_date();
std::string get_country();
int get_coivd_cases();
int get_covid_deaths();
/** @brief
* @name set_data: Takes a DataEntry* pointer and several arguments
* @param (country, date, cases, deaths)
* to set the data.
*/
void set_data(DataEntry* data, std::string country, std::string date, int cases, int deaths);
/** @brief
* @name get_input: Takes no arguments and returns an integer.
* @name goodbye: Takes no arguments and returns void.
* @name menu: Takes no arguments and returns void.
* @name run: Takes no arguments and returns void.
*/
int get_input();
void goodbye();
void menu();
void run();
/** @brief
* @name valid_month: Takes a string and returns a boolean indicating the validity of the month.
* @name valid_day: Takes a string and returns a boolean indicating the validity of the day.
* @name valid_year: Takes a string reference and returns a boolean indicating the validity of */
bool valid_month(std::string);
bool valid_day(std::string);
bool valid_year(std::string &year);
run.cpp
#include <string>
#include <iostream>
#include <vector>
#include <chrono>
#include <algorithm>
#include <limits>
#include <stdexcept>
#include <thread>
#include <atomic>
#include "run.h"
#include "CovidDB.h"
#define LOG
typedef std::numeric_limits<int> int_limits;
static int constexpr INT_MAX = int_limits::max(); | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
typedef std::numeric_limits<int> int_limits;
static int constexpr INT_MAX = int_limits::max();
/** DOCUMENTATION:
* @author Jakob Balkovec
* @file assignment4.cpp [Driver Code]
* @note Driver code for A4
*
* @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.
*/
/** @todo
* test and assert
* Clarify what to print
* Make the output neater
*/
/** @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
};
/**
* @brief Displays the menu for user interaction.
*/
void menu() {
std::cout << "\n*** Welcome to the COVID-19 Data Base ***\n\n"
<< "[1]\tCreate a Hash Table with the WHO file\n"
<< "[2]\tAdd a Data entry\n"
<< "[3]\tGet a Data entry\n"
<< "[4]\tRemove a Data entry\n"
<< "[5]\tDisplay HasH Table\n"
<< "[6]\tRehash Table\n"
<< "[7]\tLog Data [covid_db.log]\n"
<< "[8]\tLog Re-hashed Data [rehash_covid_db.log]\n"
<< "[9]\tClear screen\n"
<< "[10]\tQuit\n";
}
/**
* @brief Takes a string and returns a boolean indicating the validity of the month.
*
* @param month The input month as a string.
* @return True if the month is valid, false otherwise.
*/
bool valid_month(std::string month) {
if(month.length() != 1 and month.length() != 2) {
return false;
} else if (std::stoi(month) > 13) {
return false;
} else if (std::stoi(month) < 1) {
return false;
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
/**
* @brief Takes a string and returns a boolean indicating the validity of the day.
*
* @param day The input day as a string.
* @return True if the day is valid, false otherwise.
*/
bool valid_day(std::string day) {
if(day.length() != 1 and day.length() != 2) {
return false;
} else if (std::stoi(day) > 31) {
return false;
} else if (std::stoi(day) < 1) {
return false;
}
return true;
}
/**
* @brief Takes a string reference and returns a boolean indicating the validity of the year.
*
* @param year The input year as a string reference.
* @return True if the year is valid, false otherwise.
*/
bool valid_year(std::string &year) {
if(year.length() == 4) {
year = year[2] + year [3];
return true;
} else if(year.length() != 2) {
return false;
}
return true;
}
/**
* @brief Takes no parameters and returns a string.
* @return The processed date as a string.
* IMPORTANT: @invariant user does not enter a word input
*/
std::string get_date() {
std::string date = "\0";
std::string month = "\0";
std::string day = "\0";
std::string year = "\0";
bool is_valid = false;
while (!is_valid) {
std::cout << "[FORMAT: mm/dd/yy][Enter a Date]: ";
std::getline(std::cin, date);
std::size_t month_loc = date.find("/");
std::string month_prev = date.substr(0, month_loc);
if (month_prev[0] == '0') {
month = month_prev[1]; // if preceding 0 -> trim
} else {
month = month_prev; // if single digit -> keep
}
std::string s_str = date.substr(month_loc + 1);
std::size_t day_loc = s_str.find("/");
std::string day_prev = s_str.substr(0, day_loc);
if (day_prev[0] == '0') {
day = day_prev[1];
} else {
day = day_prev;
}
year = s_str.substr(day_loc + 1);
is_valid = valid_day(day) && valid_month(month) && valid_year(year); | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
//{
/** @brief
* c_ stands for current
* e_ satnds for entered
*/
//}
if (is_valid) {
try {
std::time_t now = std::time(nullptr);
std::tm* c_time = std::localtime(&now);
int c_day = c_time->tm_mday;
int c_month = c_time->tm_mon + 1; // Month is zero-based
int c_year = c_time->tm_year % 100; // Last two digits of the year
const int e_day = std::stoi(day);
const int e_month = std::stoi(month);
const int e_year = std::stoi(year);
if (e_year > c_year) {
is_valid = false; // Date is in the future
throw std::invalid_argument("\n[Invalid]\n");
} else if (e_year == c_year) {
if (e_month > c_month) {
is_valid = false; // Date is in the future
throw std::invalid_argument("\n[Invalid]\n");
} else if (e_month == c_month) {
if (e_day > c_day) {
is_valid = false; // Date is in the future
throw std::invalid_argument("\n[Invalid]\n");
}
}
} else {
return month + "/" + day + "/" + year;
}
} catch (const std::exception& error) {
std::cout << error.what();
is_valid = false;
}
}
}
return month + "/" + day + "/" + year;
}
/**
* @brief Takes no arguments and returns a string.
* @return The processed country as a string.
*/
std::string get_country() {
std::string country;
while (true) {
std::cout << "[Enter a country]: ";
std::cin >> country;
std::cin.ignore();
if (std::all_of(country.begin(), country.end(), [](char c) { return std::isalpha(c); })) {
bool is_all_lowercase = std::all_of(country.begin(), country.end(), [](char c) { return std::islower(c); }); | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
if (is_all_lowercase) {
country[0] = std::toupper(country[0]);
std::transform(country.begin() + 1, country.end(), country.begin() + 1, [](char c) { return std::tolower(c); });
}
return country;
} else {
std::cout << "[Input must be a string]\n";
country = ""; // Reset the input
}
}
}
/**
* @brief Takes no parameters and returns an integer.
* @return The processed Covid cases as an integer.
*/
int get_covid_cases() {
int deaths;
while (true) {
std::cout << "[Enter cases]: ";
std::cin >> deaths;
if (deaths >= 0) {
break;
} else {
std::cout << "[invalid input]\n";
// clear the input stream and ignore any remaining characters
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
return deaths;
}
/**
* @brief Takes no parameters and returns an integer.
* @return The processed Covid deaths as an integer.
*/
int get_covid_deaths() {
int deaths;
while (true) {
std::cout << "[Enter deaths]: ";
std::cin >> deaths;
if (deaths >= 0) {
break;
} else {
std::cout << "[invalid input]\n";
// clear the input stream and ignore any remaining characters
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
return deaths;
} | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
/**
* @brief Prompts the user to enter a valid intiger coresponding to one of the valus in the menu
* the user is prompted to enter the input again if it's not a number
*
* @return The processed input as an integer.
*/
int get_input() {
int const MIN = 1;
int const MAX = 10;
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 8]");
}
else {
return choice;
}
}
catch (const std::exception& error) {
std::cout << error.what() << std::endl;
std::cout << "[Re-enter]: ";
}
}
}
/** @name goodbye()
* @brief The function prompts the user goodbye
* @remark Handles UI
* @return void-type
*/
void goodbye() {
std::cout << "\n\nGoodbye!\n\n";
}
/**
* @brief clears screen
*/
static inline void clear_screen() {
#define SLEEP std::this_thread::sleep_for(std::chrono::milliseconds(500))
SLEEP;
std::system("clear");
SLEEP;
}
/**
* @brief Takes a DataEntry* pointer and sets it's data
* @param data A pointer to a DataEntry object.
*/
void set_data(DataEntry* data) {
data->set_country(get_country());
data->set_date(get_date());
data->set_c_cases(get_covid_cases());
data->set_c_deaths(get_covid_deaths());
} | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
/**
* @brief Executes the main logic of the program in a while(true) loop.
*/
void run() {
/** DECLARATIONS: */
std::cout << std::endl << std::endl << std::flush;
CovidDB data_base(17);
DataEntry *data = new DataEntry();
/** DECLARATIONS: */
while(true) {
menu();
switch(get_input()) {
case OPID::ID_1: {
data_base.add_covid_data(COVID_FILE);
break;
}
case OPID::ID_2: {
set_data(data);
bool added = data_base.add(data);
if(added) {
std::cout << "\n[Record added]\n";
} else {
std::cout << "\n[Failed to add the entry]\n";
}
break;
}
case OPID::ID_3: {
data_base.fetch_data(data, get_country());
break;
}
case OPID::ID_4: {
data_base.remove(get_country());
break;
}
case OPID::ID_5: {
data_base.display_table();
break;
}
case OPID::ID_6: {
data_base.rehash();
break;
}
case OPID::ID_7: {
#ifdef LOG
data_base.log();
#else
std::cout << "\n[Define [LOG macro in run.cpp] to run]\n";
#endif // LOG
break;
}
case OPID::ID_8: {
#ifdef LOG
data_base.log_rehashed();
#else
std::cout << "\n[Define [LOG macro in run.cpp] to run]\n";
#endif // LOG
break;
}
case OPID::ID_9: {
clear_screen();
break;
}
case OPID::ID_10: {
goodbye();
delete data;
std::exit(EXIT_SUCCESS);
break;
}
default: {
/** @note do nothing...*/
}
}
}
std::cout << std::endl << std::endl << std::flush;
}
main.cpp
#include <iostream>
#include "run.h" | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
main.cpp
#include <iostream>
#include "run.h"
/**
* @brief
* @name show_last_compiled
* @param file Name of the file that is being compiled
* @param date Date of when the file was last compiled
* @param time Time of when the file was last compiled
* @param author Author of the code
* @note all params are arrays of chars
*/
static inline void show_last_compiled(const char* file, const char* date, const char* time, const char* author) {
std::cout << "\n[" << file << "] " << "Last compiled on [" << date << "] at [" << time << "] by [" << author << "]\n" << std::endl;
}
#define AUTHOR "Jakob" //define a macro
/**
* @brief The entry point of the program.
* @return [EXIT_SUCESS], the exit status of the program.
*/
int main() {
show_last_compiled(__FILE__, __DATE__, __TIME__, AUTHOR);
run();
return EXIT_SUCCESS;
}
CovidDB.cpp
/** DOCUMENTATION:
* @author Jakob Balkovec
* @file CovidDB.cpp [Driver Code]
* @note Driver code for A4
*
* @brief This assigment focuses on using multiple operations regarding HasHTables such as:
* - Insertion
* - Printing
* - Hashing
* - Deletion
* - [File reading]
*
* Those operations were implemented using a DataEntry and a CovidDB class
*/
#include <string>
#include <cstring>
#include <sstream>
#include <iostream>
#include <fstream>
#include <cassert>
#include <ctime>
#include <chrono>
#include <iomanip>
#include <thread>
#include <cmath>
#include <cstdlib>
#include <unistd.h>
#include <atomic>
#include <sys/types.h>
#include <sys/wait.h>
#include <algorithm>
#include "CovidDB.h"
#define LOG
//#define WAIT //-> for submmission uncomment
/**
* @brief Constructs an object of DataEntry type with default parameters
* @return DataEntry Object
*/
DataEntry::DataEntry() {
this->date = "\0";
this->country = "\0";
this->c_cases = 0;
this->c_deaths = 0;
} | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
/**
* @brief Hashfunction that creates a hash
* @param country std::string entry -> country in the CSV file
* @return Hash
*/
int CovidDB::hash(std::string country) {
int sum = 0;
int count = 0;
for (char c : country) {
sum = sum + ((count + 1) * c);
count++;
}
return sum % size; //returns the hash
}
int CovidDB::re_hash_key(std::string country) {
int sum = 0;
int count = 0;
for (char c : country) {
sum = sum + ((count + 1) * c);
count++;
}
return sum % size; //returns the new hash
}
/**
* @brief Re-Hashfunction that rehashes the whole table
*/
void CovidDB::rehash() {
auto is_prime = [](int num) {
if (num <= 1)
return false;
for (int i = 2; i <= std::sqrt(num); ++i) {
if (num % i == 0)
return false;
}
return true;
};
auto find_next_prime = [&is_prime](int num) {
while (true) {
if (is_prime(num))
return num;
++num;
}
};
int new_size = size * 2;
int new_prime_size = find_next_prime(new_size);
// Create a new hash table with the new size
CovidDB new_table(new_prime_size);
// Rehash all entries from the original table to the new table
for (std::vector<DataEntry*>& row : HashTable) {
for (DataEntry* entry : row) {
if (entry != nullptr) {
int re_hash_i = re_hash_key(entry->get_country());
new_table.HashTable[re_hash_i].push_back(entry);
}
}
}
for(auto row : HashTable) {
row.clear();
}
HashTable.clear();
HashTable = std::move(new_table.HashTable);
size = new_prime_size;
#ifdef LOG
std::cout << "[LOG]: Table rehashed. New table size: " << size << std::endl;
#endif //LOG
return;
} | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
/**
* @brief Inserts one data entry into the hash table.
* @param entry The DataEntry object to be added
* @return true if record is added, false if record is rejected (date < than current date)
*/
bool CovidDB::add(DataEntry* entry) {
time_t now = time(0);
tm* ltm = localtime(&now);
// DATE FORMAT: mm/dd/yy
std::string current_date_str = std::to_string(1 + ltm->tm_mon) + "/" + std::to_string(ltm->tm_mday) + "/" + std::to_string(ltm->tm_year % 100);
std::istringstream iss(current_date_str);
std::tm current_date = {};
iss >> std::get_time(¤t_date, "%m/%d/%y");
std::tm entry_date = {};
std::istringstream iss2(entry -> get_date());
iss2 >> std::get_time(&entry_date, "%m/%d/%y");
if (mktime(¤t_date) > mktime(&entry_date)) {
std::cout << "[Record rejected]" << std::endl;
return false;
}
int index = hash(entry -> get_country());
if (HashTable[index].empty()) {
HashTable[index].push_back((entry));
} else {
bool added = false;
for (DataEntry* existing_entry : HashTable[index]) {
std::atomic<bool> valid(false);
valid.store(hash(existing_entry->get_country()) == hash(entry->get_country()) &&
existing_entry->get_country() == entry->get_country());
if (valid) {
existing_entry->set_date(entry -> get_date());
existing_entry->set_c_cases(existing_entry->get_c_cases() + entry->get_c_cases());
existing_entry->set_c_deaths(existing_entry->get_c_deaths() + entry->get_c_deaths());
added = true;
//delete entry;
break;
}
}
if (!added) {
HashTable[index].push_back(entry);
}
}
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
/**
* @brief Retrieves a data entry with the specific country name
* @param country The country to search for
* @return The DataEntry object with the matching country name, or NULL if no such entry exists
*/
DataEntry* CovidDB::get(std::string country) {
int index = hash(country);
assert(index < 17);
for (DataEntry* entry : HashTable[index]) {
if (entry->get_country() == country) {
return entry;
}
}
return nullptr;
}
/**
* @brief Fetches the data entry for a specific country and assigns it
* to the provided DataEntry pointer.
*
* @param set A pointer to a DataEntry object where the fetched data will be assigned.
* @param country The name of the country to fetch data for.
* @return void
*/
void CovidDB::fetch_data(DataEntry* set, std::string country) {
set = get(country);
if(set == nullptr) {
std::cout << "\n[No entry found for: \"" << country << "\"]\n";
return; //if nullptr don't derefernece
}
std::cout << set << std::endl;
}
/**
* @brief Removes the data entry with the specific country name
* @param country The country to remove
*/
void CovidDB::remove(std::string country) {
int index = hash(country);
for (auto it = HashTable[index].begin(); it != HashTable[index].end(); ++it) {
if ((*it)->get_country() == country) {
delete *it;
HashTable[index].erase(it);
return;
}
}
std::cout << "\n[No entry found for: " << country << "]" << std::endl;
}
/**
* @brief Prints the contents of the hash table using
* nested for each loops
*/
//{
// @bug when adding 2 entires with the same hash -> SIGSEV
//}
void CovidDB::display_table() const {
char const STICK = '|';
bool is_empty = true;
/** @note guard against printing an empty table*/
for(const auto& vec : HashTable) { //if 1st dimension is empty
if(!vec.empty()) {
is_empty = false;
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
if(is_empty) {
std::cout << "\n[Data Base is empty]\n";
return;
}
/** @note guard against printing an empty table*/
std::cout << "\n[Printing Data Base]\n|\n";
for (int i = 0; i < 3; i++) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
std::cout << STICK << std::endl;
}
std::cout << std::flush; //flush buffer
std::string const SPACE = " ";
for(std::vector<DataEntry*> vec : HashTable) {
for(DataEntry* entry : vec) {
if (entry != nullptr) { //guard against dereferencing nullptr
std::cout << std::flush;
std::cout << entry << std::endl;
}
}
}
std::cout << std::endl;
return;
}
/**
* @brief Logs the contents of the hash table using
* nested for each loops and writes them to a .log file
*/
void CovidDB::log() {
#ifdef LOG
add_covid_data(COVID_FILE); //add data and log
std::ofstream covid_file;
covid_file.open("covid_db.log");
if (covid_file.is_open()) {
covid_file << std::flush; | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
if (covid_file.is_open()) {
covid_file << std::flush;
std::string const SPACE = " ";
covid_file << "\n\n****************************** COIVD DATA LOG ******************************\n\n\n";
for (auto& vec : HashTable) {
for (auto& entry : vec) {
if (entry != nullptr) {
covid_file << "[Date: " << entry->get_date() << "]," << SPACE
<< "[Country: " << entry->get_country() << "]," << SPACE
<< "[Cases: " << entry->get_c_cases() << "]," << SPACE
<< "[Deaths: " << entry->get_c_deaths() << "]"
<< std::endl;
}
}
}
covid_file.close();
} else {
covid_file << "\n[Error opening the file covidDB.log]\n";
std::exit(EXIT_FAILURE);
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "\n------ [Log avalible] ------\n\n";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::exit(EXIT_SUCCESS);
return;
}
#else
std::cout << "\n[Define [LOG macro in CovidDB.cpp] to run]\n";
#endif // LOG
/**
* @brief Logs re-hashed data
*/
void CovidDB::log_rehashed() {
#ifdef LOG
add_covid_data(COVID_FILE); //add data and log
std::ofstream covid_file;
covid_file.open("rehash_covid_db.log");
if (covid_file.is_open()) {
covid_file << std::flush; | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
if (covid_file.is_open()) {
covid_file << std::flush;
std::string const SPACE = " ";
covid_file << "\n\n************************** REHASHED COIVD DATA LOG **************************\n\n\n";
for (auto& vec : HashTable) {
for (auto& entry : vec) {
if (entry != nullptr) {
//use of overloaded << ostream operator
covid_file << entry << std::endl;
}
}
}
covid_file.close();
} else {
covid_file << "\n[Error opening the file rehash_covidDB.log]\n";
std::exit(EXIT_FAILURE);
}
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << "\n------ [Rehash Log avalible] ------\n\n";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::exit(EXIT_SUCCESS);
return;
}
#else
std::cout << "\n[Define [LOG macro in CovidDB.cpp] to run]\n";
#endif // LOG
/**
* @brief Reads a CSV file containing COVID data and adds the data to the database.
* @param COVID_FILE The name of the CSV file to read.
* @return void
*/
void CovidDB::add_covid_data(std::string const COVID_FILE) {
std::ifstream file(COVID_FILE);
// Measure time it takes to fetch and process data
std::chrono::steady_clock::time_point start_time;
std::chrono::steady_clock::time_point end_time;
start_time = std::chrono::steady_clock::now(); // Start stopwatch
if (!file) {
std::cout << "\n[File ERROR]\n " << COVID_FILE << std::endl;
std::exit(EXIT_FAILURE);
}
std::cout << "\n[Fetching Data]\n";
std::string line;
std::getline(file, line); // Skip header line
std::string latest_date_str = "11/02/22"; // Initialize to an old date
std::tm latest_date = {};
std::istringstream iss(latest_date_str);
iss >> std::get_time(&latest_date, "%m/%d/%y");
// Get the total number of lines in the file
std::ifstream count_lines(COVID_FILE);
int total_lines = std::count(std::istreambuf_iterator<char>(count_lines), std::istreambuf_iterator<char>(), '\n');
count_lines.close(); | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
int progress_interval = total_lines / 10; // Update progress every 10% of the total lines
int current_line = 0;
// Progress bar variables
int progress_bar_width = 40;
while (std::getline(file, line)) {
std::stringstream ss(line);
std::string country, date_str, cases_str, deaths_str;
std::getline(ss, date_str, ',');
std::getline(ss, country, ',');
std::getline(ss, cases_str, ',');
std::getline(ss, deaths_str, ',');
int cases = std::stoi(cases_str);
int deaths = std::stoi(deaths_str);
std::tm entry_date = {};
std::istringstream iss2(date_str);
iss2 >> std::get_time(&entry_date, "%m/%d/%y");
if (mktime(&entry_date) > mktime(&latest_date)) {
latest_date_str = date_str;
latest_date = entry_date;
}
DataEntry* entry = new DataEntry();
entry->set_country(country);
entry->set_date(latest_date_str);
entry->set_c_cases(cases);
entry->set_c_deaths(deaths);
add(entry);
current_line++;
// Update progress bar
if (current_line % progress_interval == 0 || current_line == total_lines) {
int progress = static_cast<int>((static_cast<double>(current_line) / total_lines) * 100);
std::cout << "\r[";
int completed_width = progress_bar_width * progress / 100;
for (int i = 0; i < progress_bar_width; ++i) {
if (i < completed_width) {
std::cout << "#";
} else {
std::cout << " ";
}
}
std::cout << "] [" << progress << "%]" << std::flush;
}
}
file.close();
end_time = std::chrono::steady_clock::now(); // Stop stopwatch
std::chrono::duration<double> elapsedSeconds = end_time - start_time;
// Static cast elapsed time to an int and round up
auto elapsedSecondsCount = static_cast<int>(std::round(elapsedSeconds.count()));
std::cout << "\n[Data Fetched] [Elapsed Time: " << elapsedSecondsCount << "s]\n\n";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
return;
} | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
/**
* @brief Reads a CSV file containing COVID data and adds the new data to the database.
* @param COVID_FILE The name of the CSV file to read.
* @return void
*/
void CovidDB::add_rehashed_data(std::string const COVID_FILE) {
std::ifstream file(COVID_FILE);
// Measure time it takes to fetch and process data
std::chrono::steady_clock::time_point start_time;
std::chrono::steady_clock::time_point end_time;
start_time = std::chrono::steady_clock::now(); // Start stopwatch
if (!file) {
std::cout << "\n[File ERROR]\n " << COVID_FILE << std::endl;
std::exit(EXIT_FAILURE);
}
std::cout << "\n[Fetching Data]\n";
std::string line;
std::getline(file, line); // Skip header line
std::string latest_date_str = "11/02/22"; // Initialize to an old date
std::tm latest_date = {};
std::istringstream iss(latest_date_str);
iss >> std::get_time(&latest_date, "%m/%d/%y");
// Get the total number of lines in the file
std::ifstream count_lines(COVID_FILE);
int total_lines = std::count(std::istreambuf_iterator<char>(count_lines), std::istreambuf_iterator<char>(), '\n');
count_lines.close();
int progress_interval = total_lines / 10; // Update progress every 10% of the total lines
int current_line = 0;
// Progress bar variables
int progress_bar_width = 40;
while (std::getline(file, line)) {
std::stringstream ss(line);
std::string country, date_str, cases_str, deaths_str;
std::getline(ss, date_str, ',');
std::getline(ss, country, ',');
std::getline(ss, cases_str, ',');
std::getline(ss, deaths_str, ',');
int cases = std::stoi(cases_str);
int deaths = std::stoi(deaths_str);
std::tm entry_date = {};
std::istringstream iss2(date_str);
iss2 >> std::get_time(&entry_date, "%m/%d/%y");
if (mktime(&entry_date) > mktime(&latest_date)) {
latest_date_str = date_str;
latest_date = entry_date;
} | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
DataEntry* entry = new DataEntry();
entry->set_country(country);
entry->set_date(latest_date_str);
entry->set_c_cases(cases);
entry->set_c_deaths(deaths);
add(entry);
rehash();
current_line++;
// Update progress bar
if (current_line % progress_interval == 0 || current_line == total_lines) {
int progress = static_cast<int>((static_cast<double>(current_line) / total_lines) * 100);
std::cout << "\r[";
int completed_width = progress_bar_width * progress / 100;
for (int i = 0; i < progress_bar_width; ++i) {
if (i < completed_width) {
std::cout << "#";
} else {
std::cout << " ";
}
}
std::cout << "] [" << progress << "%]" << std::flush;
}
}
file.close();
end_time = std::chrono::steady_clock::now(); // Stop stopwatch
std::chrono::duration<double> elapsedSeconds = end_time - start_time;
// Static cast elapsed time to an int and round up
auto elapsedSecondsCount = static_cast<int>(std::round(elapsedSeconds.count()));
std::cout << "\n[Data Fetched] [Elapsed Time: " << elapsedSecondsCount << "s]\n\n";
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
return;
}
CovidDB.h
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#pragma once
static std::string const COVID_FILE = "WHO-COVID-data.csv";
/** DOCUMENTATION:
* @author Jakob Balkovec
* @file CovidDB.h [Header file]
* @note Header file for DataEntry and CovidDB class
*
* @brief This assigment focuses on using multiple operations regarding HasHTables such as:
* - Insertion
* - Printing
* - Hashing
* - Deletion
* - [File reading]
*
* Those operations were implemented using a DataEntry and a CovidDB class
*/ | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
/**
* @class DataEntry
* @brief DataEntry class represents a single entry of COVID-19 data
* for a particular date and country.
* @note This class is immutable once created.
*/
class DataEntry final {
private:
std::string date;
std::string country;
int c_cases;
int c_deaths;
public:
DataEntry();
/** @note mutators and acessors*/
inline void set_date(std::string set_date) { this->date = set_date;};
inline void set_country(std::string set_country) { this->country = set_country;};
inline void set_c_deaths(int set_c_deaths) { this->c_deaths = set_c_deaths;};
inline void set_c_cases(int set_c_cases) { this->c_cases = set_c_cases;};
inline int get_c_cases() { return c_cases;};
inline int get_c_deaths() { return c_deaths;};
inline std::string get_date() { return date;};
inline std::string get_country() { return country;};
inline static void print_data_entry(std::ostream& stream, DataEntry* entry) {
char const SPACE = ' ';
if (entry != nullptr) {
stream << "[Date: " << entry->get_date() << "]," << SPACE
<< "[Country: " << entry->get_country() << "]," << SPACE
<< "[Cases: " << entry->get_c_cases() << "]," << SPACE
<< "[Deaths: " << entry->get_c_deaths() << "]";
}
}
//declare as "friend" so it doesn't give a fuck about access specifiers
inline friend std::ostream& operator<<(std::ostream& stream, DataEntry* entry) {
print_data_entry(stream, entry);
return stream;
}
};
/**
* @brief A hash table implementation to store Covid-19 data by country
* @class CovidDB
* @note The hash table size is fixed at 17.
*/
class CovidDB final {
private:
int size;
std::vector<std::vector<DataEntry*>> HashTable;
public:
//non default construcotr with parameters
//@param size -> custom size
inline CovidDB(int size) : size(size), HashTable(size) {}; | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
//default construcotr
inline CovidDB() { //default size
HashTable.resize(17);
}
inline void clear() {
for (auto& row : HashTable) {
for (auto& entry : row) {
delete entry;
}
row.clear();
}
HashTable.clear();
HashTable.shrink_to_fit();
}
inline ~CovidDB() { //handles memory
clear();
}
/** @note Copy constructor */
CovidDB(const CovidDB& other) {
size = other.size;
HashTable.resize(size);
for (int i = 0; i < size; ++i) {
for (const auto& entry : other.HashTable[i]) {
HashTable[i].push_back(new DataEntry(*entry));
}
}
}
/** @note Move constructor */
CovidDB(CovidDB&& other) noexcept
: size(other.size)
, HashTable(std::move(other.HashTable))
{
other.size = 0;
}
/** @note Overloaded assigment operator*/
CovidDB& operator=(CovidDB other) {
std::swap(other.size, size);
std::swap(other.HashTable, HashTable);
return *this;
}
DataEntry* get(std::string country);
void fetch_data(DataEntry* set, std::string country);
bool add(DataEntry* entry);
void add_covid_data(std::string const COVID_FILE);
void add_rehashed_data(std::string const COVID_FILE);
void rehash();
int re_hash_key(std::string country);
int hash(std::string country);
void remove(std::string country);
void display_table() const;
void log();
void log_rehashed();
};
MakeFile
CC = g++
CFLAGS = -Wall -Werror -std=c++11 -pedantic -O3
SRCS = run.cpp CovidDB.cpp main.cpp
OBJS = $(SRCS:.cpp=.o)
TARGET = main
all: $(TARGET)
$(TARGET): $(OBJS)
$(CC) $(CFLAGS) $(OBJS) -o $(TARGET)
%.o: %.cpp
$(CC) $(CFLAGS) -c $< -o $@
clean:
rm -f $(OBJS) $(TARGET)
Answer: Avoid macros where possible
Is the stuff I am doing with defining "random" macros such as LOG or WAIT bad practice? | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
Is the stuff I am doing with defining "random" macros such as LOG or WAIT bad practice?
First of all, in C++ you almost always be able to avoid using macros to begin with. Instead, create static constexpr constants (these also work for strings) or write regular functions. So consider:
static constexpr bool log = true;
static constexpr const char* author = "Jakob";
static void sleep() {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
Instead of #ifdef, you can write this:
if constexpr (log) {
data_base.log();
} else {
std::cout << "\n[Set variable `log` in run.cpp to `true` to run]\n";
}
You can omit the constexpr in that if-statement, although then both the if and the else part must be valid code.
Use a logging library
I would also be very grateful if someone could point me on how to log errors without creating a logging class. Is there a library for that?
Logging can be more important than you think, and doing logging properly can be a lot of work. So instead of implementing it yourself, indeed consider using an existing library, for example spdlog or Boost::log, but there are many others.
About Doxygen
One of my professors introduced me to doxygen but I found that it takes me a lot longer than just // {desc: β¦ pre: β¦ post β¦} | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
The reason to use the Doxygen format is so that there are tools that understand your documentation. For example, Doxygen (the program) will be able to create nice hyperlinked HTML and PDF files. But there are also code editors that understand Doyxgen comments, and will be able to show you the documentation when you hover over a function name for example.
If you believe it takes too much time writing it, then try to find some way to make it more efficient to write Doyxgen comments. For example, most code editors allow you to create macros or store snippets that allow you to insert a template Doxygen comment, and then you only have to fill in the details. See also this StackOverflow question.
Use '\n' instead of std::endl
Use '\n' instead of std::endl; the latter is equivalent to the former, but will also force the output to be flushed, which is usually unnecessary and might hurt performance.
For example, in this line you are flushing the output thrice:
std::cout << std::endl << std::endl << std::flush; | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
Especially at the start of run(), what is the point of the flushing anyway? Nothing else was printed at this point. On most operating systems, the standard output is line-buffered, so there is no need to explicitly flush after a newline.
Avoid declaring functions no other source file is going to use
In run.h you are declaring a lot of functions. However, with the exception of run(), all of these functions are only ever used inside run.c. So instead all the declarations could be removed from run.h, and the corresponding definitions in run.c be made static. This avoids polluting the global namespace with lots of generic function names.
Consider merging run.cpp into main.cpp
Your main() basically just calls run(), and main.cpp doesn't do much else. Consider just moving all of run.cpp into main.cpp; this avoids having to declare a globally visible function run().
Showing the timestamp of compilation
Another issue is show_last_compiled(). While technically what it prints is correct, it is actually not very useful. Because you have most of the code in other source files, it's in the other source files where you will make changes. So when you compile your project, your build system will likely not recompile main.cpp. What use is showing the date of compilation of just main.cpp? Unfortunately, there is no standard C++ solution to get the date when the whole binary was built, however your build system might be configured in a way to make this happen, or you might use some tricks like having a static object in each source file that registers its compilation time in its constructor, and then in main() just print the latest of those times.
Personally, I would rather avoid printing the build time; its use is limited to begin with, and even if you make it work, there are issues like whether your clock was set correctly. | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
Note that since C++20, you no longer have to use a macro to get the name of the file that is being compiled. Instead, you can use std::source_location. However, it doesn't come with a way to get the time of compilation.
Avoid fluff
As a beginning programmer, you might be tempted to add a personal tough or some flair to your program. While the intention might be good, try to avoid any fluff, like clearing the screen, sleeping unnecessarily, showing fake progress bars, and so on. These things don't add any functionality, might start to irritate you at some point, require more code that has to be written and can contain bugs, and make your program less efficient.
Take clear_screen(): every time it is called, you have to wait a second for no reason. It also uses std::system(), which forks a new shell process, which in turn parses the command you gave it, which in turn will fork a new process to execute /usr/bin/clear, which in turn is written in C itself and will just print an ANSI code to the screen to clear it. That's a huge overhead, and has even more issues: first, it is not portable (on Windows you'd have to use "cls" as the command), and second its behavior can change depending on your environment settings (consider that your $PATH might be such that it finds a clear that's not /usr/bin/clear).
While you can clear the screen by just printing an ANSI escape code, consider whether the screen needs to be cleared at all. If there is no good reason, just don't do it. The same goes for the unnecessary sleeps and the fake progress bar in display_table(). Consider:
void CovidDB::display_table() const {
std::cout << "[Printing database]\n";
bool empty = true;
for(auto& vec : HashTable) {
for(auto* entry : vec) {
if (entry != nullptr) {
empty = false;
std::cout << entry << '\n';
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
if (empty) {
std::cout << "[The database is empty]\n";
}
}
Notice how much shorter that function is now! That's less code to write, less chance of bugs, and easier to maintain. And you get the data printed immediately instead of having to wait 600 milliseconds!
Spelling and profanity
There are a few spelling errors in your code, like "intiger", "COIVD", and the consistent "data base" instead of "database" (it's one word). This happens to everyone, even native speakers. Consider using a spell checker once in a while to find mistakes and correct them. A rather nice one to use on source code is codespell.
I also saw this:
//declare as "friend" so it doesn't give a fuck about access specifiers
Avoid using profanity in your code. Not everyone appreciates it, and if you ever have to collaborate with others, they might object to it. Also consider that if your code is public, then others can find it. Consider that if you apply for a job, the recruiters might search for code you wrote. It's best to just write neutral and boring comments.
Avoid manual memory allocation
Instead of using new and delete manually, prefer having memory managed by containers and smart pointers instead. In your case, you already have a container that stores entries, so you can have that manage your memory directly:
std::vector<std::vector<DataEntry>> HashTable; | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
This simplifies your code a lot. For example, you no longer need a destructor in class CovidDB. Since entries are stored by value, you also don't need a copy constructor to make deep copies of pointers.
Since there are no pointers anymore, there is also no possibility that there is a nullptr. So all those checks can go away.
One advantage of pointers was that you can pass them around without having to copy the whole object. To make adding new entries to the database still be efficient, some changes should be made. First, add a constructor to DataEntry:
class DataEntry final {
private:
std::string date;
std::string country;
int c_cases = 0;
int c_deaths = 0;
public:
DataEntry() = default;
DataEntry(const std::string& date, const std::string& country,
int c_cases, int c_deaths):
date(date), country(country), c_cases(c_cases), c_deaths(c_deaths) {}
β¦
};
Then in CovidDB, take entry by value, but std::move() it into the table:
bool CovidDB::add(DataEntry entry) {
β¦
HashTable[index].push_back(std::move(entry));
β¦
}
Then in add_covid_data() for example, then instead of allocating a new entry and calling the set_*() functions, you can write:
add({country, latest_date_str, cases, deaths});
This way, a temporary DataEntry object is created that is moved all the way into the table, without unnecessary copies. With whole-program optimization enabled, the compiler can probably even optimize out the moves.
Why implement your own hash table?
Instead of implementing your own hash table, you could have just used std::unordered_map.
If the goal of the excercise was to have you create your own hash table, then I would try to separate the hash table part from the COVID database; basically so that you write something that looks like:
template<typename T>
class MyHashTable {
β¦
};
class CovidDB {
MyHashTable<std::vector<DataEntry>> HashTable;
β¦
}; | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, beginner, c++11, hash-map, homework
class CovidDB {
MyHashTable<std::vector<DataEntry>> HashTable;
β¦
};
Uninitialized value
If you use the default constructor of CovidDB, the member variable HashTable is initialized, but size is not.
However, instead of initializing size, I would just remove this member variable: you can just use HashTable.size() to get the size of the table. This avoids you having to keep your own size in sync.
Unnecessary use of final and inline
The keyword inline does nothing for member functions defined in the class declaration, those are already implicitly inline.
While marking a class as final might be useful in some cases, why do it here? There is no inheritance being used anywhere. And what if you really do want to inherit from CovidDB at some point? Would that really be a problem?
Avoid calling std::exit() from class member functions
By calling std::exit() from class member functions, you take away the possibility of the caller recovering from the error. Instead, consider throwing an exception instead (preferrably one of the standard exceptions or a custom class derived from those). If the exceptions are not caught, this will still cause the program to exit with a non-zero exit code, but now it allows the caller to try-catch and deal with the problem.
Missing error checking
You are doing a little bit of error checking on input/output, but there is a lot more that can go wrong than just opening the file: there could be a read or write error at any point for example.
When reading a file, when you think you have reached the end, check if file.eof() == true. If not, then an error occured.
When writing a file, check that file.good() == true after calling file.close(). If not, an error occured writing any part of it. | {
"domain": "codereview.stackexchange",
"id": 44765,
"lm_label": 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, c++11, hash-map, homework",
"url": null
} |
c++, c++11, homework
Title: O(NlogN) sorting algorithms in C++
Question: The following code is my lab which focused on implementing any 3 known sorting algorithms out there. Since the professor gave us a choice to pick any of them and compare their execution time I chose Quick Sort, Selection Sort, and Heap Sort. I had the option to choose bogo or bubble sort but I think that's boring and doesn't present a challenge.
I had to measure the execution time for every algorithm and print the size = 10 one, I used the chrono library to measure the execution time of the algorithms. Is there a way to speed some of the algorithms up? Would anyone recommend different design choices?
I know the heap sort could be implemented with STL using std::make_heap() and then use std::sort() but when I thought about it, it felt like it defies the purpose of the lab (own implementation).
I used a random pivot since I read that QS is very slow if the elements are sorted/partially sorted/ or all the same. I was using rand() which made a system call every iteration and really slowed down performance. Would the median of three be better in this case?
Restrictions:
C++ 11 standard
Flags: -Werror -Wall -pedantic
No templates
Can't use std::vector or std::array or std::list...
I had to pass a new, random, non-sorted array (not a copy of the original) into every single algorithm separately | {
"domain": "codereview.stackexchange",
"id": 44766,
"lm_label": 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, homework",
"url": null
} |
c++, c++11, homework
I find the last one stupid, since it offers no "control" over the time measurements, especially for quicksort. The odds of getting a size = 10 sorted array out of 100000 numbers are slim but still there.
Edit: in the merge function I used i, j, and k as my variable names, which could go in the "bad practice" basket...This is due to the lack of MS I was following my professor's flowchart that she made in class. Also I know that C++ prefers to use camelCase for variables over snake_case, I prefer snake_case and I hope that's not an issue.
Perfect timing lol: I got my grade back (92/100), and I got downgraded (-4) for readability of code and I quote "Comments could be better"(-4).
Code:
/**
* @author Jakob Balkovec
* @file lab5.cpp [Driver Code]
* @note Driver code for lab5
*
* @brief This assignment focuses on using sorting algorithms such as:
* - Heap Sort
* - Quick Sort
* - Merge Sort
* @note use of function pointers
*/
#include <iostream>
#include <chrono>
#include <random>
#include <iomanip>
/**
* @brief Maintains the max heap property of a subtree rooted at index 'root'.
* @param arr The array to be sorted.
* @param size The size of the heap/subtree.
* @param root The index of the root of the subtree.
*/
void heapify(int *arr, int size, int root) {
int largest = root; //largest is the root of the heap
int left = 2 * root + 1; // L child
int right = 2 * root + 2; // R child
// if left child is larger than root
if (left < size && arr[left] > arr[largest]) {
largest = left;
}
// if right child is larger than current largest
if (right < size && arr[right] > arr[largest]) {
largest = right;
}
// if largest is not root
if (largest != root) {
std::swap(arr[root], arr[largest]);
heapify(arr, size, largest); //recursive call
}
} | {
"domain": "codereview.stackexchange",
"id": 44766,
"lm_label": 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, homework",
"url": null
} |
c++, c++11, homework
/**
* @brief Performs heap sort on an array.
* @param arr The array to be sorted.
* @param size The size of the array.
*/
void heap_sort(int *arr, int size) {
// build a max heap
for (int i = size / 2 - 1; i >= 0; i--) {
heapify(arr, size, i);
}
// extract elements from heap one by one
for (int i = size - 1; i >= 0; i--) {
// move current root to the end
std::swap(arr[0], arr[i]);
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
}
/**
* @brief Merges two subarrays of arr[]
* @param arr The array to be sorted
* @param p Starting index of the first subarray
* @param q Ending index of the first subarray
* @param r Ending index of the second subarray
*/
void merge(int *arr, int p, int q, int r) {
int n1 = q - p + 1; // size of the first subarray
int n2 = r - q; // size of the second subarray
//temp arrays
int* left_sub = new int[n1];
int* right_sub = new int[n2];
//copy elements
for(int i = 0; i < n1; i++) {
left_sub[i] = arr[p+i];
}
//copy elements
for(int j = 0; j < n2; j++) {
right_sub[j] = arr[q+1+j];
}
int i = 0;
int j = 0;
int k = p;
// merge the elements from the temporary arrays back into arr[] in sorted order
while(i < n1 and j < n2) {
if(left_sub[i] < right_sub[j]) {
arr[k] = left_sub[i];
i++;
} else {
arr[k] = right_sub[j];
j++;
}
k++;
}
//copy elements over if any
while (i < n1) {
arr[k] = left_sub[i];
i++;
k++;
}
//copy elements over if any
while (j < n2) {
arr[k] = right_sub[j];
j++;
k++;
}
delete[] left_sub; //free memory
delete[] right_sub;
} | {
"domain": "codereview.stackexchange",
"id": 44766,
"lm_label": 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, homework",
"url": null
} |
c++, c++11, homework
/**
* @brief Sorts an array using merge sort algorithm
* @param arr The array to be sorted
* @param p Starting index of the array
* @param r Ending index of the array
*/
void merge_sort_helper(int *arr, int p, int r) {
if (p < r) {
int q = (p + r) / 2;
merge_sort_helper(arr, p, q);
merge_sort_helper(arr, q + 1, r);
merge(arr, p, q, r);
}
}
/**
* @brief Sorts an array using merge sort algorithm
* @param arr The array to be sorted
* @param size The size of the array
*/
void merge_sort(int *arr, int size) {
merge_sort_helper(arr, 0, size - 1);
}
/**
* @brief Generates a random pivot index between low and high (inclusive)
* @param low Starting index of the array
* @param high Ending index of the array
* @return Random pivot index
*/
int random_pivot(int low, int high) {
return low + rand() % (high - low + 1);
}
/**
* @brief Partitions the array and returns the partition index
* @param arr The array to be partitioned
* @param low Starting index of the partition
* @param high Ending index of the partition
* @return Partition index
*/
int partition(int* arr, int low, int high) {
int pivotIndex = random_pivot(low, high);
int pivot = arr[pivotIndex];
std::swap(arr[pivotIndex], arr[high]);
int i = low - 1; // Index of the smaller element
for (int j = low; j <= high - 1; j++) {
// If current element is smaller than or equal to the pivot
if (arr[j] <= pivot) {
i++; // Increment index of smaller element
std::swap(arr[i], arr[j]); // Swap current element with the smaller element
}
}
std::swap(arr[i + 1], arr[high]); // Swap the pivot with the element at the partition index
return i + 1; // Return the partition index
} | {
"domain": "codereview.stackexchange",
"id": 44766,
"lm_label": 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, homework",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.