text stringlengths 1 2.12k | source dict |
|---|---|
rust, iterator
let tot = part_one(&res);
assert_eq!(tot, 7);
}
#[cfg(test)]
#[test]
fn test_part_two() {
let test = String::from(
"199\n200\n208\n210\n200\n207\n240\n269\n260\n263"
);
let res = parse_to_int(test);
let tot = part_two(&res);
assert_eq!(tot, 5);
}
Any advice is welcome, but I'd love some pointers on if I can make this more idiomatic. As a note, the body.strip() line is due to the fact that my editor keeps putting an extra newline at the end of the AoC data file, I shouldn't need it otherwise.
Answer: Your code looks good to me! Here is how we can try to make things better.
Use more tools: fmt
Your code looks properly formatted. However, for your information, you can use cargo fmt to ensure that you never have to worry about formatting your code manually anymore.
With the code provided, the only changes performed are about blank lines and lines break.
Use more tools: clippy
clippy is a really nice tool to catch mistakes and improve your code.
In your case, there is nothing spectacular suggested but it is worth adding it to your toolbox.
Here are the suggestions, all of them are easy to take into account.
error: this argument is passed by value, but not consumed in the function body
--> src/2021/day1/main_review.rs:6:23
|
6 | fn parse_to_int(body: String) -> Vec<i32> {
| ^^^^^^ help: consider changing the type to: `&str`
|
= note: `-D clippy::needless-pass-by-value` implied by `-D clippy::pedantic`
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_value
error: single-character string constant used as pattern
--> src/2021/day1/main_review.rs:9:16
|
9 | .split("\n")
| ^^^^ help: try using a `char` instead: `'\n'`
|
= note: `-D clippy::single-char-pattern` implied by `-D clippy::perf`
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_char_pattern | {
"domain": "codereview.stackexchange",
"id": 44020,
"lm_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, iterator",
"url": null
} |
rust, iterator
error: writing `&Vec` instead of `&[_]` involves a new object where a slice will do
--> src/2021/day1/main_review.rs:12:21
|
12 | fn part_one(parsed: &Vec<i32>) -> i32 {
| ^^^^^^^^^ help: change this to: `&[i32]`
|
= note: `-D clippy::ptr-arg` implied by `-D clippy::style`
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ptr_arg
error: casting `bool` to `i32` is more cleanly stated with `i32::from(_)`
--> src/2021/day1/main_review.rs:18:23
|
18 | .map(|(a, b)| (b > a) as i32)
| ^^^^^^^^^^^^^^ help: try: `i32::from(b > a)`
|
= note: `-D clippy::cast-lossless` implied by `-D clippy::pedantic`
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#cast_lossless
Simplifying tests
In particular, once you've taken these suggestions into account, you can get rid of the String::from in your test cases and get something much more concise:
#[cfg(test)]
#[test]
fn test_int_conversion() {
let res = parse_to_int("199\n200\n208\n210\n200\n207\n240\n269\n260\n263");
assert_eq!(res, vec![199, 200, 208, 210, 200, 207, 240, 269, 260, 263]);
}
#[cfg(test)]
#[test]
fn test_part_one() {
let res = parse_to_int("199\n200\n208\n210\n200\n207\n240\n269\n260\n263");
let tot = part_one(&res);
assert_eq!(tot, 7);
}
#[cfg(test)]
#[test]
fn test_part_two() {
let res = parse_to_int("199\n200\n208\n210\n200\n207\n240\n269\n260\n263");
let tot = part_two(&res);
assert_eq!(tot, 5);
}
You can also try to define the input example just once (and maybe remove various variables used just once):
#[cfg(test)]
mod tests {
use super::*;
const INPUT_EXAMPLE: &str = "199\n200\n208\n210\n200\n207\n240\n269\n260\n263"; | {
"domain": "codereview.stackexchange",
"id": 44020,
"lm_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, iterator",
"url": null
} |
rust, iterator
const INPUT_EXAMPLE: &str = "199\n200\n208\n210\n200\n207\n240\n269\n260\n263";
#[cfg(test)]
#[test]
fn test_int_conversion() {
assert_eq!(
parse_to_int(INPUT_EXAMPLE),
vec![199, 200, 208, 210, 200, 207, 240, 269, 260, 263]
);
}
#[test]
fn test_part_one() {
assert_eq!(part_one(&parse_to_int(INPUT_EXAMPLE)), 7);
}
#[test]
fn test_part_two() {
assert_eq!(part_two(&parse_to_int(INPUT_EXAMPLE)), 5);
}
}
Solution for part 1
The algorithm put in place for part 1 looks good to me.
However, instead of having parsed.iter() multiple times including one shifted of 1, you could directly yuse tuple_windows (from the itertools crate) to write: parsed.iter().tuple_windows().map(|(a, b)| i32::from(b > a)).sum().
This may look a bit overkilled but this will be even more relevant for the part 2.
Also, the variable name parsed does not convey much meaning. My preference would go for something like depths (even though it is easy to forget that we are tackling a submarine problem and not just a mathematical one).
As a final side note, instead of having map(|(a, b)| i32::from(b > a)).sum(), one could use filter(|(a, b)| a < b).count() but I cannot guarantee that it is more efficient and/or more idiomatic.
Solution for part 2
For this particular part, a mathematical trick can be applied. Indeed, we are comparing sum of sliding windows but doing it the obvious way: compute sliding windows, compute sums, compare sums. Instead, the following observation can be done:
Computing:
Window(n + 1) > Window(n)
ss the same as computing:
d(n+1) + d(n+2) + ... + d(n+1+windowsize) > d(n) + d(n+1) + ... + d(n+windowsize) (where d is depth)
Which is the same as computing:
d(n+1+windowsize) > d(n) which does not involve any kind of summation. | {
"domain": "codereview.stackexchange",
"id": 44020,
"lm_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, iterator",
"url": null
} |
rust, iterator
d(n+1+windowsize) > d(n) which does not involve any kind of summation.
Hence, the solution for part 2 can be written:
fn part_two(depths: &[i32]) -> usize {
// Window(n + 1) > Window(n)
// d(n+1) + d(n+2) + ... + d(n+1+windowsize) > d(n) + d(n+1) + ... + d(n+windowsize)
// d(n+1+windowsize) > d(n)
depths
.iter()
.tuple_windows()
.filter(|(a, _, _, d)| a < d)
.count()
} | {
"domain": "codereview.stackexchange",
"id": 44020,
"lm_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, iterator",
"url": null
} |
java, error-handling, crud
Title: When to use IllegalStateException
Question: I am implementing an API that implements an interface, but I do not need to implement all methods.
In that case, is it better to just return null or throw an IllegalStateException because it if not implemented?
Thanks.
@Override
public ResponseEntity get(long id) {
// ... some meaningful code
return response;
}
@Override
public ResponseEntity post(Request request, long id) {
// ... some meaningful code
return response;
// Not needed to implement this
@Override
public ResponseEntity put(Request request, long id) {
return null;
// or
throw IllegalStateException(“not implemented yet”)
Answer: You can use UnsupportedOperationException.
Don't return null since it won't notify you about unintended use of the method and will result in a much more annoying NullPointerException instead. | {
"domain": "codereview.stackexchange",
"id": 44021,
"lm_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, error-handling, crud",
"url": null
} |
c, strings
Title: Simple string comparison function
Question: A small, simple yet always needed function to compare two strings for equality.
int strequal (const char *str1, const char *str2)
{
while(1)
{
if((*str1) != (*str2))
{
return 1; /* Not Equal*/
}
else if((*str1) == '\0')
{
return 0; /* Equal */
}
str1++;
str2++;
}
return 0; /* Equal*/
}
int main ()
{
const char *str1 = "Hello";
const char *str2 = "Hi";
printf("Strings are equal? %s\n", strequal(str1, str2)? "NO":"YES");
return 0;
}
The performance is the main focus.
Answer: If you want better performance, you should be using the standard library function strcmp():
#include <string.h>
int str_unequal(const char *str1, const char *str2)
{
return strcmp(str1, str2) != 0;
}
The library function can take advantage of the target processor, possibly comparing multiple characters per iteration, which you can't easily do in a portable C program.
Other issues in the function:
strequal() is a name reserved for future library extension, as is any identifier beginning str followed immediately by a letter.
equal is misleading in the name, as it returns true only when the strings are unequal.
while (1) is dubious practice, especially given that there's a natural terminating condition (end of one of the strings).
Unnecessary parentheses around the result of dereference operator * - that's higher precedence than comparisons.
The final return 0; is unreachable.
Problems with the test program:
Uses printf without including <stdio.h>.
Should explicitly state that main() accepts no arguments (i.e. int main(void)).
Only tests a small portion of the functionality (no tests of two equal strings, or one that's a prefix of the other).
Always returns a success status, even when the function is wrong. | {
"domain": "codereview.stackexchange",
"id": 44022,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
c, strings
Modified function and tests:
int str_equal(const char *s1, const char *s2)
{
while (*s1) {
if (*s1++ != *s2++) {
return 0;
}
}
return !*s2;
}
#include <stdio.h>
int test_str_equal(int expected, const char *a, const char *b)
{
int actual = str_equal(a, b);
if (actual == expected) { return 0; }
fprintf(stderr, "\"%s\"==\"%s\" should return %d\n", a, b, expected);
return 1;
}
int main(void)
{
return test_str_equal(1, "", "")
+ test_str_equal(0, "", "x")
+ test_str_equal(0, "x", "")
+ test_str_equal(1, "x", "x")
+ test_str_equal(0, "x", "y")
+ test_str_equal(0, "x", "xy")
+ test_str_equal(0, "xy", "x")
+ test_str_equal(0, "xx", "xy")
+ test_str_equal(1, "xy", "xy");
} | {
"domain": "codereview.stackexchange",
"id": 44022,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
c#, asp.net, asp.net-mvc
Title: Building ASP.Net control from JSON Data | {
"domain": "codereview.stackexchange",
"id": 44023,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asp.net, asp.net-mvc",
"url": null
} |
c#, asp.net, asp.net-mvc
Question: I am working project where I need to build ASP.net control base on JSON data. I am using this method below to get all the data into class. I as using FirstOrDefault and the Where(x => x.Type == ??? to drill down into the data. I think the logic could be simplified, Any suggestions are welcomed. working sample below
JSON data
[
{
"MeetingPollingQuestionId": 2,
"MeetingPollingQuestionType": "LongAnswerText",
"MeetingPollingId": 3,
"SequenceOrder": 1,
"MeetingPollingParts": [
{
"MeetingPollingPartsId": 2,
"Type": "Question",
"MeetingPollingQuestionId": 2,
"MeetingPollingPartsValues": [
{
"Type": "label",
"QuestionValue": "This is a long question",
"FileManagerId": 0,
"FileName": null,
"FileData": null,
"FileType": null
}
]
}
]
},
{
"MeetingPollingQuestionId": 3,
"MeetingPollingQuestionType": "MultipleChoice",
"MeetingPollingId": 3,
"SequenceOrder": 2,
"MeetingPollingParts": [
{
"MeetingPollingPartsId": 3,
"Type": "Question",
"MeetingPollingQuestionId": 3,
"MeetingPollingPartsValues": [
{
"Type": "label",
"QuestionValue": "this is a multiple choice question",
"FileManagerId": 0,
"FileName": null,
"FileData": null,
"FileType": null
}
]
},
{
"MeetingPollingPartsId": 4,
"Type": "Image",
"MeetingPollingQuestionId": 3, | {
"domain": "codereview.stackexchange",
"id": 44023,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asp.net, asp.net-mvc",
"url": null
} |
c#, asp.net, asp.net-mvc
"Type": "Image",
"MeetingPollingQuestionId": 3,
"MeetingPollingPartsValues": [
{
"Type": "Image",
"QuestionValue": null,
"FileManagerId": 14552,
"FileName": null,
"FileData": null,
"FileType": null
}
]
},
{
"MeetingPollingPartsId": 5,
"Type": "Answers",
"MeetingPollingQuestionId": 3,
"MeetingPollingPartsValues": [
{
"Type": "radio",
"QuestionValue": "Yes",
"FileManagerId": 0,
"FileName": null,
"FileData": null,
"FileType": null
},
{
"Type": "radio",
"QuestionValue": "No",
"FileManagerId": 0,
"FileName": null,
"FileData": null,
"FileType": null
},
{
"Type": "radio",
"QuestionValue": "Abstain",
"FileManagerId": 0,
"FileName": null,
"FileData": null,
"FileType": null
}
]
}
]
}
] | {
"domain": "codereview.stackexchange",
"id": 44023,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asp.net, asp.net-mvc",
"url": null
} |
c#, asp.net, asp.net-mvc
method creating controls
public class LongAnswerText : IMeetingPollingQuestion
{
private List<MeetingPollingParts> meetingPollingParts;
private string label = null;
private string textbox = null;
private string type = null;
public LongAnswerText(List<MeetingPollingParts> meetingPollingParts)
{
this.SequenceOrder = SequenceOrder;
this.MeetingPollingId = MeetingPollingId;
this.MeetingPollingQuestionId = MeetingPollingQuestionId;
this.meetingPollingParts = meetingPollingParts;
var MeetingPollingPartsValuesLabel = new List<MeetingPollingPartsValues>();
MeetingPollingPartsValuesLabel = meetingPollingParts.SelectMany(s => s.MeetingPollingPartsValues).ToList();
var labelControl = MeetingPollingPartsValuesLabel.Where(x=>x.Type=="label").FirstOrDefault();
var textboxControl = MeetingPollingPartsValuesLabel.Where(x => x.Type == "textbox").FirstOrDefault();
this.label = LabelControl(string.Format("label_{0}", labelControl.MeetingPollingPartsValuesId), labelControl.QuestionValue);
this.textbox = TextboxControl(string.Format("label_{0}", labelControl.MeetingPollingPartsValuesId));
}
public string LabelControl(string target, string text){
return string.Format("@Html.LabelFor('{0}'>{1}</input>",target,text);
}
public string TextboxControl(string target) {
return string.Format("@Html.TextBoxFor('{0}')",target);
}
}
Output View
<div class="form-group row">
div class="col-md-12">
@Html.LabelFor(model => model.label_1)
@Html.TextBoxFor(x => x.label_1, new { id = "label_1", @class = "form-control" })
</div>
</div>
fiddle
https://dotnetfiddle.net/j6YIPN | {
"domain": "codereview.stackexchange",
"id": 44023,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asp.net, asp.net-mvc",
"url": null
} |
c#, asp.net, asp.net-mvc
fiddle
https://dotnetfiddle.net/j6YIPN
Answer: As was mentioned in the comments, there is no need in using Where LINQ since FirstOrDefault accepts a predicate that can be used to get the value you need:
var labelControl = MeetingPollingPartsValuesLabel.FirstOrDefault(part => part.Type == "label");
As for the other issues...
this.SequenceOrder = SequenceOrder;
this.MeetingPollingId = MeetingPollingId;
this.MeetingPollingQuestionId = MeetingPollingQuestionId;
There is no point is assigning a property to itself (unless there is some important logic in the setter but that is even worse and not your case).
You can just delete those lines with no effect.
Similarly there is no reason to assign null to all those fields:
private string label = null;
private string textbox = null;
private string type = null;
They are already null by default.
List<MeetingPollingParts> meetingPollingParts
This parameter name implies that it is a collection of some parts. However type parameter of the List is MeetingPollingParts in plural, which means that it is a collection of collections of parts. MeetingPollingParts should be named MeetingPollingPart since it represents a singular part. Such small naming mistakes make the code much harder to read. Please pay attention to them.
Methods LabelControl and TextboxControl don't use the instance of LongAnswerText whose member methods they are, therefore there is no reason in them being member methods.
LongAnswerText : IMeetingPollingQuestion
This implementation looks out of place: why does Text implement Question? Judging by your full code, there is no reason in having this interface in the first place since it only has one implementation and you never call instances of that implementation by the interface. | {
"domain": "codereview.stackexchange",
"id": 44023,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asp.net, asp.net-mvc",
"url": null
} |
c#, asp.net, asp.net-mvc
In conclusion, most of the suggestions are aiming at making your solution less verbose: it will help a lot with readability and overall code clarity. There is a lot of extra logic which is not needed for the task you're trying to accomplish, get read of it and it will become much easier to implement stuff that you actually need.
Good luck with refactoring! | {
"domain": "codereview.stackexchange",
"id": 44023,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, asp.net, asp.net-mvc",
"url": null
} |
c, strings
Title: Function to return last line's length of a string
Question: I am completely re-writing the textbox GUI widget.
In order to set the position cursor after the last character in the last line of a text, it is good if you know the exact column of it. So I created a small function that calculates this. It is meant to work sonicly.
int get_last_line_length (char *string)
{
const int len = strlen(string) - 1;
int i;
for(i = len; i != -1 && string[i] != '\n'; i--);
return (len - i);
}
Answer: It's good that you've used strlen, but there's actually another standard function that could be useful here. Instead of your reverse loop, you can use strrchr to find a pointer to the last occurrence of a character (or NULL if said character is not found). As discussed in the comments, this could be (and likely is) slower in the case when a newline is not found, but unless this function is called very often or is in a very performance critical path, I can't imagine it will be an issue. If you do need to optimize it to your original implementation, I would pull the reverse loop logic out into a function.
Anyway, a bit of a review:
Your string parameter should be a pointer to const since it's not modified.
Personal style thing: I'm not a fan of return (...). If it matters, it also tends to be pretty rare style wise in C.
You should probably explicitly document what happens if a line break is not found in the text. I wouldn't be sure whether strlen(string) or -1 should be returned. | {
"domain": "codereview.stackexchange",
"id": 44024,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings",
"url": null
} |
typescript
Title: DRY-ness of two typescript functions
Question: Is there a way to make this code bellow more DRY or is this fine as it is? I am wondering if there could for instance be a way to combine the two functions in to 1, the output type of which would be determined by some typescript logic but I don't see how yet.
Please let me know if you happen to see anything else worth improving...
import { EntityManager, EntityTarget, In } from 'typeorm';
export async function batchEntitiesBy<Entity, T extends keyof Entity>(
em: EntityManager,
entityClass: EntityTarget<Entity>,
by: T,
variables: readonly Entity[T][]
): Promise<(Entity)[]> {
const entities = await em.find(entityClass, { [by]: In(variables as Entity[T][]) });
// reorder the entities to match by
const entityMap = new Map<Entity[T], Entity>()
entities.forEach((e) => {
entityMap.set(e[by], e)
})
return variables.map((v) => {
const out = entityMap.get(v)
if (!out) {
throw new Error(`Could not find ${entityClass} with ${String(by)} ${v}`)
}
return out
})
}
export async function batchEntitiesArrayBy<Entity, T extends keyof Entity>(
em: EntityManager,
entityClass: EntityTarget<Entity>,
by: T,
variables: readonly Entity[T][]
): Promise<Entity[][]> {
const entities = await em.find(entityClass, { [by]: In(variables as Entity[T][]) });
// reorder the entities to match by
const entityMap = new Map<Entity[T], Entity[]>()
entities.forEach((e) => {
const el = entityMap.get(e[by]) ?? []
el.push(e)
entityMap.set(e[by], el)
})
// ? do we need this []?
return variables.map((v) => {
const out = entityMap.get(v)
if (!out) {
throw new Error(`Could not find ${entityClass} with ${String(by)} ${v}`)
}
return out
})
}
``` | {
"domain": "codereview.stackexchange",
"id": 44025,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "typescript",
"url": null
} |
typescript
Answer: Single function
Since both functions have identical input signatures, I don't see a way to merge them into one. You have to somehow tell the program, what kind of return value you want if it's 1d or 2d array of Entities. Either by additional parameter or having 2 functions (which I think is better anyway).
In some languages with strong static typing and generics support you could tell also possibly say this information by passing generics type of your return object, because generic types are parts of the method signature. It would be possible in C# or using kotlin reified inline functions, but not in Javascript or JVM languages as they don't know the generic type on runtime.
DRY
Only difference is in your entityMap variable and it's construction. I suggest this:
Extract common code into a 3rd private function
Call this function from your 2 public functions
Specific code (constructing entityMap) keep in your public functions
Your private function can look something like this:
private async function batchEntitiesBy<Entity, T extends keyof Entity, Result>(
entityClass: EntityTarget<Entity>,
by: T,
variables: Entity[T][],
entityMap: Map<Entity[T], Result>,
): Promise<Result[]> {
return variables.map((v) => {
const out = entityMap.get(v)
if (!out) {
throw new Error(`Could not find ${entityClass} with ${String(by)} ${v}`)
}
return out
})
}
It may not be syntactically correct as I am not too experienced with Typescript so apologies for any errors, but it should give you the idea.
Result generics should be either Entity or Entity[].
Constructing your maps
You can use functional approach to convert your entities to entityMap. In your case you can simplify it to this for the first function:
entities.reduce((obj, item) => obj[item[by]] = item, {}) | {
"domain": "codereview.stackexchange",
"id": 44025,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "typescript",
"url": null
} |
javascript, algorithm, wordle
Title: Wordle color algorithm in JavaScript
Question: A lot of Wordle clones get the tile-coloring algorithm wrong: for example,
if the word is BURNT and you guess TOAST, the colors should be ----G (not Y---G)
if the word is MAXIM and you guess MAMMA, the colors should be GGY-- (not GGYYY)
if the word is SWIFT and you guess IIWIS, the colors should be Y-Y-Y (not YYYYY)
I've written a JavaScript implementation of the tile-coloring algorithm. I'd like to know both whether it's correct (non-buggy), and how it can be improved. In particular, if there's some way to compute just the color of the indexth tile, without computing all the tiles' colors as a side effect, that would be nice to know.
function computeColor(targetWord, guess, index) {
let colors = Array(WORD_LENGTH).fill("wrong")
for (var i = 0; i < WORD_LENGTH; ++i) {
if (targetWord[i] === guess[i]) {
colors[i] = "correct"
} else if (targetWord.includes(guess[i])) {
colors[i] = "wrong-location"
}
}
for (var i = 0; i < WORD_LENGTH; ++i) {
if (colors[i] == "wrong-location") {
// Only the correct number of tiles should be colored yellow.
const letter = guess[i]
const targetCount = targetWord.split('').filter((ch) => ch == letter).length
const greenCount = Array.from(Array(WORD_LENGTH).keys()).filter((j) => (guess[j] === letter && colors[j] === "correct")).length
const maxYellowCount = targetCount - greenCount
let currentYellowCount = 0
for (var j = 0; j < i; ++j) {
if (guess[j] == letter && colors[j] === "wrong-location") {
currentYellowCount += 1
}
}
if (currentYellowCount == maxYellowCount) {
colors[i] = "wrong"
}
}
}
return colors[index]
} | {
"domain": "codereview.stackexchange",
"id": 44026,
"lm_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, wordle",
"url": null
} |
javascript, algorithm, wordle
console.assert(computeColor('BURNT', 'TOAST', 0) === "wrong")
console.assert(computeColor('BURNT', 'TOAST', 1) === "wrong")
console.assert(computeColor('BURNT', 'TOAST', 2) === "wrong")
console.assert(computeColor('BURNT', 'TOAST', 3) === "wrong")
console.assert(computeColor('BURNT', 'TOAST', 4) === "correct")
console.assert(computeColor('MAXIM', 'MAMMA', 0) === "correct")
console.assert(computeColor('MAXIM', 'MAMMA', 1) === "correct")
console.assert(computeColor('MAXIM', 'MAMMA', 2) === "wrong-location")
console.assert(computeColor('MAXIM', 'MAMMA', 3) === "wrong")
console.assert(computeColor('MAXIM', 'MAMMA', 4) === "wrong")
console.assert(computeColor('SWIFT', 'IIWIS', 0) === "wrong-location")
console.assert(computeColor('SWIFT', 'IIWIS', 1) === "wrong")
console.assert(computeColor('SWIFT', 'IIWIS', 2) === "wrong-location")
console.assert(computeColor('SWIFT', 'IIWIS', 3) === "wrong")
console.assert(computeColor('SWIFT', 'IIWIS', 4) === "wrong-location")
```
Answer: REVISED
Code should be correct, maintainable, robust, reasonably efficient, and, most important, readable.
Wordle is a clever, challenging, and fun game implemented by a skilled software engineer.
Hi, I'm Josh [Wardle].
https://powerlanguage.co.uk/
Wordle is daily word guessing game I made.
The Wordle tile coloring rules are:
Guess the WORDLE in six tries.
Each guess must be a valid five-letter word. Hit the enter button to submit.
After each guess, the color of the tiles will change to show how close your guess was to the word.
Green: The letter is in the word and in the correct spot.
Yellow: The letter is in the word but in the wrong spot.
Gray: The letter is not in the word in any spot. | {
"domain": "codereview.stackexchange",
"id": 44026,
"lm_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, wordle",
"url": null
} |
javascript, algorithm, wordle
Review 1 is a code review that critiques the OP's code and provides a revised, simplified version of the OP's code that conforms to Wordle rules. The revised code efficiently satisfies the rule that five letters must be entered before the color of the tiles change by returning a five letter array of tile colors.
In a comment on Review 1, the OP says: "the "wordle.js" I'm plugging this into expects a function with the given signature [(word, guess, index)]; I wanted to surgically replace just the buggy coloring function."
Review 2 refactors the revised solution from Review 1 to provide an efficient function with the expected signature: (word, guess, index).
REVIEW 1
I'd like to know whether it's correct
Your code is complicated. It's hard to prove it is correct.
Production executable code, like Wordle, is minified, use spacing and useful comments to enhance readability.
The letter background colors will be used both inside and outside the function. Use outside the function color constants.
Simplify your code. In particular, eliminate extraneous methods: split, filter, from, keys, and so on. Some of these methods implement implicit loops, which, inside a for loop, have O(n**2) complexity. The simplified code has only two loops with O(n) complexity.
Don't use var for variable declarations. Use let or const.
Don't use == for equality; use === for strict equality.
There is no reason to limit the function to five letter words and guesses. However, check the function word and guess length equality invariant.
The simplfied code, as required by Wordle, returns a complete array of letter background colors. The original function only returns the color for a single letter. There is (times five) computational rundundancy to color all five letters of a guess.
Using jsbench.me, coloring a five letter guess using the original code is over 90% slower than the simplified code. | {
"domain": "codereview.stackexchange",
"id": 44026,
"lm_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, wordle",
"url": null
} |
javascript, algorithm, wordle
Here is a simplified version of your code:
// letter background colors
const COLOR_NOT_ENTERED = "White";
const COLOR_CORRECT_SPOT = "Green";
const COLOR_WRONG_SPOT = "Yellow";
const COLOR_NOT_ANY_SPOT = "Gray";
// guessColors returns an array of guess letter background colors.
function guessColors(word, guess) {
let colors = new Array(guess.length);
if (word.length !== guess.length) {
return colors.fill(COLOR_NOT_ENTERED);
}
// color matched guess letters as correct-spot,
// and count unmatched word letters
let unmatched = {}; // unmatched word letters
for (let i = 0; i < word.length; i++) {
let letter = word[i];
if (letter === guess[i]) {
colors[i] = COLOR_CORRECT_SPOT;
} else {
unmatched[letter] = (unmatched[letter] || 0) + 1;
}
}
// color unmatched guess letters right-to-left,
// allocating remaining word letters as wrong-spot,
// otherwise, as not-any-spot
for (let i = 0; i < guess.length; i++) {
let letter = guess[i];
if (letter !== word[i]) {
if (unmatched[letter]) {
colors[i] = COLOR_WRONG_SPOT;
unmatched[letter]--;
} else {
colors[i] = COLOR_NOT_ANY_SPOT;
}
}
}
return colors;
}
if there's some way to compute just the color of the indexth tile, without computing all the tiles' colors as a side effect.
There is not. Why do you want to do that?
Consider a word
[ A X A A A ]
and a partial (index 0) guess of
[ X - - - - ]
which evaluates to colors
[ Yellow, ------, ------, ------, ------ ]
Now, add another letter to the guess, a partial (index 1) guess of
[ X X - - - ]
which evaluates to colors
[ Grey, Green, ------, ------, ------ ]
Partial colors evaluation is not always stable.
REVIEW 2 | {
"domain": "codereview.stackexchange",
"id": 44026,
"lm_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, wordle",
"url": null
} |
javascript, algorithm, wordle
Partial colors evaluation is not always stable.
REVIEW 2
Here is a revised, simplified version of the OP's code to provide a more readable, more efficient function with the expected signature: (word, guess, index).
Using jsbench.me, the OP's code is about 96% slower than the following simplified code. The simplified code is about 25 times faster. The simplified code only has one loop. The simplified code does not contain extraneous code.
Wordle rules:
Each guess must be a valid five-letter word.
Hit the enter button to submit.
After each guess, the color of the tiles will change.
For an official, accurate Wordle guess tile color, on each call to the function "guess must be a five-letter word." Wait until the guess is submitted: "Hit the enter button to submit."
A simple example illustrates the problem. Using Wordle rules, tile color depends on guess letters before and after guess[index]:
AXAAA
X
[ 'Yellow', 'Gray', 'Gray', 'Gray', 'Gray' ]
AXAAA
XX
[ 'Gray', 'Green', 'Gray', 'Gray', 'Gray' ]
The tile color for guess[0] varies depending on how many guess letters are entered.
Also, coloring tiles before the guess is complete would ruin the game by making it too easy.
// Wordle letter tile background colors
const COLOR_CORRECT_SPOT = "Green";
const COLOR_WRONG_SPOT = "Yellow";
const COLOR_NOT_ANY_SPOT = "Gray";
// guessColor returns the guess[index] letter tile background color.
//
// Wordle tile coloring rules:
// Each guess must be a valid five-letter word.
// Hit the enter button to submit.
// After each guess, the color of the tiles will change.
// Green: The letter is in the word and in the correct spot.
// Yellow: The letter is in the word but in the wrong spot.
// Gray: The letter is not in the word in any spot.
function guessColor(word, guess, index) {
// correct (matched) index letter
if (guess[index] === word[index]) {
return COLOR_CORRECT_SPOT;
} | {
"domain": "codereview.stackexchange",
"id": 44026,
"lm_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, wordle",
"url": null
} |
javascript, algorithm, wordle
let wrongWord = wrongGuess = 0;
for (let i = 0; i < word.length; i++) {
// count the wrong (unmatched) letters
if (word[i] === guess[index] && guess[i] !== guess[index] ) {
wrongWord++;
}
if (i <= index) {
if (guess[i] === guess[index] && word[i] !== guess[index]) {
wrongGuess++;
}
}
// an unmatched guess letter is wrong if it pairs with
// an unmatched word letter
if (i >= index) {
if (wrongGuess === 0) {
break;
}
if (wrongGuess <= wrongWord) {
return COLOR_WRONG_SPOT;
}
}
}
// otherwise not any
return COLOR_NOT_ANY_SPOT;
}
function testGuessColor(tests) {
for (let [word, guess] of tests) {
console.log(word);
console.log(guess);
let colors = [];
for (let i = 0; i < word.length; i++) {
colors.push(guessColor(word, guess, i));
}
console.log(colors);
}
}
let tests = [
['BURNT', 'TOAST'],
['MAXIM', 'MAMMA'],
['SWIFT', 'IIWIS'],
['ABBEY', 'BOBBY'],
["ABCDE", "ABCDE"],
["ABCDE", "VWXYZ"],
];
testGuessColor(tests);
$ node wordle.js
BURNT
TOAST
[ 'Gray', 'Gray', 'Gray', 'Gray', 'Green' ]
MAXIM
MAMMA
[ 'Green', 'Green', 'Yellow', 'Gray', 'Gray' ]
SWIFT
IIWIS
[ 'Yellow', 'Gray', 'Yellow', 'Gray', 'Yellow' ]
ABBEY
BOBBY
[ 'Yellow', 'Gray', 'Green', 'Gray', 'Green' ]
ABCDE
ABCDE
[ 'Green', 'Green', 'Green', 'Green', 'Green' ]
ABCDE
VWXYZ
[ 'Gray', 'Gray', 'Gray', 'Gray', 'Gray' ]
$ | {
"domain": "codereview.stackexchange",
"id": 44026,
"lm_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, wordle",
"url": null
} |
java, comparative-review, fluent-interface
Title: Comparing a weak fluent API with a strong fluent API in Java
Question: I have this simple POJO:
package com.github.coderodde.person;
import java.util.Objects;
public class Person {
private int age;
private String firstName;
private String lastName;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public Person() {
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public int hashCode() {
int hash = 3;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Person other = (Person) obj;
if (this.age != other.age) {
return false;
}
if (!Objects.equals(this.firstName, other.firstName)) {
return false;
}
return Objects.equals(this.lastName, other.lastName);
} | {
"domain": "codereview.stackexchange",
"id": 44027,
"lm_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, comparative-review, fluent-interface",
"url": null
} |
java, comparative-review, fluent-interface
@Override
public String toString() {
return "Person[age = "
+ age
+ ", firstName = \'"
+ firstName
+ "\', lastName = \'"
+ lastName
+ "\']";
}
public static LastNameSelector withFirstName(String firstName) {
return new LastNameSelector(firstName);
}
public static final class LastNameSelector {
private final String firstName;
LastNameSelector(String firstName) {
this.firstName = firstName;
}
public AgeSelector withLastName(String lastName) {
return new AgeSelector(firstName, lastName);
}
}
public static final class AgeSelector {
private final String firstName;
private final String lastName;
AgeSelector(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Person withAge(int age) {
return new Person(firstName, lastName, age);
}
}
}
The above implementation defines, what I call, a strong fluent API, that enforces the order of setters.
On the other hand, I have a weak fluent API, in which the order of setters is arbitrary:
package com.github.coderodde.person; | {
"domain": "codereview.stackexchange",
"id": 44027,
"lm_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, comparative-review, fluent-interface",
"url": null
} |
java, comparative-review, fluent-interface
public class PersonBuilder {
private Person person;
public static PersonBuilder newPerson() {
PersonBuilder personBuilder = new PersonBuilder();
personBuilder.person = new Person();
return personBuilder;
}
public PersonBuilder withAge(int age) {
person.setAge(age);
return this;
}
public PersonBuilder withFirstName(String firstName) {
person.setFirstName(firstName);
return this;
}
public PersonBuilder withLastName(String lastName) {
person.setLastName(lastName);
return this;
}
public Person create() {
return person;
}
}
(The demo code follows.)
package com.github.coderodde.person;
public class Demo {
public static void main(String[] args) {
Person alice =
PersonBuilder
.newPerson()
.withLastName("Funky II")
.withAge(34)
.withFirstName("Alice")
.create();
System.out.println(alice);
Person bob = Person.withFirstName("Bob")
.withLastName("Davidson")
.withAge(36);
System.out.println(bob);
}
}
Now, my question is: which one should I use in industrial code?
Answer: You already answered yourself. Use the second one when the order matters, although I can't think of a situation when I ever needed that. I expect that in most cases the typical builder pattern will be just fine and order isn't as important as much as ensuring all the required data to the builder have been set.
A few points: | {
"domain": "codereview.stackexchange",
"id": 44027,
"lm_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, comparative-review, fluent-interface",
"url": null
} |
java, comparative-review, fluent-interface
In your example neither of your approaches makes sense and the correct solution would be to use constructor.
There is absolutely no validation and I see that as a big problem.
I find this usage overall pretty cool, but when in the end you are creating just anemic domain model, it loses all it's charm.
I would restrict empty constructor of Person and have identical fields in the builder rather than reference of "unfinished" Person instance.
If I was to implement this myself, the first solution would internally use the second solution to hold the temporary data. | {
"domain": "codereview.stackexchange",
"id": 44027,
"lm_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, comparative-review, fluent-interface",
"url": null
} |
beginner, algorithm, c, mathematics
Title: Checking if a number is divisible by 9
Question: I tried to develop a new way to check if a number is divisible by 9. I have written my code and it is working fine. I'm not allowed to use *,/ and %.
int isDivby9(int x)
{
int status = 0;
int divby8 = 0;
int orgx = x;
if(x>=9)
{
divby8 = x >> 3;
int olddivby8 = divby8;
while(divby8 >= 9)
{
divby8 = divby8 - 9;
}
if(divby8 == (orgx - (olddivby8 << 3)))
{
status = 1;
}
else{
status = 0;
}
x = divby8;
}
return status;
}
Can someone please check if this is a good way to check if a number is divisibility by 9? Is it too complex? Is there any better way to perform the same? I also referred to the logic given in geeksforgeeks.
Answer: I see some things that you might want to use to improve your code.
Use an early bailout
If the passed number x is less than 9, the routine can immediately return 0.
Eliminate multiples of 2
Since 9 and 2 have no common factors, you can speed up the operation (on average) by shifting the incoming x to the right until the least significant bit is non-zero.
Eliminate unused variables
With a minor restructuring of the code, you can eliminate most of the variables and make the code shorter, faster and easier to read.
Consider implementing a test program
You have apparently already done some testing, but posting the test with the code to be reviewed may help others review the code properly.
Putting it all together
Here's what I came up with using all of these suggestions:
#include <stdio.h>
#include <assert.h>
int isDivby9(int x)
{
while (0 == (x & 1)) {
x >>= 1;
}
if(x<9)
return 0;
int divby8 = x >> 3;
while(divby8 >= 9) {
divby8 -= 9;
}
return divby8 == (x & 7);
} | {
"domain": "codereview.stackexchange",
"id": 44028,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, algorithm, c, mathematics",
"url": null
} |
beginner, algorithm, c, mathematics
int main()
{
for (int i=1; i < 1000000; ++i)
assert(isDivby9(i) == (i%9 == 0));
}
Results
On my machine (64-bit Linux box), the original code runs in 2.3 seconds, and the version above completes in 1.5 seconds; a considerable improvement in performance with identical mathematical results. By comparison, the straightforward approach in @Edenia's answer takes 18.8 seconds on the same machine.
All were compiled with gcc 4.9.2 with -O2 optimizations.
Updated algorithm
I couldn't stop thinking about this question because I knew there was a better algorithm, but just couldn't think of it. I finally came across this superb answer to a similar question on StackOverflow. With that excellent answer, I translated a finite state machine implemention into C and came up with this:
#include <limits.h>
struct state {
int nextstate[2];
};
int isDivby9 (int num)
{
static const int HIGH_BIT = INT_MAX - (INT_MAX >> 1);
static const struct state states[9] = {
{{0, 1}}, {{2, 3}}, {{4, 5}},
{{6, 7}}, {{8, 0}}, {{1, 2}},
{{3, 4}}, {{5, 6}}, {{7, 8}}
};
if (num < 0)
num = -num;
int s = 0;
for ( ; num ; num <<= 1) {
s = states[s].nextstate[(num & HIGH_BIT) ? 1 : 0];
}
return s==0;
}
Each bit, starting from the MSB, drives the state machine to the next state. The state is held in variable s and the branches for the 0 and 1 bits are the the two nextstate entries. It works well (including for negative numbers and zero) and is very fast. In fact, on my machine, this routine takes 0.045 seconds.
Updated results
In more concise timing tests on my machine, and adjusting all routines to also work correctly on negative numbers, here's what I found on this machine:
861092 modulus operator
1152840 JS1
1581770 gnasher729
2479987 Simon
8961866 Edward DFA function | {
"domain": "codereview.stackexchange",
"id": 44028,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, algorithm, c, mathematics",
"url": null
} |
beginner, algorithm, c, mathematics
So the % operator is fastest, followed by @JS1's routine, followed by @gnasher729's, followed by @Simon's followed by the DFA routine (by a wide margin!)
Naturally, this might differ on different machines with different architectures, so as always, timing routines on your own actual hardware is recommended.
I learned some things that might well be useful for the next time I work on synthesizing my own logic or on an embedded microprocessor without a multiply instruction. | {
"domain": "codereview.stackexchange",
"id": 44028,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, algorithm, c, mathematics",
"url": null
} |
javascript, algorithm
Title: Box Blur algorithm
Question: This is a challenge from CodeSignal.
For
image = [[1, 1, 1],
[1, 7, 1],
[1, 1, 1]]
the output should be boxBlur(image) = [[1]].
To get the value of the middle pixel in the input 3 × 3 square: (1 + 1 + 1 + 1 + 7 + 1 + 1 + 1 + 1) = 15 / 9 = 1.66666 = 1. The border pixels are cropped from the final result.
For
image = [[7, 4, 0, 1],
[5, 6, 2, 2],
[6, 10, 7, 8],
[1, 4, 2, 0]]
the output should be
boxBlur(image) = [[5, 4],
[4, 4]]
There are four 3 × 3 squares in the input image, so there should be four integers in the blurred output. To get the first value: (7 + 4 + 0 + 5 + 6 + 2 + 6 + 10 + 7) = 47 / 9 = 5.2222 = 5. The other three integers are obtained the same way, then the surrounding integers are cropped from the final result.
Here's my code:
function boxBlur(image) {
const SQUARE = 3
const outerArr = []
for (let i = 0; i < image.length; i++) {
const innerArr = []
for (let j = 0; j < image[0].length; j++) {
if (image[i][j] !== undefined && image[i][j+2] !== undefined && image[i+2]) {
let sum = 0
for (let k = 0; k < SQUARE; k++) {
for (let y = 0; y < SQUARE; y++) {
sum += image[i+k][j+y]
}
}
innerArr.push(Math.floor(sum/9))
}
}
if (innerArr.length) outerArr.push(innerArr)
}
return outerArr
}
```
Answer: Some suggestions on coding style:
Your choice in variables is somewhat confusing i, j? For an algorithm operating on a 2D image, the names x and y would be better. And dx, dy for the offsets in the inner loop.
You defined the width of your kernel as SQUARE, yet you hardcode 2 in the expression image[i][j+2]. | {
"domain": "codereview.stackexchange",
"id": 44029,
"lm_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",
"url": null
} |
javascript, algorithm
You defined the width of your kernel as SQUARE, yet you hardcode 2 in the expression image[i][j+2].
Your boundary checks can be more efficient. Why check for undefined if you know the exact size of the image? You can loop i from 0 to image.length - SQUARE, and loop j from 0 to image[0].length - SQUARE and remove the if statement:
for (let i = 0; i < image.length - SQUARE; i++) {
for (let j = 0; j < image[0].length - SQUARE; j++) {
// no if-statement needed anymore
...
}
}
Note that the naive algorithm works fine for small kernels, but can be done more efficient using a summation map where you first calculate the total sum of all preceding values in a preprocessing step, and then calculate the sum of the pixels in the square using the summation map of the 4 corner points. That way, the algorithm speed becomes independent of the size SQUARE of your kernel. | {
"domain": "codereview.stackexchange",
"id": 44029,
"lm_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",
"url": null
} |
performance, c, strings, integer, converting
Title: Implementation of itoa
Question: int get_digits (int num)
{
if(num < 10)
return 1;
if(num < 100)
return 2;
if(num < 1000)
return 3;
if(num < 10000)
return 4;
if(num < 100000)
return 5;
if(num < 1000000)
return 6;
if(num < 10000000)
return 7;
if(num < 100000000)
return 8;
if(num < 1000000000)
return 9;
return 10; /* num > 1000000000 */
}
char *itoa (int n)
{
static char temp[10]; // MN that can be replaced by some def?
int nDigits = 0;
int i = 0;
if(n == 0)
{
temp[0] = '0';
temp[1] = '\0';
return temp; // or just return "0"; ?
}
nDigits = get_digits(n); // fast function to count digits..
temp[nDigits] = '\0'; // ..needed just here
for(i = n; i >= 1; i /= 10) // whole method stinks
{
temp[--nDigits] = ((i % 10) + '0'); // modulo is quite slow
}
return temp;
}
This is my implementation of the infamous function itoa(), which isn't available everywhere and more importantly not available in my environment. Generally, the implementation of this function is ought to be different anyway. Performance and memory optimization is important.
This function converts an integer to a string. The function owns the reference to the returned string, which is statically allocated and the caller is responsible to make a copy of the returned string if he plans on changing it or preserving it across subsequent calls.
Answer: Interface
static char temp[10];
⋮
return temp; | {
"domain": "codereview.stackexchange",
"id": 44030,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, strings, integer, converting",
"url": null
} |
performance, c, strings, integer, converting
Answer: Interface
static char temp[10];
⋮
return temp;
Returning a pointer to a static member can be a problem. If clients aren't specifically warned, then they may inadvertently overwrite the storage before using it (consider printf("%s%s", itoa(1), itoa(2)) as a minimal example).
In any case, such functions are not safely usable from multiple threads, and writing single-threaded code is an onerous limitation in the modern world.
One alternative is to allocate memory, but that obviously carries a huge performance penalty.
The usual approach for such functions is for the caller to pass appropriate storage. The traditional interface is void itoa(int n, char *buf), but I would strongly recommend updating to imitate snprintf() with something like size_t itoa(int n, char *buf, size_t bufsize) - where the return value represents the number of characters that would be written, even if greater than bufsize.
The getdigits() function shouldn't need external linkage, I think, so declare it static.
It returns 1 for all negative numbers. The way to fix that is to convert all positive inputs to negative ones (note that the other way around does not work, since -INT_MIN isn't necessarily valid, but -INT_MAX always is).
int get_digits(int num)
{
if (num > 0) {
/* strip the leading '-' */
return get_digits(-num) - 1;
}
if(num > -10)
return 2;
if(num > -100)
return 3;
⋮
This function makes assumptions about INT_MAX which are not safe: If INT_MAX is less than 1000000000, then we have an undefined conversion, and if it's greater than 10000000000, we will return a value that's too small.
Since INT_MAX is guaranteed to be at least 10000, we can make a portable version:
int get_digits(int num)
{
if (num > 0) {
/* strip the leading '-' */
return get_digits(-num) - 1;
} | {
"domain": "codereview.stackexchange",
"id": 44030,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, strings, integer, converting",
"url": null
} |
performance, c, strings, integer, converting
int digit_count = 1; /* leading '-' */
while (num <= -10000) {
digit_count += 4;
num /= 10000;
}
if (num <= -100) {
digit_count += 2;
num /= 100;
}
if (num <= -10) {
digit_count += 1;
}
return digit_count;
}
However, counting the digits in advance shouldn't be necessary - we can work backwards, then reverse the result in-place for less cost:
#include <stdlib.h>
size_t itoa(int n, char *buf, size_t bufsize)
{
if (n == 0) {
if (bufsize > 1) {
buf[0] = '0';
buf[1] = '\0';
}
return 1;
}
size_t i = 0;
size_t digits = 0;
if (n < 0) {
while (n) {
int r = n % 10;
n /= 10;
if (r > 0) {
/* non-standard compiler */
r -= 10;
++n;
}
if (buf && i < bufsize - 1) {
buf[i++] = (char)('0' - r);
}
++digits;
}
if (buf && i < bufsize - 1) {
buf[i++] = '-';
}
++digits;
} else {
/* n > 0 */
while (n) {
int r = n % 10;
n = n / 10;
if (buf && i < bufsize - 1) {
buf[i++] = (char)('0' + r);
}
++digits;
}
}
if (buf && i < bufsize - 1) {
buf[i--] = '\0';
/* reverse the output in-place */
for (size_t j = 0; j < i; --i, ++j) {
char c = buf[i];
buf[i] = buf[j];
buf[j] = c;
}
}
return digits;
} | {
"domain": "codereview.stackexchange",
"id": 44030,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, strings, integer, converting",
"url": null
} |
performance, c, strings, integer, converting
return digits;
}
#include <stdio.h>
#include <string.h>
int test_itoa(const char *file, int line,
int n, const char *expected)
{
char buf[20];
int result = 0;
size_t actual = itoa(n, 0, 0);
if (actual != strlen(expected)) {
fprintf(stderr, "%s:%d: error: itoa(%d) returned %zu instead of %zu\n",
file, line,
n, actual, strlen(expected));
result = 1;
}
actual = itoa(n, buf, sizeof buf);
if (actual != strlen(expected)) {
fprintf(stderr, "%s:%d: error: itoa(%d) returned %zu instead of %zu\n",
file, line,
n, actual, strlen(expected));
result = 1;
}
if (strcmp(buf, expected)) {
fprintf(stderr, "%s:%d: error: itoa(%d) produced %s instead of %s\n",
file, line,
n, buf, expected);
result = 1;
}
return result;
}
#define TEST_ITOA(n, s) test_itoa(__FILE__, __LINE__, n, s)
int main(void)
{
return TEST_ITOA(0, "0")
| TEST_ITOA(1, "1")
| TEST_ITOA(10, "10")
| TEST_ITOA(12345, "12345")
| TEST_ITOA(-1, "-1")
| TEST_ITOA(-10, "-10")
| TEST_ITOA(-12345, "-12345")
;
} | {
"domain": "codereview.stackexchange",
"id": 44030,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, strings, integer, converting",
"url": null
} |
c++, array, matrix
Title: N dimensional array index utility
Question: I created the below class to help working with ND Arrays, mapping based on this question. This will help in implementing the code for handling convolutions.
How can I improve upon this? Is there something essential I'm missing from the interface?
header:
class NDArrayIndex{
public:
NDArrayIndex(
std::initializer_list<std::uint32_t> dimensions, std::int32_t padding = 0,
std::initializer_list<std::uint32_t> position = {}
);
NDArrayIndex& set(const std::vector<std::uint32_t>& position);
NDArrayIndex& step();
NDArrayIndex& step(std::uint32_t dimension, std::int32_t delta);
const std::vector<std::uint32_t>& position() const{
return m_position;
}
std::optional<std::uint32_t> calculate_mapped_position(const std::vector<std::uint32_t>& position) const;
std::optional<std::uint32_t> mapped_position() const{
return m_mappedIndex;
}
bool inside_bounds(const std::vector<std::uint32_t>& position, std::uint32_t dimension = 0u, std::int32_t delta = 0) const;
bool inside_bounds(std::uint32_t dimension = 0u, std::int32_t delta = 0) const{
return inside_bounds(m_position, dimension, delta);
}
bool inside_bounds(const NDArrayIndex& index, std::uint32_t dimension = 0u, std::int32_t delta = 0) const{
return inside_bounds(index.position(), dimension, delta);
}
bool inside_content(const std::vector<std::uint32_t>& position, std::uint32_t dimension = 0u, std::int32_t delta = 0) const;
bool inside_content(std::uint32_t dimension = 0u, std::int32_t delta = 0) const{
return inside_content(m_position, dimension, delta);
}
bool inside_content(const NDArrayIndex& index, std::uint32_t dimension = 0u, std::int32_t delta = 0) const{
return inside_content(index.position(), dimension, delta);
} | {
"domain": "codereview.stackexchange",
"id": 44031,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, matrix",
"url": null
} |
c++, array, matrix
using IntervalPart = std::pair<std::uint32_t, std::uint32_t>;
std::vector<IntervalPart> mappable_parts_of(std::uint32_t dimension, std::int32_t delta) const{
return mappable_parts_of(m_position, dimension, delta);
}
std::vector<IntervalPart> mappable_parts_of(
const std::vector<std::uint32_t>& position, std::uint32_t dimension, std::int32_t delta
) const;
std::uint32_t buffer_size(){
return m_bufferSize;
}
private:
const std::vector<std::uint32_t> m_dimensions;
const std::int32_t m_padding;
const std::vector<std::uint32_t> m_strides;
const std::uint32_t m_bufferSize;
std::vector<std::uint32_t> m_position;
std::optional<std::uint32_t> m_mappedIndex;
};
source:
NDArrayIndex::NDArrayIndex(
std::initializer_list<std::uint32_t> dimensions, std::int32_t padding,
std::initializer_list<std::uint32_t> position
)
: m_dimensions(dimensions)
, m_padding(padding)
, m_strides(init_strides(dimensions, m_padding))
, m_bufferSize(std::accumulate(m_dimensions.begin(), m_dimensions.end(), 1.0,
[](const std::uint32_t& partial, const std::uint32_t& element){ return partial * element; }
))
, m_position(init_position(m_dimensions, position))
, m_mappedIndex(calculate_mapped_position(m_position))
{
assert(0 == std::count(m_dimensions.begin(), m_dimensions.end(), 0));
assert(inside_bounds(m_position));
}
NDArrayIndex& NDArrayIndex::set(const std::vector<std::uint32_t>& position){
assert(position.size() == m_position.size());
assert(inside_bounds(position));
m_position = position;
m_mappedIndex = calculate_mapped_position(m_position);
assert( (!m_mappedIndex.has_value())||(m_mappedIndex.value() < m_bufferSize) );
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 44031,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, matrix",
"url": null
} |
c++, array, matrix
NDArrayIndex& NDArrayIndex::step(){
std::uint32_t dim = 0;
bool changed = false;
while(dim < m_dimensions.size()){
if(inside_bounds(dim, 1)){
step(dim, 1);
break;
}else{
changed = true;
m_position[dim] = 0;
}
++dim;
}
if(dim >= m_dimensions.size()){
m_mappedIndex = 0; /* Overflow happened, start from the beginning */
}else{
if(changed)m_mappedIndex = calculate_mapped_position(m_position);
assert(m_mappedIndex < m_bufferSize);
}
return *this;
}
NDArrayIndex& NDArrayIndex::step(std::uint32_t dimension, std::int32_t delta){
const std::int32_t new_position = static_cast<std::int32_t>(m_position[dimension]) + delta;
assert(0 <= new_position);
assert((m_dimensions[dimension] + (2 * std::max(0, m_padding))) > static_cast<std::uint32_t>(new_position));
m_position[dimension] = new_position;
bool new_position_is_inside_content = inside_content(m_position);
if(m_mappedIndex.has_value() && new_position_is_inside_content){ /* m_mappedIndex has a value if the previous position was valid */
m_mappedIndex.value() += m_strides[dimension] * delta;
assert(m_mappedIndex < m_bufferSize);
}else if(new_position_is_inside_content){ /* if the new position is inside bounds, then the mapped index can be caluclated */
m_mappedIndex = calculate_mapped_position(m_position);
}else m_mappedIndex = {}; /* No mapped index for positions inside the padding */
return *this;
}
std::optional<std::uint32_t> NDArrayIndex::calculate_mapped_position(const std::vector<std::uint32_t>& position) const{
assert(position.size() == m_strides.size());
if(!inside_content(position))
return {};
std::uint32_t result_index = 0u;
for(std::uint32_t dim = 0; dim < position.size(); ++dim){
result_index += (position[dim] - std::max(m_padding, -m_padding)) * m_strides[dim];
}
return result_index;
} | {
"domain": "codereview.stackexchange",
"id": 44031,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, matrix",
"url": null
} |
c++, array, matrix
bool NDArrayIndex::inside_bounds(const std::vector<std::uint32_t>& position, std::uint32_t dimension, std::int32_t delta) const{
std::uint32_t dimension_index = 0;
return std::all_of(position.begin(), position.end(),
[this, &dimension_index, dimension, delta](const std::uint32_t& pos){
std::int32_t position = static_cast<std::int32_t>(pos);
if(dimension_index == dimension) position += delta;
return( (0 <= position)&&(position < static_cast<int32_t>(2 * std::max(0, m_padding) + m_dimensions[dimension_index++])) );
}
);
}
bool NDArrayIndex::inside_content(const std::vector<std::uint32_t>& position, std::uint32_t dimension, std::int32_t delta) const{
std::uint32_t dimension_index = 0;
return std::all_of(position.begin(), position.end(),
[this, &dimension_index, dimension, delta](const std::uint32_t& pos){
std::int32_t actual_position = static_cast<std::int32_t>(pos);
if(dimension_index == dimension) actual_position += delta;
return(
(std::max(m_padding, -m_padding) <= actual_position)
&&(actual_position < static_cast<std::int32_t>(m_dimensions[dimension_index++] + m_padding))
);
}
);
} | {
"domain": "codereview.stackexchange",
"id": 44031,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, matrix",
"url": null
} |
c++, array, matrix
std::vector<NDArrayIndex::IntervalPart> NDArrayIndex::mappable_parts_of(
const std::vector<std::uint32_t>& position, std::uint32_t dimension, std::int32_t delta
) const{
std::vector<NDArrayIndex::IntervalPart> result;
bool part_in_progress = false;
for(std::int32_t delta_index = 0; delta_index < delta; delta_index += std::copysign(1, delta)){
const bool current_position_in_inside_content = inside_content(position, dimension, delta_index);
if(current_position_in_inside_content && part_in_progress){
assert(0 < result.size());
++std::get<1>(result.back()); /* Increase the size of the current part of the interval */
}else if(current_position_in_inside_content){ /* If the interval iteration became inside bounds */
result.push_back({(position[dimension] + delta_index), 1}); /* Add the new part as a result */
part_in_progress = true;
}else part_in_progress = false;
}
return result;
}
and with the following tests:
TEST_CASE("Testing NDArray Indexing with a 2D array without padding", "[NDArray]"){
std::uint32_t width = rand()%100;
std::uint32_t height = rand()%100;
NDArrayIndex idx({width, height});
for(std::uint32_t variant = 0; variant < 5; ++variant){
std::uint32_t x = rand()%width;
std::uint32_t y = rand()%height;
idx.set({x,y});
REQUIRE(idx.inside_bounds());
REQUIRE(idx.mapped_position().has_value());
REQUIRE(idx.mapped_position().value() == (x + (y * width)));
std::uint32_t elements_after_x_row = width - x;
REQUIRE(1 == idx.mappable_parts_of(0,width).size());
REQUIRE(x == std::get<0>(idx.mappable_parts_of(0,width)[0]));
REQUIRE(elements_after_x_row == std::get<1>(idx.mappable_parts_of(0,width)[0]));
/*!Note: using width in the above interfaces because it is guaranteed
* that an interval of that size spans over the relevant dimension
* */
} | {
"domain": "codereview.stackexchange",
"id": 44031,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, matrix",
"url": null
} |
c++, array, matrix
REQUIRE(idx.buffer_size() == (width * height));
idx.set({0,0});
for(std::uint32_t i = 0; i < idx.buffer_size(); ++i){
REQUIRE(idx.inside_bounds());
REQUIRE(idx.inside_content());
REQUIRE(idx.mapped_position().has_value() == true);
REQUIRE(idx.mapped_position().value() == i);
idx.step();
}
}
TEST_CASE("Testing NDArray Indexing with a 2D array with positive padding", "[NDArray][padding]"){
std::uint32_t width = 1 + rand()%20;
std::uint32_t height = 1 + rand()%20;
std::int32_t padding = 5;
NDArrayIndex idx({width, height}, padding);
for(std::uint32_t variant = 0; variant < 5; ++variant){
std::uint32_t x = padding + rand()%(width);
std::uint32_t y = padding + rand()%(height);
idx.set({x,y});
REQUIRE(idx.inside_bounds());
REQUIRE(idx.mapped_position().has_value());
REQUIRE( idx.mapped_position().value() == (x - padding + ((y - padding) * width)) );
std::uint32_t elements_after_x_row = padding + width - x;
REQUIRE(1 == idx.mappable_parts_of(0,width).size());
REQUIRE(x == std::get<0>(idx.mappable_parts_of(0,width)[0]));
REQUIRE(elements_after_x_row == std::get<1>(idx.mappable_parts_of(0,width)[0]));
} | {
"domain": "codereview.stackexchange",
"id": 44031,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, matrix",
"url": null
} |
c++, array, matrix
REQUIRE(idx.buffer_size() == (width * height));
std::uint32_t x = 0u;
std::uint32_t y = 0u;
std::uint32_t reference_mapped_position = 0u;
idx.set({0,0});
for(std::uint32_t i = 0; i < idx.buffer_size(); ++i){
if(
(padding <= static_cast<std::int32_t>(x) && x < (padding + width))
&&(padding <= static_cast<std::int32_t>(y) && y < (padding + height))
){
REQUIRE(idx.inside_bounds());
REQUIRE(idx.inside_content());
REQUIRE(idx.mapped_position().has_value() == true);
REQUIRE(idx.mapped_position().value() == reference_mapped_position);
++reference_mapped_position;
}else{
REQUIRE(idx.inside_bounds());
REQUIRE(idx.mapped_position().has_value() == false);
}
idx.step();
if(x < padding + width + padding - 1){
++x;
}else{
x = 0;
++y;
}
}
}
TEST_CASE("Testing NDArray Indexing with a 2D array with negative padding", "[NDArray][padding]"){
std::uint32_t width = 11 + rand()%20;
std::uint32_t height = 11 + rand()%20;
std::int32_t padding = -5;
NDArrayIndex idx({width, height}, padding);
for(std::uint32_t variant = 0; variant < 5; ++variant){
std::uint32_t x = -padding + rand()%(width + 2 * padding);
std::uint32_t y = -padding + rand()%(height + 2 * padding);
idx.set({x,y});
REQUIRE(idx.inside_bounds());
REQUIRE(idx.mapped_position().has_value());
REQUIRE( idx.mapped_position().value() == (x + padding + ((y + padding) * (width + 2 * padding))) );
std::uint32_t elements_after_x_row = padding + width - x;
REQUIRE(1 == idx.mappable_parts_of(0,width).size());
REQUIRE(x == std::get<0>(idx.mappable_parts_of(0,width)[0]));
REQUIRE(elements_after_x_row == std::get<1>(idx.mappable_parts_of(0,width)[0]));
} | {
"domain": "codereview.stackexchange",
"id": 44031,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, matrix",
"url": null
} |
c++, array, matrix
REQUIRE(idx.buffer_size() == (width * height));
std::uint32_t x = 0u;
std::uint32_t y = 0u;
std::uint32_t reference_mapped_position = 0u;
idx.set({0,0});
for(std::uint32_t i = 0; i < idx.buffer_size(); ++i){
if(
(-padding <= static_cast<std::int32_t>(x) && x < (padding + width))
&&(-padding <= static_cast<std::int32_t>(y) && y < (padding + height))
){
REQUIRE(idx.inside_bounds());
REQUIRE(idx.inside_content());
REQUIRE(idx.mapped_position().has_value() == true);
REQUIRE(idx.mapped_position().value() == reference_mapped_position);
++reference_mapped_position;
}else{
REQUIRE(idx.inside_bounds());
REQUIRE(idx.mapped_position().has_value() == false);
}
idx.step();
if(x < (width - 1)){
++x;
}else{
x = 0;
++y;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44031,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, matrix",
"url": null
} |
c++, array, matrix
Answer: Add Doxygen documentation
I'm having a hard time understanding what the purpose is of all those member functions. Adding Doxygen documentation for the class and all its members would be of great help.
Do you need a variable number of dimensions?
Usually when dealing with data, you already know its dimensionality. It would make more sense then to make NDArrayIndex be a template, with the template parameter being the number of dimensions, and then use std::array instead of std::vector to store the things that are now stored in std::vectors. This will allow the compiler to optimize the code much better, and avoids all the memory allocations.
Even if you don't know the number of dimensions up front, maybe you can make the template parameter be the maximum number of dimensions, so you can still use std::arrays. Consider that, at least on Linux on AMD64, the size of an empty std::vector is 24 bytes, which is the same size as a std::array<uint32_t, 6>.
Why is padding a scalar?
It's weird that m_dimensions and m_strides are vectors, but m_padding is a scalar. There is no reason why you could not have a different padding size for each dimension.
Prefer declaring a struct instead of using std::pair
While std::pair and std::tuple are sometimes helpful in generic code, if you can just declare a struct instead, prefer the latter. This allows you to give names to the two elements of the pair, and avoids the ugly calls to std::get<>():
struct IntervalPart {
std::uint32_t start;
std::uint32_t size;
}; | {
"domain": "codereview.stackexchange",
"id": 44031,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, matrix",
"url": null
} |
c++, array, matrix
Unsafe conversions between signed and unsigned integers
The API makes it seem like any unsigned 32-bit value is safe to be used, but the cast to std::int32_t inside inside_bounds() makes large values unsafe. You should handle this somehow.
Consider adding iterators
It looks to me like in the end, you want to iterate over the mappable part of a multi-dimensional array. Now you have to call a mix of mappable_parts_of(), step() and mapped_position(). But all of this is slow; if you have the mappable parts, you shouldn't need the fancyness of step(), and you don't need the bounds checking done by mapped_position(). I think that an interface that provides an iterator to efficiently iterate over a mappable part would be best. For example:
NDArray array = ...;
NDArrayIndex index = ...;
for (auto position: index.mappable_parts_range(...)) {
do_something_with(array[position]);
}
Of course, for convolutions you need two positions, one for each array you want to convolve, that move together, so you either want to be able to derive one from the other quickly, or have an even more fancy API that allows provides you with both positions simultaneously, or perhaps even pass in the arrays directly and have it return references to array elements:
NDArray array1, array2;
float sum = {};
...
for (auto& [el1, el2]: overlapping_range(array1, array2, ...)) {
sum += el1 * el2;
} | {
"domain": "codereview.stackexchange",
"id": 44031,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, matrix",
"url": null
} |
c++, beginner, game, sfml, minesweeper
Title: Minesweeper using SFML with C++
Question: Hi, I am making a Minesweeper game using SFML 2.0.
I am just a beginner in C++ and started using the framework for 2 weeks now, so it is safe to say I may have made lots of mistake especially when it comes to data types or algorithm implementations.
Before I start, I'll have to explain this two setting variables to avoid confusions:
CELLS_OFFSET = where the grid of cells position will generate. (can be used to center the cells)
CELLS_SIZE = What is the row and columns length. (not the scale value of the cell sprites)
I would really appreciate if you could take your time and review these (sort of messy) codes, and telling any mistake or bad practices^^
Settings.hpp
const unsigned short CELLS_SIZE = 14;
const unsigned short CELLS_BOMBS = 24;
int8_t CELLS_DATA[CELLS_SIZE][CELLS_SIZE]; // The hidden cell values
int8_t CELLS_SDATA[CELLS_SIZE][CELLS_SIZE]; // The cells on top of the hidden cell values
const sf::Vector2i CELLS_OFFSET = sf::Vector2i(202, 16); // The position where the grid of cells will generate
Cell.hpp & Cell.cpp
// Cell.hpp
#include <SFML/Graphics.hpp>
#ifndef CELL_HPP
#define CELL_HPP
class Cell
{
private:
sf::Sprite sprite;
sf::Texture texture;
public:
Cell();
void change(int8_t index);
void draw(sf::RenderWindow &window, sf::Vector2i position, sf::Vector2i offset);
};
#endif // CELL_HPP
// Cell.cpp
#include "Cell.hpp"
Cell::Cell()
{
this->texture.loadFromFile("Assets/Cells.png");
this->sprite.setTextureRect(sf::IntRect(0, 0, 16, 16));
this->sprite.setTexture(texture);
}
void Cell::change(int8_t index)
{
this->sprite.setTextureRect(sf::IntRect(16 * index, 0, 16, 16));
}
void Cell::draw(sf::RenderWindow &window, sf::Vector2i position, sf::Vector2i offset)
{
this->sprite.setPosition(position.x * 32 + offset.x, position.y * 32 + offset.y);
this->sprite.setScale(2, 2);
window.draw(this->sprite);
} | {
"domain": "codereview.stackexchange",
"id": 44032,
"lm_label": 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, game, sfml, minesweeper",
"url": null
} |
c++, beginner, game, sfml, minesweeper
Main.cpp
#include <SFML/Graphics.hpp>
#include "Cell.hpp"
#include "Settings.hpp"
int main()
{
sf::RenderWindow window(sf::VideoMode(852, 480), "Minesweeper", sf::Style::Titlebar | sf::Style::Close);
window.setVerticalSyncEnabled(true);
// Define the cell class and randomly seed the bombs
Cell cell; srand(time(0));
// Fill Bomb Cells
for (short x = 0; x < CELLS_BOMBS; x++)
{
int8_t &cell_location = CELLS_DATA[rand() % CELLS_SIZE][rand() % CELLS_SIZE];
if (cell_location == 9)
x--;
else
cell_location = 9;
}
// Fill Number Cells
for (short x = 0; x < CELLS_SIZE; x++) for (short y = 0; y < CELLS_SIZE; y++)
{
int8_t &cell_location = CELLS_DATA[x][y];
if (cell_location == 9) continue; // Skip if this cell is a bomb
for (int8_t rx = -1; rx < 2; rx++) for (int8_t ry = -1; ry < 2; ry++) {
// Skip if this cell is out of bounds
if (x + rx > CELLS_SIZE - 1 || y + ry > CELLS_SIZE - 1 || x + rx < 0 || y + ry < 0 || (rx == 0 && ry == 0)) continue;
// Increases the number if the neighbor cell has a bomb
if (CELLS_DATA[x + rx][y + ry] == 9) cell_location++;
}
}
// Game Loop
while (window.isOpen())
{
sf::Vector2i cell_position = sf::Vector2i(std::floor((sf::Mouse::getPosition(window).x - CELLS_OFFSET.x) / 32.0), std::floor((sf::Mouse::getPosition(window).y - CELLS_OFFSET.y) / 32.0)); // I would appreciate if someone optimize this line
bool cell_bounds = cell_position.x >= 0 && cell_position.x < CELLS_SIZE && cell_position.y >= 0 && cell_position.y < CELLS_SIZE; // Used to check if the cursor position is inside the grid of cells
int8_t &cell_location = CELLS_DATA[cell_position.x][cell_position.y];
int8_t &cell_slocation = CELLS_SDATA[cell_position.x][cell_position.y]; | {
"domain": "codereview.stackexchange",
"id": 44032,
"lm_label": 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, game, sfml, minesweeper",
"url": null
} |
c++, beginner, game, sfml, minesweeper
sf::Event event; while (window.pollEvent(event))
{
// Cells Input
if (event.type == sf::Event::MouseButtonPressed && cell_bounds) switch(event.mouseButton.button)
{
case sf::Mouse::Left: // Cell Opening
if (cell_slocation != 0) continue;
cell_slocation = -1;
// Flood Fill (BFS)
if (cell_location != 0) continue;
{
std::vector<sf::Vector2i> queue = {cell_position};
while (true)
{
// Get the first queue vector2 for checking it's neighbors
sf::Vector2i queue_first_position = sf::Vector2i(queue.at(0).x, queue.at(0).y);
// Loop through neigboring cells
for (int8_t rx = -1; rx < 2; rx++) for (int8_t ry = -1; ry < 2; ry++) {
// The cell must not be on out of bounds
if (queue_first_position.x + rx > CELLS_SIZE - 1 || queue_first_position.y + ry > CELLS_SIZE - 1 || queue_first_position.x + rx < 0 || queue_first_position.y + ry < 0 || (rx == 0 && ry == 0)) continue;
int8_t &neighbor_location = CELLS_DATA[queue_first_position.x + rx][queue_first_position.y + ry];
int8_t &neighbor_slocation = CELLS_SDATA[queue_first_position.x + rx][queue_first_position.y + ry];
// The cell must be already opened, and it is not a bomb
if (neighbor_slocation == -1 || neighbor_location == 9) continue;
// Open the cell
neighbor_slocation = -1;
// The cell must empty
if (neighbor_location != 0) continue; | {
"domain": "codereview.stackexchange",
"id": 44032,
"lm_label": 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, game, sfml, minesweeper",
"url": null
} |
c++, beginner, game, sfml, minesweeper
// Add the cell's vector2 to queue
queue.push_back(sf::Vector2i(queue_first_position.x + rx, queue_first_position.y + ry));
}
// Remove the first element in the queue for checking if done filling
queue.erase(queue.begin());
if (queue.size() <= 0) break;
}
}
break;
case sf::Mouse::Right: // Cell Flagging
if (cell_slocation == 1)
cell_slocation = 0;
else if (cell_slocation == 0)
cell_slocation = 1;
break;
}
if (event.type == sf::Event::Closed) window.close();
}
// Cells Render
for (short x = 0; x < CELLS_SIZE; x++) for (short y = 0; y < CELLS_SIZE; y++)
{
switch(CELLS_SDATA[x][y])
{
case 0: cell.change(10); break; // Unopened Cell
case 1: cell.change(11); break; // Flagged Cell
default: cell.change(CELLS_DATA[x][y]); // Numbered Cell
}
cell.draw(window, sf::Vector2i(x, y), CELLS_OFFSET);
}
// Cells Highlight
if (cell_bounds && ((cell_slocation == -1 && cell_location != 0) || (cell_slocation != -1)))
{
sf::RectangleShape highlight(sf::Vector2f(32, 32));
highlight.setFillColor(sf::Color(255, 255, 255, 30));
highlight.setPosition(cell_position.x * 32 + CELLS_OFFSET.x, cell_position.y * 32 + CELLS_OFFSET.y);
window.draw(highlight);
}
window.display();
window.clear();
}
return EXIT_SUCCESS;
}
Regarding about the code, I kept using this data type int8_t to store the value of the cells. I wonder if it that's a good practice or not. | {
"domain": "codereview.stackexchange",
"id": 44032,
"lm_label": 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, game, sfml, minesweeper",
"url": null
} |
c++, beginner, game, sfml, minesweeper
Preview
Answer: Congratulations making a working game! As you already suspected, there are indeed some things that can be improved:
Rethink the structure of your code
You have had some idea about organizing your code in different files and using classes. However, the vast majority of the code is all in main(). You should really try to add more structure to your code. As a rule of thumb, try not to make functions longer than 20 lines of code, and split them up if they do. Code and functionality that belongs together should be put in its own class. You did this for Cell, but you could also have created a class Board that represents the whole board.
Another trick when writing a function is to write a few lines that describe in a high level what the function does, and then create more functions that implement the low-level details, which in turn call even lower-level functions if necessary. Consider main(): it should look like:
int main()
{
// 1. Initialize
// 2. Run game loop
// 3. Cleanup
}
Now turn this into a real function, and for each step only use a few lines of code, or delegate to a (member) function if it would be more. So for example:
int main()
{
// 1. Initialize
sf::RenderWindow window(sf::VideoMode(852, 480), "Minesweeper", sf::Style::Titlebar | sf::Style::Close);
window.setVerticalSyncEnabled(true);
Board board;
// 2. Run game loop
while (window.isOpen())
{
handleEvents(window, board);
renderGame(window, board);
}
// 3. Cleanup
return EXIT_SUCCESS;
}
For the above code to work, a class Board has to be created that fills bomb and number cells in its constructor, and a function handleEvents() has to be created that reads window events and updates the board accordingly. That function can look like:
void handleEvents(sf::RenderWindow &window, Board &board)
{
sf::Event event; | {
"domain": "codereview.stackexchange",
"id": 44032,
"lm_label": 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, game, sfml, minesweeper",
"url": null
} |
c++, beginner, game, sfml, minesweeper
while (window.pollEvent(event))
{
switch(event.type)
{
case sf::MouseButtonPressed:
handleMouseButtonPressed(window, board, event);
break;
case sf::Event::Closed:
window.close();
}
}
}
In turn, a function handleMouseButtonPressed() has to be created that checks which mouse button is pressed, looks at the coordinates (which are also part of the event.mouseButton, no need to call sf::Mouse::getPosition()), and updates the board.
Note that these small functions are easy to read and understand. They have names that describe what they do, so there is less need to write comments to explain what your code is doing.
Avoid long lines of code
Some of your lines are very long, in particular the one that calculates which cell is under the mouse pointer. Try to reduce the length of lines, either by adding line breaks, by splitting one statement into multiple statements, or by moving the complicated parts into their own function. For example:
sf::Vector2i get_cell_position(int x, int y)
{
x = (x - CELLS_OFFSET.x) / 32;
y = (y - CELLS_OFFSET.y) / 32;
return {x, y};
}
...
sf::Vector2i cell_position = get_cell_position(event.mouseButton.x, event.mouseButton.y); | {
"domain": "codereview.stackexchange",
"id": 44032,
"lm_label": 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, game, sfml, minesweeper",
"url": null
} |
c++, beginner, game, sfml, minesweeper
Also, some lines of code contain multiple statements, like the nested for-loops. A common rule in coding style guides is to never have more than one statement on a single line. This keeps lines shorter, but also avoids surprises if there is another statement on a line, but it is not visible because it was too far to the right.
Make the most of the libraries you use
The above can be further simplified, if you make more use of sf::Vector2i: the latter allows you to do simple arithmetic as well, so you can write:
sf::Vector2i get_cell_position(sf::Vector2i mouse_position)
{
return (mouse_position - CELLS_OFFSET) / 32;
}
...
sf::Vector2i mouse_position = {event.mouseButton.x, event.mouseButton.y};
sf::Vector2i cell_position = get_cell_position(mouse_position); | {
"domain": "codereview.stackexchange",
"id": 44032,
"lm_label": 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, game, sfml, minesweeper",
"url": null
} |
c++, beginner, game, sfml, minesweeper
Avoid hardcoding and magic numbers
In Settings.hpp, you made an effort to give names to some constants, such as the size of the board and the number of bombs. However, there are many constants that are not named in your code, such as the size of a cell (32), the value that indicates a cell is a bomb (9), and so on. Try to find all these numbers and make constants for them. The advantage is that it makes it easier for someone else reading the code to know what a number represents, and also allows you to change a constant in a single location, without having to go through all the code to search and replace those constants.
Even if you name all the constants, consider whether some things should be constant. It might make sense for the size of a cell, since you want it to match the size of the image you have for it, but what about the window size, or the size of the board or the number of bombs?
Try to see if you can make more things variable. This might require some more extensive changes to your code; for example the CELLS_DATA[][] and CELLS_SDATA[][] arrays no longer compile if CELLS_SIZE is not a constant. You might have to use std::vector or something similar to store cells instead.
Create a struct for the cell's state
You have a class Cell that handles drawing a cell, but there is also the state a cell is in. This is currently stored in two arrays as int8_ts. However, consider creating a struct that holds all the information of the state of a single cell. Also, consider creating an enum that encodes whether a cell is hidden, visible or flagged:
enum class CellState {
HIDDEN,
FLAGGED,
VISIBLE,
};
struct CellData
{
int8_t neighbours;
CellState state;
};
Then you only need one array:
CellData cells[CELLS_SIZE][CELLS_SIZE]; | {
"domain": "codereview.stackexchange",
"id": 44032,
"lm_label": 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, game, sfml, minesweeper",
"url": null
} |
c++, beginner, game, sfml, minesweeper
Then you only need one array:
CellData cells[CELLS_SIZE][CELLS_SIZE];
Naming things
Some things in your code have names that are confusing. For example, CELLS_SIZE sounds like the size of a cell, but it's actually the size of the board. So BOARD_SIZE would be a better name. CELLS_BOMBS should be renamed to NUMBER_OF_BOMBS, N_BOMBS or BOMB_COUNT.
When adding bombs to the board, you use x as the loop counter. However, x is usually associated with an x-coordinate. I would use i instead, it's the well-known name for a generic loop index.
Make sure names are clear, concise and unambiguous.
The first click should be safe
Many versions of Minesweeper ensures that the first time you click on the board, there is no bomb under the mouse. The reason is that it doesn't make sense to put a flag as the first move, and it would be perceived as unfair as the first move you make could cause you to lose without any mistake from the player.
There are several ways to implement this; if the first click is on a bomb, you could remove the bomb or place it elsewhere, and fix up the neighbor counts. Alternatively, you can delay placing bombs until the player has clicked somewhere. | {
"domain": "codereview.stackexchange",
"id": 44032,
"lm_label": 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, game, sfml, minesweeper",
"url": null
} |
c#, game, unity3d
Title: Weapon shoot system FPS Game
Question: Hello I'm currently developing a FPS game for my portfolio and I made a weapon shoot system, and I would like to receive feedback about my code to make more cleaner and efficient. Thanks.
using UnityEngine;
[RequireComponent(typeof(PlayerGunController))]
public class PlayerGunShootManager : MonoBehaviour
{
private PlayerGunController _playerGunController;
[SerializeField] private int _bulletDamage;
[SerializeField] private int _gunMagazineSize;
[SerializeField] private int _bulletsPerShoot;
[SerializeField] private float _shootDelay;
[SerializeField] private float _bulletSpreadRange;
[SerializeField] private float maxDistanceTheBulletCanHit;
[SerializeField] private LayerMask _bulletLayerMask;
[SerializeField] private Transform bulletSpawmPosition;
private float _gunReloadTime;
private bool _playerCanShoot = true;
private int _bulletsLeft;
private Vector3 _randomBulletSpreadRangeValue = new Vector3(0f, 0f, 0f);
private readonly RaycastHit[] rayHit = new RaycastHit[4];
private float _defaultBulletSpreadRangeValue;
private const string EnemyTag = "Enemy";
public bool PlayerIsShooting { get; private set; }
public bool PlayerIsReloading { get; private set; }
private void Awake()
{
_playerGunController = GetComponent<PlayerGunController>();
_defaultBulletSpreadRangeValue = _bulletSpreadRange;
}
private void Start()
{
_playerGunController.GetPlayerController().PlayerInputsManager.OnPlayerIsPressingShootButton += PlayerIsPressingShootButton;
_playerGunController.GetPlayerController().PlayerInputsManager.OnPlayerStoppedPressingShootButton += PlayerHasStoppedShooting;
_playerGunController.GetPlayerController().PlayerInputsManager.OnPlayerPressedReloadButton += ReloadGun; | {
"domain": "codereview.stackexchange",
"id": 44033,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, unity3d",
"url": null
} |
c#, game, unity3d
_playerGunController.GetPlayerController().PlayerInputsManager.OnPlayerIsPressingAimButton += ChangeBulletSpreadValueToMorePrecise;
_playerGunController.GetPlayerController().PlayerInputsManager.OnPlayerStoppedPressingAimButtom += ChangeBulletSpreadRangeToDefaultValue;
_bulletsLeft = _gunMagazineSize;
_gunReloadTime = _playerGunController.PlayerGunAnimationManager.GetGunReloadAnimationTime();
}
private void Update()
{
if (CheckIfPlayerCanShoot() && PlayerIsShooting)
{
Shoot();
}
}
private bool CheckIfPlayerCanShoot()
{
return _playerCanShoot && !PlayerIsReloading && _bulletsLeft > 0;
}
private void Shoot()
{
_playerCanShoot = false;
_bulletsLeft -= _bulletsPerShoot;
Vector3 directionBulletRaycastShouldGo = bulletSpawmPosition.forward + GetRandomBulletSpreadValue();
if (Physics.RaycastNonAlloc(transform.position, directionBulletRaycastShouldGo, rayHit, maxDistanceTheBulletCanHit, _bulletLayerMask) > 0)
{
for (int i = 0; i < rayHit.Length; i++)
{
if (rayHit[i].collider != null && rayHit[i].collider.gameObject.CompareTag(EnemyTag))
{
Damageable damageable = rayHit[i].collider.gameObject.GetComponent<Damageable>();
damageable.TakeDamage(_bulletDamage);
break;
}
}
}
if (_bulletsLeft > 0)
{
Invoke(nameof(AllowPlayerShootAgain), _shootDelay);
return;
}
ReloadGun();
}
private void ChangeBulletSpreadRangeToDefaultValue()
{
_bulletSpreadRange = _defaultBulletSpreadRangeValue;
}
private void ChangeBulletSpreadValueToMorePrecise()
{
_bulletSpreadRange *= 0.5f;
} | {
"domain": "codereview.stackexchange",
"id": 44033,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, unity3d",
"url": null
} |
c#, game, unity3d
private Vector3 GetRandomBulletSpreadValue()
{
_randomBulletSpreadRangeValue.x = Random.Range(-_bulletSpreadRange, _bulletSpreadRange);
_randomBulletSpreadRangeValue.y = Random.Range(-_bulletSpreadRange, _bulletSpreadRange);
return _randomBulletSpreadRangeValue;
}
private void AllowPlayerShootAgain()
{
_playerCanShoot = true;
}
private void PlayerHasStoppedShooting()
{
PlayerIsShooting = false;
PlayerGlobalGunManager.SetPlayerIsShootingToFalse();
}
private void PlayerIsPressingShootButton()
{
PlayerIsShooting = true;
PlayerGlobalGunManager.SetPlayerIsShootingToTrue();
}
private void ReloadGun()
{
if (!PlayerIsReloading && _bulletsLeft < _gunMagazineSize)
{
PlayerIsReloading = true;
PlayerGlobalGunManager.SetPlayerIsReloadingToTrue();
Invoke(nameof(ReloadFinished), _gunReloadTime);
}
}
private void ReloadFinished()
{
_bulletsLeft = _gunMagazineSize;
PlayerIsReloading = false;
PlayerGlobalGunManager.SetPlayerIsReloadingToFalse();
AllowPlayerShootAgain();
}
}
Answer: _playerGunController.GetPlayerController().PlayerInputsManager.OnPlayerIsPressingShootButton += PlayerIsPressingShootButton;
_playerGunController.GetPlayerController().PlayerInputsManager.OnPlayerStoppedPressingShootButton += PlayerHasStoppedShooting;
_playerGunController.GetPlayerController().PlayerInputsManager.OnPlayerPressedReloadButton += ReloadGun;
_playerGunController.GetPlayerController().PlayerInputsManager.OnPlayerIsPressingAimButton += ChangeBulletSpreadValueToMorePrecise;
_playerGunController.GetPlayerController().PlayerInputsManager.OnPlayerStoppedPressingAimButtom += ChangeBulletSpreadRangeToDefaultValue; | {
"domain": "codereview.stackexchange",
"id": 44033,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, unity3d",
"url": null
} |
c#, game, unity3d
That's a lot of copying. You can put _playerGunController.GetPlayerController().PlayerInputsManager into a variable and use it instead of retrieving it again every time.
private bool CheckIfPlayerCanShoot()
{
return _playerCanShoot && !PlayerIsReloading && _bulletsLeft > 0;
}
If this method decides whether the player can shoot or not, then what is _playerCanShoot. It turns out that sometimes _playerCanShoot == true (which suggests to the reader that the player can indeed shoot) but CheckIfPlayerCanShoot() will return false. Who should we trust?
If you can shoot if _bulletsLeft > 0, nothing stops you from shooting with one bullet in the magazine even if your _bulletsPerShoot is higher than one which makes your _bulletsLeft negative.
if (Physics.RaycastNonAlloc(transform.position, directionBulletRaycastShouldGo, rayHit, maxDistanceTheBulletCanHit, _bulletLayerMask) > 0)
{
for (int i = 0; i < rayHit.Length; i++)
rayHit.Length is always 4 since you made it that way. What you should check for is the result of Physics.RaycastNonAlloc(...) that you just got.
if (_bulletsLeft > 0)
Invoke(nameof(AllowPlayerShootAgain), _shootDelay);
return;
}
ReloadGun();
Again this doesn't take _bulletsPerShoot into account.
private void PlayerHasStoppedShooting()
{
PlayerIsShooting = false;
PlayerGlobalGunManager.SetPlayerIsShootingToFalse();
}
private void PlayerIsPressingShootButton()
{
PlayerIsShooting = true;
PlayerGlobalGunManager.SetPlayerIsShootingToTrue();
}
Those functions do the exact opposite things but their names don't reflect it.
Overall pretty well written, keep it up! | {
"domain": "codereview.stackexchange",
"id": 44033,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, game, unity3d",
"url": null
} |
python, functional-programming
Title: Create a function with two parameters: a list and a string, where the string has the following values
Question: I tried so many things to do this task. I have no idea why doesn't it work. Please help!
'''Create a function in Python that accepts two parameters. The first will be a list of numbers. The second parameter will be a string that can be one of the following values: asc, desc, and none.
If the second parameter is "asc," then the function should return a list with the numbers in ascending order. If it's "desc," then the list should be in descending order, and if it's "none," it should return the original list unaltered '''
def func(*args, str):
list1=args
if str == 'asc':
a = sorted(list1,reverse=False)
print(a)
elif str == 'desc':
b = sorted(list1,reverse=True)
print(b)
else:
print(list1)
l = [2,3,7,6,5]
m = 'asc'
print(func(l,m))
I know that I also have to do 'none' for str, but I don't know how
Answer: Ok so when you do
function(*args, str):
...
args collects all positional arguments, str then becomes a keyword only argument.
Since you pass the values as a single list instead of multiple single values you don't even need the *
function(args, str): # will work just fine
....
Another thing not directly related to the functionality of this specific code is that you really shouldn't use built-in names like that, even though here it's limited to the function scope. | {
"domain": "codereview.stackexchange",
"id": 44034,
"lm_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, functional-programming",
"url": null
} |
rust
Title: implement `getcwd(3)` in Rust
Question: I am trying to implement a getcwd(3) (or env::current_dir() in Rust std).
In the implementation, I use a Composer (an iterator) to yield (call next() on Composer) each path entry:
CWD = /home/steve, returns Ok(Some("steve"))
CWD = /home, returns Some(Ok("home"))
CWD = /, returns None
Src
Playground Link
use std::{
collections::VecDeque,
env::set_current_dir,
ffi::OsString,
fs::{metadata, read_dir, File},
io::Result,
os::{linux::fs::MetadataExt, unix::io::AsRawFd},
path::PathBuf,
};
use libc::{fchdir, PATH_MAX};
/// A CWD composer, returns the next path entry
///
/// ##### Example
/// * `/home/steve` -> `Some(Ok("steve"))`
/// * `/home` -> `Some(Ok("home"))`
/// * `/` -> `None`
struct Composer;
impl Composer {
fn new() -> Self {
Composer
}
}
impl Iterator for Composer {
type Item = Result<OsString>;
fn next(&mut self) -> Option<Self::Item> {
let cur_dir_metadata = match metadata(".") {
Ok(m) => m,
Err(e) => return Some(Err(e)),
};
let parent_metadata = match metadata("..") {
Ok(m) => m,
Err(e) => return Some(Err(e)),
};
// reaches root
if cur_dir_metadata.st_dev() == parent_metadata.st_dev()
&& cur_dir_metadata.st_ino() == parent_metadata.st_ino()
{
return None;
}
// cd to parent dir
if let Err(e) = set_current_dir("..") {
return Some(Err(e));
}
let dir = match read_dir(".") {
Ok(dir) => dir,
Err(e) => return Some(Err(e)),
};
for res_entry in dir {
let entry = match res_entry {
Ok(entry) => entry,
Err(e) => return Some(Err(e)),
};
let entry_metadata = match entry.metadata() {
Ok(m) => m,
Err(e) => return Some(Err(e)),
}; | {
"domain": "codereview.stackexchange",
"id": 44035,
"lm_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
if entry_metadata.st_dev() == cur_dir_metadata.st_dev()
&& entry_metadata.st_ino() == cur_dir_metadata.st_ino()
{
return Some(Ok(entry.file_name()));
}
}
unreachable!("This is unreachable unless there is something wrong with your file system");
}
}
pub fn getcwd() -> Result<PathBuf> {
let cwd = File::open(".")?;
let comp = Composer::new();
let mut entries = VecDeque::new();
for item in comp {
entries.push_front(item?);
}
let mut res = OsString::with_capacity(PATH_MAX as usize);
entries.iter().for_each(|entry| {
res.push("/");
res.push(entry);
});
res.shrink_to_fit();
unsafe { fchdir(cwd.as_raw_fd()) };
Ok(PathBuf::from(res))
}
Problem
I am not satisfied with the implementation of Composer::next(). Within this method, I have used a lot of functions whose return value is std::io::Result<T>, if the return value is an Err(e), I have to match against it and return Some(Err(e)). I kind of think this is not idiomatic and Rusty. Can I avoid this or change it to a more natural way?
Answer: For your primary question, my strategy would be something like:
impl Composer {
fn next_component(&self) -> Result<Option<OsStr>> {
// do your main logic here, since it returns a result, you
// use ? and simplify the code nicely.
}
}
impl Iterator for Composer {
fn next(&mut self) -> Self::Item {
self.next_component().invert()
}
}
Manipulating the current working directory as part of the algorithm is asking for trouble. Instead, you should at least use increasing chains of ".." to ask for parent directories. Honestly, though, getting the current working directory is so low level that its hard to meaningfully reimplement it yourself. | {
"domain": "codereview.stackexchange",
"id": 44035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
python
Title: Employee Company Emulator
Question: I have the following code:
class HiringRequirements:
def employee_eligible(self, employee, role):
if employee.grades_percent_average >= self.minimum_hiring_grades_percent:
if not self.role_occupied(role):
return True
else:
print("Somebody is occupying this position.")
return False
else:
print("You did not meet our requirements")
return False
def role_occupied(self, role):
for (key, value) in self.employee_dict.items():
for (attr, package) in value.items():
if package == role:
return True
else:
return False
class Hirer:
def employee_application(self, employee, role):
apply = self.hire_employee(employee, role)
hired = apply
if hired:
self.give_post(employee, role)
def hire_employee(self, employee, role):
if self.employee_eligible(employee, role):
key = len(self.employee_dict)
value = employee.__dict__
self.employee_dict[key] = value
# returns index of employee in list, used later
print("You got the job")
return True
else:
return False
def give_post(self, employee, role):
employee.employee_num = len(self.employee_dict) - 1
employee.has_job = True
employee.role = role
employee.available_leaves = self.employee_max_leaves
employee.salary_dollars = employee.grades_percent_average * 1000
employee.company = self
class LeaveValidator:
def employee_ask_leaves(self, employee, leaves_required):
ask_leaves = self.give_leaves(employee, leaves_required)
if ask_leaves:
employee.working_days -= leaves_required | {
"domain": "codereview.stackexchange",
"id": 44036,
"lm_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
def give_leaves(self, employee, leaves_required):
if leaves_required <= 3 and employee.available_leaves - leaves_required >= 0:
employee.available_leaves -= leaves_required
print("Leaves are granted.")
return True
else:
print("Leaves can't be granted.")
return False
class Company(Hirer, HiringRequirements, LeaveValidator):
def __init__(self, name):
self.minimum_hiring_grades_percent = 90
self.employee_max_leaves = 30
self.name = name
self.employee_dict = {}
def promote_employee(self, employee, salary_increase):
employee.salary_dollars += salary_increase
if not "Head" in employee.role:
employee.role = f"Head {employee.role}"
print(f"{employee.name} is promoted to {employee.role}")
def print_company_employees(self):
self.employees = [
v
for (key, value) in self.employee_dict.items()
for (k, v) in value.items()
if k == "name"
]
print(self.employees)
def employee_fire(self, employee):
self.employee_dict.pop(employee.employee_num)
self.employee_del_attr(employee)
print(f"{employee.name} is fired from {self.name}")
def employee_resignation(self, employee):
self.employee_dict.pop(employee.employee_num)
self.employee_del_attr(employee)
def employee_del_attr(self, employee):
del employee.company
del employee.salary_dollars
del employee.employee_num
employee.has_job = False
class Employee:
def __init__(self, name, number, grades):
self.name = name
self.number = number
self.working_days = 300
self.bonus_percent = 30
self.has_job = False
self.grades_percent_average = grades
self.employee_num = None
I believe my code isn't the most design friendly so,
I would like to receive feedback on: | {
"domain": "codereview.stackexchange",
"id": 44036,
"lm_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
I believe my code isn't the most design friendly so,
I would like to receive feedback on:
If HiringRequirements and Hirer should be merged.
If methods such as employee_resignation and employee_fire should have their own
class for example: RemoveEmployee
Answer: class Company(Hirer, HiringRequirements, LeaveValidator):
is an interesting implementation of c# partial through python's multiple inheritance, although it comes with some serious problems. To be honest, this is the first time I see it used like that, thumbs up for ingenuity (but don't do that ever again).
By looking at HiringRequirements we can't tell what self.minimum_hiring_grades_percent and self.employee_dict.items are since they are not defined here.
These classes don't encapsulate any data and they can't be used in any way other than being a base class for Company which makes them just a bunch of related methods grouped under a header.
Instead you can turn them into real classes:
class HrDepartment:
def __init__(self):
self.employee_dict = {}
self.min_hiring_grades = DEFAULT_MIN_HIRING_GRADES
self.employee_max_leaves = DEFAULT_EMPLOYEE_MAX_LEAVES
def employee_application(self, employee, role):
...
def hire_employee(self, employee, role):
...
def give_post(self, employee, role):
...
def employee_eligible(self, employee, role):
...
def role_occupied(self, role):
...
Now we have our own data to work with! And it's fully defined in the constructor.
Now instead of inheritance () use composition ():
class Company():
def __init__(self, name):
self.name = name
self.hr_department = HrDepartment()
def employee_fire(self, employee):
self.hr_department.employee_dict.pop(employee.employee_num)
self.employee_del_attr(employee)
print(f"{employee.name} is fired from {self.name}") | {
"domain": "codereview.stackexchange",
"id": 44036,
"lm_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
Company.employees and Employee.salary_dollars are not defined in the constructor block which makes in unclear what fields our classes actually have. Read more on this here.
Storing employees in a dict is weird, especially since the keys are... just their serial numbers? You could use list for that. Also for practice I would recommend making a tree for that purpose where each Manager(Employee) stores a list of their direct subordinates. A simple list is fine though if you don't want hierarchy.
Method names should reflect what they do and what to expect in return. You follow this rule mostly but there are some places for improvement:
is_role_occupied instead of role_occupied
is_employee_eligible instead of employee_eligible
employee_application should be a part of hire_employee
ask_for_leave (instead of employee_asks_leaves) should be an instance method of Employee
resign (instead of employee_resignation) should be an instance method of Employee
To sum it up: when you write a class make sure it encapsulates data and (optionally) does something with that data (instance methods). Writing a company model like this is a great way to practice OOP. Good luck! | {
"domain": "codereview.stackexchange",
"id": 44036,
"lm_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
} |
c++, matrix, classes
Title: Sparse String Matrix Storage Class C++
Question: Introduction
I implemented a class to store a matrix with entries at positions (i,j) that are strings. The matrices I would like to efficiently store in this class have strings as entries and it occurs very often that entries are the same. I am at the moment not interested in reading out the matrix, but to store the overall information as efficiently as possible.
Code
My class looks as follows
#include <vector>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
struct DataClass {
std::vector<uint64_t> matrix_element_is {};
std::vector<uint64_t> matrix_element_js {};
std::vector<uint64_t> matrix_amplitude_ids {};
std::vector<std::string> amplitudes {};
void reserve(uint64_t const s_me_ids, uint64_t const s_ma_ids, uint64_t const r_amps) {
matrix_element_is.reserve(s_me_ids);
matrix_element_js.reserve(s_me_ids);
matrix_amplitude_ids.reserve(s_ma_ids);
amplitudes.reserve(r_amps);
}
void add_matrix_element(uint64_t const i, uint64_t const j, std::string const & elm) {
matrix_element_is.push_back(i);
matrix_element_js.push_back(j);
auto const it = std::find(std::begin(amplitudes),std::end(amplitudes),elm);
matrix_amplitude_ids.push_back(distance(std::begin(amplitudes),it));
if (it == std::end(amplitudes)) amplitudes.push_back(elm);
}
void write_to_file(std::string const & fn) const {
std::ofstream f(fn);
for (auto & e: amplitudes) f << e << "\n";
for (uint64_t i {}; i < matrix_element_is.size(); ++i){
f << matrix_element_is[i] << "," << matrix_element_js[i] << "," << matrix_amplitude_ids[i];
if (i==(matrix_element_is.size()-1)) break;
f << "\n";
}
f << std::flush;
f.close();
}
}; | {
"domain": "codereview.stackexchange",
"id": 44037,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, matrix, classes",
"url": null
} |
c++, matrix, classes
};
int main () {
DataClass B {};
B.add_matrix_element(0UL,0UL,"h0");
B.add_matrix_element(1UL,1UL,"h1");
B.add_matrix_element(1UL,2UL,"h1");
B.add_matrix_element(0UL,1UL,"h0");
for (auto & e : B.matrix_element_is) std::cout << e << " ";
std::cout << std::endl;
for (auto & e : B.matrix_element_js) std::cout << e << " ";
std::cout << std::endl;
for (auto & e : B.matrix_amplitude_ids) std::cout << e << " ";
std::cout << std::endl;
for (auto & e : B.amplitudes) std::cout << e << " ";
std::cout << std::endl;
B.write_to_file("test.dat");
}
The class has basically three functionalities:
Reserving memory for the vectors that store the data
Storing new entries. A new entry (i,j,s) is stored, by appending i and j to the respective vectors. The string is stored in the amplitudes vector, if the string is not yet in the amplitudes vectors. The position of the amplitude in the amplitudes vector is then stored to associate the correct amplitude with the respective (i,j)
Writing the class to a file
I also included some demo of the class in the main function.
My main question would be:
Do you have ideas how to store the the information (uint64_t,uint64_t,std::string) more compactly and efficiently?
And do have ideas how to store the struct more efficiently in a file?
Otherwise I would also be interested in feedback:
If there are any evident flaws in the layout of my struct?
There are stylistic improvements I can make to my code? | {
"domain": "codereview.stackexchange",
"id": 44037,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, matrix, classes",
"url": null
} |
c++, matrix, classes
Answer: We're missing an include of <iterator>. This can be made more obvious by sorting the standard library includes.
You seem to have misspelt std::uint64_t throughout. Are you sure you need exactly 64 bits, or would std::uint_least64_t be a better choice?
Also misspelt: std::distance.
The parallel vectors matrix_element_is, matrix_element_js and matrix_amplitude_ids will be more efficient if those are in a single array containing a suitable aggregate type. In any case, the storage should be class-private to avoid breaking its internal consistency.
Linear search in amplitudes is going to get expensive when this gets large. Consider a pair of std::map instead. Or a single std::map if write_to_file is infrequent.
There's nothing to prevent us adding duplicate entries, and no way to retrieve any element that's stored.
write_to_file() is usually implemented as operator<<. Then it's easier to test (as we can write to a std::ostringstream and examine that), and it has a standard way to report failure (through the fail bit of the stream). This implementation gives us no way of knowing whether write_to_file() successfully wrote the whole contents to file or not.
There's no way to reliably read back from file, as we have no way to tell where each amplitude element ends and the next one begins.
f << std::flush is pointless, as that's implied by the immediately following f.close(). | {
"domain": "codereview.stackexchange",
"id": 44037,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, matrix, classes",
"url": null
} |
python
Title: Extract value from config.json (Python)
Question: Usually my project directory structure look like:
project_name/
lib/
utils.py
logs/
main.py
requirements.txt
config.json
My config.json file looks like:
{
"api": {
"api_key": "abcdefg",
"api_secret": "hijklmn"
},
"trading": {
"invest_amount": 50,
"mode": "futures",
"cumulative_position": false
}
}
In utils.py, I have a class Config
import typing
import inspect
import os
import json
from typing import Any
class Config(object):
_CONFIG_FILE: typing.Optional[str] = None
_CONFIG: typing.Optional[dict] = None
def __init__(self):
config_file = Config.get_config_path(frame=inspect.stack()[1])
with open(config_file, 'r') as f:
Config._CONFIG = json.load(f)
@staticmethod
def get_config_path(frame: inspect.FrameInfo, config_file_name: str = "config.json") -> str:
caller_file_name = frame[0].f_code.co_filename
caller_folder_name = os.path.dirname(caller_file_name)
config_file_name = os.path.join(caller_folder_name, config_file_name)
return config_file_name
@staticmethod
def get_config_value(param: str) -> Any:
for key in Config._CONFIG.keys():
value = Config._CONFIG.get(key).get(param, None)
if value is not None:
return value
raise ValueError(f"{param} doesn't exist")
And I will use it in main.py usually:
from lib.utils import Config
def main(trading_mode, invest_amount, cumulative_position):
print(trading_mode, invest_amount, cumulative_position)
if __name__ == "__main__":
config = Config()
main(trading_mode=config.get_config_value(param="mode"),
invest_amount=config.get_config_value(param="invest_amount"),
cumulative_position=config.get_config_value(param="cumulative_position")) | {
"domain": "codereview.stackexchange",
"id": 44038,
"lm_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
Is there any code that can improve or rewrite in class Config, for the purpose of efficiency, readability or clear logic, etc?
Answer: The good parts
You code is very readable. You stick to PEP 8 for the most part (except the annoying line length limitation) and use reasonable naming.
Managing configuration
Your first mistake, imho, is that you make the config part of the project.
Having the config in the project's repo, especially if it contains things like api_secret (or password etc.) is a common source for secret leakage via repo hosting services such as Git{Hub,Lab}.
Load config explicitly.
Currently, one of the first things your script main.py does is to read data from the file system. Though this is not immediately visible to the reader, since it is hidden in Config.__init__().
You can write a simple function like
from json import load
from pathlib import Path
from typing import Any
...
def load_config(filename: Path | str) -> dict[str, Any]:
"""Load configuration from a JSON file."""
with open(filename, 'rb') as file:
return load(file)
to load configuration from a JSON file by explicitly specifying it's path and use the returned dict.
If you have JSON, use JSON
Python's json library already does all the work to parse JSON objects into associative arrays aka. dicts. Use them directly to access the desired data:
from lib.utils import Config
def main(trading_mode, invest_amount, cumulative_position):
print(trading_mode, invest_amount, cumulative_position)
if __name__ == "__main__":
config = load_config('/path/to/my/config.json')
trading_cfg = config.get('trading')
main(
trading_mode=trading_cfg.get('mode'),
invest_amount=trading_cfg.get('invest_amount'),
cumulative_position=trading_cfg.get('cumulative_position')
) | {
"domain": "codereview.stackexchange",
"id": 44038,
"lm_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
All the introspection automagic might feel comfortable at first, but it hides away a lot of potential side-effects.
Furthermore, it won't be needed anyways if you separate your configuration from your project source code. | {
"domain": "codereview.stackexchange",
"id": 44038,
"lm_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
} |
c++, template, classes, stl, knapsack-problem
Title: A greedy approach to the Knapsack problem with C++ templates
Question: The assignment is to be implemented on the following instructions:
You are to write a Knapsack class and the main() to support and
demonstrate the functionality required here.
A function generate(int) is prototyped in collect.h and defined in the
library libGenerate.a. It returns a letter (char) that identifies
which object you need to try and fit into your knapsack. You need to
pass an object of that type to the knapsack using a function
template/template function defined inside Knapsack. That function
template should take an object of arbitrary type and attempt to ”add
it” to the knapsack. If the object fits, based on the size using
sizeof, you record that object as being included, using the name
attribute of the classes. The object itself should not be stored in
the knapsack. Once the next object to be passed cannot be added to the
knapsack, you should stop generating objects.
More details:
Private members in the Knapsack class are:
size : A positive integer. The size of the knapsack.
seed : A positive integer. Random seed to be passed to the generate
function.
the generate function is prototyped and a c++ library .a file is
included as well. (This works)
Header file required for assignment:
#ifndef COLLECT_H
#define COLLECT_H
char generate(int seed);
class A // size --> 1 {
private:
char name;
public:
A(){name='A';}
char getName(){return name;}
};
class B // size --> 2 {
private:
char name;
char B1;
public:
B(){name='B';}
char getName(){return name;}
};
class C // size --> 4 {
private:
char name;
char C1,C2,C3;
public:
C(){name='C';}
char getName(){return name;}
};
class D // size --> 8 {
private:
char name;
char D1,D2,D3;
int D4;
public:
D(){name='D';}
char getName(){return name;}
};
class E // size --> 16 {
private:
char name;
char E1,E2,E3;
int E4, E5, E6; | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
class E // size --> 16 {
private:
char name;
char E1,E2,E3;
int E4, E5, E6;
public:
E(){name='E';}
char getName(){return name;}
};
class F // size --> 32 {
private:
char name;
char F1,F2,F3;
int F4, F5, F6;
double F7, F8;
public:
F(){name='F';}
char getName(){return name;}
};
class G // size --> 64 {
private:
char name;
char G1,G2,G3;
int G4,G5,G6;
double G7,G8;
long double G9,G10;
public:
G(){name='G';}
char getName(){return name;}
};
#endif
Full code:
#include <iostream>
#include <string>
#include <vector>
#include "collect.h" // no need to submit this
template <class T>
class Knapsack
{
private:
int size;
int seed;
T obj;
public:
Knapsack(int, int);
int getsize();
int addtoknapsack(T obj);
};
template <class T>
Knapsack<T>::Knapsack(int _size, int _seed): size(_size), seed(_seed) {}
template <class T>
int Knapsack<T>::getsize()
{
return size;
}
template <class T>
int Knapsack<T>::addtoknapsack(T obj)
{
int objsize = sizeof(obj);
if(size > objsize)
{
size -= sizeof(obj);
// std::cout << size << std::endl;
return size;
}
else
{
return size;
}
}
int main(int argc, char *argv[])
{
int knapsacksize = strtol(argv[1], nullptr, 0);
int seed = strtol(argv[2], nullptr, 0);
int objsize = 0;
// set capacity, will not be changed
int capacity = knapsacksize;
std::vector<char> objlist;
std::cout << "===========================" << std::endl;
std::cout << "== C++ Knapsack problem ===" << std::endl;
std::cout << "============== ~Gh0u1Ss ===" << std::endl;
std::cout << "Knapsack Size: " << knapsacksize << std::endl;
Knapsack<int> thisknapsack(knapsacksize,seed);
// knapsacksize with decrease as objects are being added
while(knapsacksize > objsize)
{
char cresult = generate(seed); | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
//std::cout << knapsacksize << std::endl; | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
if (cresult == 'A')
{
A a;
// compare objsize with knapsacksize decreasing every interation to break the loops
// knapsacksize decreases and stops adding objects when objsize is greater than knapsacksize
objsize = sizeof(a);
if (objsize > knapsacksize)
{
break;
}
else
{
Knapsack<A> thisknapsack(knapsacksize,seed);
knapsacksize = thisknapsack.addtoknapsack(a); // knapsacksize decreases here
objlist.push_back(a.getName()); // using getname: is this acceptable?
}
}
else if(cresult == 'B')
{
B b;
objsize = sizeof(b);
if (objsize > knapsacksize)
{
break;
}
else
{
Knapsack<B> thisknapsack(knapsacksize,seed);
knapsacksize = thisknapsack.addtoknapsack(b);
objlist.push_back(b.getName());
}
}
else if(cresult == 'C')
{
C c;
objsize = sizeof(c);
if (objsize > knapsacksize)
{
break;
}
else
{
Knapsack<C> thisknapsack(knapsacksize,seed);
knapsacksize = thisknapsack.addtoknapsack(c);
objlist.push_back(c.getName());
}
}
else if(cresult == 'D')
{
D d;
objsize = sizeof(d);
if (objsize > knapsacksize)
{
break;
}
else
{
Knapsack<D> thisknapsack(knapsacksize,seed);
knapsacksize = thisknapsack.addtoknapsack(d);
objlist.push_back(d.getName());
}
}
else if(cresult == 'E')
{
E e;
objsize = sizeof(e); | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
else if(cresult == 'E')
{
E e;
objsize = sizeof(e);
if (objsize > knapsacksize)
{
break;
}
else
{
Knapsack<E> thisknapsack(knapsacksize,seed);
knapsacksize = thisknapsack.addtoknapsack(e);
objlist.push_back(e.getName());
}
}
else if(cresult == 'F')
{
F f;
objsize = sizeof(f);
if (objsize > knapsacksize)
{
break;
}
else
{
Knapsack<F> thisknapsack(knapsacksize,seed);
knapsacksize = thisknapsack.addtoknapsack(f);
objlist.push_back(f.getName());
}
}
else if(cresult == 'G')
{
G g;
objsize = sizeof(g);
if (objsize > knapsacksize)
{
break;
}
else
{
Knapsack<G> thisknapsack(knapsacksize,seed);
knapsacksize = thisknapsack.addtoknapsack(g);
objlist.push_back(g.getName());
}
}
objsize = 0; // Bug log: refresh objsize to compare with next object size on next iteration
//objlist.push_back(cresult);
} | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
int addedobjsize = capacity - knapsacksize;
std::cout << "Knapsack Size: " << addedobjsize << std::endl;
for (char character : objlist)
{
std::cout << character;
}
int countA = 0;
int countB = 0;
int countC = 0;
int countD = 0;
int countE = 0;
int countF = 0;
int countG = 0;
std::cout << std::endl;
for (char character : objlist)
{
if(character == 'A')
{
countA++;
}
else if(character == 'B')
{
countB++;
}
else if(character == 'C')
{
countC++;
}
else if(character == 'D')
{
countD++;
}
else if(character == 'E')
{
countE++;
}
else if(character == 'F')
{
countF++;
}
else if(character == 'G')
{
countG++;
}
}
if(countA > 0)
{
std::cout << "A : 1, " << countA << std::endl;
}
if(countB > 0)
{
std::cout << "B : 2, " << countB << std::endl;
}
if(countC > 0)
{
std::cout << "C : 4, " << countC << std::endl;
}
if(countD > 0)
{
std::cout << "D : 8, " << countD << std::endl;
}
if(countE > 0)
{
std::cout << "E : 16, " << countE << std::endl;
}
if(countF > 0)
{
std::cout << "F : 32, " << countF << std::endl;
}
if(countG > 0)
{
std::cout << "G : 64, " << countG << std::endl;
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
Refer to the template function and while loop in main() method:
Even though my program complies and runs successfully, I feel that my program logic design is bad (when working in industry) because the condition to check if the knapsack can fit more items is being checked two times:
Note: items have different sizes (classes in c++, see the header file)
In the addtoknapsack() function --> if(size > objsize)
In the main() function --> while(knapsacksize > objsize)
How can I improve on it such that the condition is only checked once? (Preferably in addtoknapsack() function)
Output:
Knapsack Size: 180
Knapsack Size: 177
CBDFBGAFF
A : 1, 1
B : 2, 2
C : 4, 1
D : 8, 1
F : 32, 3
G : 64, 1
Answer: There are a lot of problems with the code, but before I even start with that, I have to point out that I think you failed to understand the problem given.
This is what the problem description says:
You are to write a Knapsack class ...
... You need to pass an object of that type to the knapsack using a function template/template function defined inside Knapsack. That function template should take an object of arbitrary type and attempt to ”add it” to the knapsack. ...
What you were asked to do is create a class with a function template. What you did was create a class template with a function (that is not a template). In other words:
// This is a class template...
template <typename T>
class knapsack
{
// ... with a non-template function.
auto add(T);
};
// This is a (non-template) class...
class knapsack
{
// ... with a function template.
template <typename T>
auto add(T);
}; | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
It’s partly because you got that wrong that you have ended up with code that is mostly absurd, with insane amounts of duplication and lots of dead-ends and pointless complexity.
You see, because you have templated the knapsack (and not the add function), you have been forced to create dozens and dozens of knapsacks in your code. You just keep creating them, and then throwing them away:
std::cout << "===========================" << std::endl;
std::cout << "== C++ Knapsack problem ===" << std::endl;
std::cout << "============== ~Gh0u1Ss ===" << std::endl;
std::cout << "Knapsack Size: " << knapsacksize << std::endl;
/*******************************************************************
* This knapsack is created, and then just... thrown away.
* It's never used again.
* And, bizarrely, it's created with a template parameter of int.
* That just makes no sense at all. What does int have to do with
* anything? I know you just needed something to make it work...
* but "slap anything in there to make it work" is literally the
* opposite of good programming.
******************************************************************/
Knapsack<int> thisknapsack(knapsacksize,seed);
// knapsacksize with decrease as objects are being added
while(knapsacksize > objsize)
{
char cresult = generate(seed);
//std::cout << knapsacksize << std::endl; | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
if (cresult == 'A')
{
A a;
// compare objsize with knapsacksize decreasing every interation to break the loops
// knapsacksize decreases and stops adding objects when objsize is greater than knapsacksize
objsize = sizeof(a);
if (objsize > knapsacksize)
{
break;
}
else
{
/*******************************************************
* This knapsack is created for no other reason than to
* do `knapsacksize += sizeof(A);`...
******************************************************/
Knapsack<A> thisknapsack(knapsacksize,seed);
knapsacksize = thisknapsack.addtoknapsack(a); // knapsacksize decreases here
objlist.push_back(a.getName()); // using getname: is this acceptable?
/*******************************************************
* ... and it's immediately destroyed here.
******************************************************/
}
}
else if(cresult == 'B')
{
B b;
objsize = sizeof(b);
if (objsize > knapsacksize)
{
break;
}
else
{
/********************************************************
* AGAIN, a knapsack is created for no other reason than
* to do `knapsacksize += sizeof(B);`...
*******************************************************/
Knapsack<B> thisknapsack(knapsacksize,seed);
knapsacksize = thisknapsack.addtoknapsack(b);
objlist.push_back(b.getName());
/********************************************************
* ... and AGAIN it's immediately destroyed here. | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
* ... and AGAIN it's immediately destroyed here.
*******************************************************/
}
}
/***************************************************************
* And the same thing happens again and again, for every type:
* pointless knapsacks are created, then discarded.
**************************************************************/ | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
If you think about it for a second, that just makes no sense. You’re supposed to have ONE knapsack… not dozens of them. And if you’re putting things in and expecting to query the contents later, it makes no sense to be throwing the knapsack(s) away over and over.
And this is really the problem throughout the code. Rather than taking the time to THINK about what you need and what should be happening, you’re just blindly throwing everything at the wall to see what sticks. This is not programming, this is just hacking.
I would advise throwing the whole thing out and starting from scratch. First, make a proper knapsack class. THINK it through: what does the knapsack class need? It needs to know its total size, and it needs to keep track of its contents and their size. Your current knapsack class knows its total size—that’s good—but then it knows a random seed it never uses—why?—and it only holds a single object.
Once you get the knapsack class right, you will avoid any need for the rest of the absurdity in your code, like the fact that you have a knapsack class, yet you’re keeping track of the objects in the knapsack using a separate vector (objlist). Isn’t that weird? When you put things in a bag, do you actually put nothing in that bag, but rather have a separate thing keeping track of what’s supposed to be in that bag? That’s not how bags work.
The bottom line is that you need to completely rethink what your code is doing, or rather, perhaps, think it through for the first time. C++ is a modelling language, so THINK about what you are modelling: what are the “objects”, what are their properties, how do they interact, and so on. Once you do that, everything will just fall together, and silliness like double-checking the fit condition won’t be a problem anymore.
Code review
I’m not sure whether the header is supposed to be part of the review, but, meh, it’s terrible anyway, so maybe at least someone can learn from having it reviewed.
char generate(int seed); | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
Without seeing the body of the function, there’s no way to know how it actually works, but repeatedly reseeding a pseudo-random generator is generally a bad idea. A proper interface would have a separate seed function and generate function. (As with std::srand() and std::rand(), but don’t use those, they are garbage.)
class A // size --> 1 {
private:
char name;
public:
A(){name='A';}
char getName(){return name;}
};
class B // size --> 2 {
// ... [snip] ...
class C // size --> 4 {
// ... [snip] ...
// ... [etc.] ...
Hoo boy.
Okay, first of all, this code assumes that sizeof(int) is 4, not to mention assumptions about the size of double and long double. Maybe, maybe not. Even if it “works” on your platform, it makes no sense when there are easier and better ways to guarantee a size of 4, portably. More or less.
You see, there is technically no way to guarantee a size of anything. The C++ compiler is free to add padding as it pleases. But let’s ignore that complication for now. (For the record, you can fix that with compiler switches and pragmas. But that’s compiler-specific stuff.)
So all you want is a set of types of a fixed size. No problem:
template <char Name, int Size>
requires (Size >= 1)
class fixed_size_type
{
char _data[Size];
public:
// Could also make this constexpr and noexcept:
auto getName() const { return Name; }
};
using A = fixed_size_type<'A', 1>;
using B = fixed_size_type<'B', 2>;
using C = fixed_size_type<'C', 4>;
// ... and so on ... | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
“Don’t Repeat Yourself (DRY)” is a core rule of good programming.
I would also recommend against using .h as the extension for C++ header files. That is the C header file extension. Unless your header is intended to be compatible with C, you should use .hpp or .hxx or something else to clearly mark it as a C++ header file.
Okay, onto the main source file.
template <class T>
class Knapsack
{
private:
int size;
int seed;
T obj;
public:
Knapsack(int, int);
int getsize();
int addtoknapsack(T obj);
};
So I’ve already explained why this class is all wrong, and needs to be rewritten. I’m not going to spell out exactly how to rewrite it, because I suspect that’s the point of the lesson. I will, however, give some tips.
All your knapsack class needs to know is its total size, the list of objects it contains, and their total size. For the list of objects, you could just use that objlist vector<char> that is currently external to the knapsack as a data member. All the class needs to do is report its total size, its current size and the list of objects it contains, and have a function to add new objects. The add function should check that the new object will fit, and return an error (or throw an exception) if not. All you need to do in main() is keep adding objects until you get that error. Simple.
int knapsacksize = strtol(argv[1], nullptr, 0);
int seed = strtol(argv[2], nullptr, 0);
There is no error-checking done here. Since this is just a toy program, that’s probably fine, but obviously you shouldn’t do this in a real program.
int objsize = 0;
There is no point creating this variable here. It’s not used until a couple dozen or so lines later.
// set capacity, will not be changed
int capacity = knapsacksize;
The word for “will not be changed” in C++ is const.
std::vector<char> objlist; | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
The word for “will not be changed” in C++ is const.
std::vector<char> objlist;
As already mentioned, the knapsack should be keeping track of the objects it contains. There should be no need for an external variable.
std::cout << "===========================" << std::endl;
std::cout << "== C++ Knapsack problem ===" << std::endl;
std::cout << "============== ~Gh0u1Ss ===" << std::endl;
Don’t use std::endl. It’s (almost) always wrong. If you want a new line, just write a new line: "\n" or '\n'. It’s not only going to be significantly faster, it’s also shorter to write.
By the by, there is no need to split this message over 6 different output operations. You could just do:
std::cout << "===========================\n"
"== C++ Knapsack problem ===\n"
"============== ~Gh0u1Ss ===\n";
The strings will be automatically merged.
std::cout << "Knapsack Size: " << knapsacksize << std::endl;
Given how many variables you have floating around keeping track of one size or another, you should be more careful with terminology. I believe what you mean to specify here is the knapsack capacity.
And knapsacksize probably means remaining capacity, but your logic is so confused it’s hard to tell.
Knapsack<int> thisknapsack(knapsacksize,seed);
This knapsack object is created and… just never used. It’s also instantiated with an int template parameter, which means… nothing. It’s just gibberish.
// knapsacksize with decrease as objects are being added
while(knapsacksize > objsize)
Why are you testing this here? There are no objects yet (on the first run through), so this test is nonsense. objsize shouldn’t even exist yet, because you don’t have any objects to have a size of.
// knapsacksize with decrease as objects are being added
while(knapsacksize > objsize)
{
char cresult = generate(seed);
//std::cout << knapsacksize << std::endl; | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
//std::cout << knapsacksize << std::endl;
if (cresult == 'A')
{
A a;
// compare objsize with knapsacksize decreasing every interation to break the loops
// knapsacksize decreases and stops adding objects when objsize is greater than knapsacksize
objsize = sizeof(a);
if (objsize > knapsacksize)
{
break;
}
else
{
Knapsack<A> thisknapsack(knapsacksize,seed);
knapsacksize = thisknapsack.addtoknapsack(a); // knapsacksize decreases here
objlist.push_back(a.getName()); // using getname: is this acceptable?
}
}
else if(cresult == 'B')
{
// ... [snip repeated blocks] ...
Okay, this is the meat of the main() function, and it’s basically just the same if block repeated over and over. Whenever you see repetition like this, it’s a signal that you need to create a function.
Every if block looks like this:
if (cresult == 'T')
{
T t;
objsize = sizeof(t);
if (objsize > knapsacksize)
{
break;
}
else
{
Knapsack<T> thisknapsack(knapsacksize,seed);
knapsacksize = thisknapsack.addtoknapsack(t);
objlist.push_back(t.getName());
}
}
… where T/t gets replaced with “A” through “G”.
First, let’s simplify by removing some of the unnecessary garbage. If you had a proper knapsack class with a proper add function—one that returns false if the new object won’t fit—then this block becomes this:
if (cresult == 'T')
{
if (not knapsack.add(T{}))
break;
} | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
c++, template, classes, stl, knapsack-problem
Amazing, right? That’s what it looks like when you get the types right.
So let’s pull all those if blocks out and put them in a function:
auto add_to_knapsack(knapsack& knap, char item)
{
switch (item)
{
case 'A':
if (not knapsack.add(A{}))
return false;
break;
case 'B':
if (not knapsack.add(B{}))
return false;
break;
// ... [and so on] ...
}
return true;
}
Now the loop in main() is just:
while (add_to_knapsack(knap, generate(seed)))
{
// This block is empty.
}
That’s literally it. That’s pretty much the whole program. That’s over a hundred lines of code gone. and it’s maximally efficient: no repeated tests or any other nonsense.
Finally, there’s the histogram calculation at the end. Once again, there’s a crap ton of duplicated code. But all you need is a single map:
auto counts = std::map<char, int>{};
// This does all the counting.
for (auto character : objlist)
++counts[character];
// This does all the printing.
for (auto [character, count] : counts)
std::cout << character << " : " << get_object_size_by_name(character) << ", " << count << "\n";
// Notice the get_object_size_by_name() function in there. All that does
// is take the character, figure out which type it represents, and then
// return the size, like so:
auto get_object_size_by_name(char name)
{
switch (name)
{
case 'A': return sizeof(A);
case 'B': return sizeof(B);
// ... [ and so on ] ...
}
// Handle errors here.
}
Everything starts with getting the types right, though. Because you got the knapsack class wrong, everything turned into a disaster. If you got the knapsack type right, everything would flow smoothly, you would get simpler and clearer code, and there would be no inefficiencies or duplication. | {
"domain": "codereview.stackexchange",
"id": 44039,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, template, classes, stl, knapsack-problem",
"url": null
} |
python, datetime
Title: Generates list of intervals using the biggest different time unit within period
Question: I've created a function to split a period into the biggest different time unit possible. It can be years, months, weeks or days.
However, it ended up being quite big and I feel it can be greatly improved, but I'm having difficulties finding ways to do it.
import calendar
from datetime import datetime, timedelta | {
"domain": "codereview.stackexchange",
"id": 44040,
"lm_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, datetime",
"url": null
} |
python, datetime
def create_intervals(start_date, end_date):
start = datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.strptime(end_date, "%Y-%m-%d")
di = []
# Year
if (sy := start.year) < (ey := end.year):
for y in range(sy, ey + 1):
if sy == y:
di.append((start_date, f"{y}-12-31"))
elif sy < y < ey:
di.append((f"{y}-01-01", f"{y}-12-31"))
else:
di.append((f"{y}-01-01", end_date))
# Month
elif (sm := start.month) < (em := end.month):
for m in range(sm, em + 1):
last_day = calendar.monthrange(sy, m)[1]
if sm == m:
di.append((start_date, f"{sy}-{m:02d}-{last_day}"))
elif sm < m < em:
di.append((f"{sy}-{m:02d}-01", f"{sy}-{m:02d}-{last_day}"))
else:
di.append((f"{sy}-{m:02d}-01", end_date))
# Week
elif (sw := start.isocalendar().week) < (ew := end.isocalendar().week):
for w in range(sw, ew + 1):
if sw == w:
last = start - timedelta(days=start.weekday()) + timedelta(days=6)
di.append((start_date, f"{sy}-{sm:02d}-{last.day:02d}"))
elif sw < w < ew:
wd = datetime.strptime(f"{sy}-W{w}-1", "%Y-W%W-%w")
first = wd - timedelta(days=wd.weekday())
last = wd - timedelta(days=wd.weekday()) + timedelta(days=6)
di.append((f"{sy}-{sm:02d}-{first.day:02d}", f"{sy}-{sm:02d}-{last.day:02d}"))
else:
first = end - timedelta(days=end.weekday())
di.append((f"{sy}-{sm:02d}-{first.day:02d}", end_date))
# Day
elif start.day < end.day:
for d in range(start.day, end.day + 1):
di.append((f"{sy}-{sm:02d}-{d:02d}", f"{sy}-{sm:02d}-{d:02d}"))
# None
else:
di.append((start_date, end_date))
return di | {
"domain": "codereview.stackexchange",
"id": 44040,
"lm_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, datetime",
"url": null
} |
python, datetime
Example for years as biggest different time unit:
create_intervals("2021-10-22", "2023-03-02")
# Outputs intervals for each year:
# [("2021-10-22", "2021-12-31"),
# ("2022-01-01", "2022-12-31"),
# ("2023-01-01", "2023-03-02")]
Example for days as biggest different time unit:
create_intervals("2021-10-22", "2021-10-24")
# Outputs:
# [("2021-10-22", "2021-10-22"),
# ("2021-10-23", "2021-10-23"),
# ("2021-10-24", "2021-10-24")]
Answer: There is never a case where you should use string datetime representation in this code, and there is never a case where you should use datetime; use date instead.
Consider converting to a generator function to simplify your code.
Your one- and two-letter variable names need to go away.
Almost all of your walrus assignments need to go away except that of the week comparison.
first = wd - timedelta(days=wd.weekday()) should not do any subtraction because the right-hand term will always be 0.
Write unit tests based on the cases you already have, and expand for cases that you don't already have.
Writing conditions for the beginning and end of a sequence within a loop is an antipattern - instead, cut those out to statements before and after the loop, and make the loop unconditional.
Add PEP484 typehints.
Suggested
import calendar
from datetime import date, timedelta
from typing import Iterator
def create_intervals(start: date, end: date) -> Iterator[tuple[date, date]]:
# Year
if start.year < end.year:
yield start, date(start.year, 12, 31)
for year in range(start.year + 1, end.year):
yield date(year, 1, 1), date(year, 12, 31)
yield date(end.year, 1, 1), end
# Month
elif start.month < end.month:
last_days = (
calendar.monthrange(start.year, month)[1]
for month in range(start.month, end.month + 1)
)
yield start, date(start.year, start.month, next(last_days)) | {
"domain": "codereview.stackexchange",
"id": 44040,
"lm_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, datetime",
"url": null
} |
python, datetime
yield start, date(start.year, start.month, next(last_days))
for month, last_day in zip(range(start.month + 1, end.month), last_days):
yield date(start.year, month, 1), date(start.year, month, last_day)
yield date(start.year, end.month, 1), end
# Week
elif (start_week := start.isocalendar().week) < (end_week := end.isocalendar().week):
last = start + timedelta(days=6 - start.weekday())
yield start, date(start.year, start.month, last.day)
for week in range(start_week + 1, end_week):
first = date.fromisocalendar(start.year, week, 1)
last = first + timedelta(days=6)
yield date(start.year, start.month, first.day), date(start.year, start.month, last.day)
first = end - timedelta(days=end.weekday())
yield date(start.year, start.month, first.day), end
# Day
elif start.day < end.day:
for day in range(start.day, end.day + 1):
yield date(start.year, start.month, day), date(start.year, start.month, day)
# None
else:
yield start, end
def test() -> None:
# Years
result = tuple(create_intervals(date(2021, 10, 22), date(2023, 3, 2)))
assert result == (
(date(2021, 10, 22), date(2021, 12, 31)),
(date(2022, 1, 1), date(2022, 12, 31)),
(date(2023, 1, 1), date(2023, 3, 2)),
)
# Months
result = tuple(create_intervals(date(2021, 3, 7), date(2021, 10, 26)))
assert result == (
(date(2021, 3, 7), date(2021, 3, 31)),
(date(2021, 4, 1), date(2021, 4, 30)),
(date(2021, 5, 1), date(2021, 5, 31)),
(date(2021, 6, 1), date(2021, 6, 30)),
(date(2021, 7, 1), date(2021, 7, 31)),
(date(2021, 8, 1), date(2021, 8, 31)),
(date(2021, 9, 1), date(2021, 9, 30)),
(date(2021, 10, 1), date(2021, 10, 26)),
) | {
"domain": "codereview.stackexchange",
"id": 44040,
"lm_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, datetime",
"url": null
} |
python, datetime
# Weeks
result = tuple(create_intervals(date(2021, 10, 2), date(2021, 10, 26)))
assert result == (
(date(2021, 10, 2), date(2021, 10, 3)),
(date(2021, 10, 4), date(2021, 10, 10)),
(date(2021, 10, 11), date(2021, 10, 17)),
(date(2021, 10, 18), date(2021, 10, 24)),
(date(2021, 10, 25), date(2021, 10, 26))
)
# Days
result = tuple(create_intervals(date(2021, 10, 22), date(2021, 10, 24)))
assert result == (
(date(2021, 10, 22), date(2021, 10, 22)),
(date(2021, 10, 23), date(2021, 10, 23)),
(date(2021, 10, 24), date(2021, 10, 24)),
)
if __name__ == '__main__':
test() | {
"domain": "codereview.stackexchange",
"id": 44040,
"lm_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, datetime",
"url": null
} |
c++, asynchronous, boost, ipc
Title: Tool for asynchronous IPC using pipes
Question: Description of the code:
The code provides asynchronous IPC functionality in C++ using the Boost libraries and pipes.
Each process asynchronously "listens" on the read end of the pipe and the messages are added to a queue, which means you won't have to call read() manually: you just have to send messages and they're automatically received on the other end.
I also plan to add a feature which enables you to send the name of a function and its arguments to the other process to call it remotely.
My question:
This is pretty much the first non Tic-tac-toe project I've done, and I've never really written production code for a big project, so I always have doubt about whether I'm doing things the proper way or I'm just making stuff up.
I'd really appreciate it if you could look at the code and point out what you would've done differently if you were to create this project yourself.
Any bugs or ways to make the code faster are also very welcome.
Unrelated question, could this be of use to anyone? Should I put it up on GitHub?
The code:
example_server.cpp
// Code for "Connector" is provided below, I thought it would be better
// to show how it's used first.
#include "Connector.hpp"
#include <iostream>
#include <string>
#include <memory>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
int main()
{
// Create two pipes and convert the file descriptors to char.
int pipe_fd1[2];
int pipe_fd2[2];
pipe(pipe_fd1);
pipe(pipe_fd2);
char reader_for_client[4];
char writer_for_client[4];
sprintf(&reader_for_client[0], "%d", pipe_fd1[0]);
sprintf(&writer_for_client[0], "%d", pipe_fd2[1]);
// Create the child process or "Client" and pass
// one read handle and one write handle to it.
pid_t cpid = fork();
if(cpid == 0)
{
execl("./example_client", &reader_for_client[0], &writer_for_client[0], (char*) NULL);
} | {
"domain": "codereview.stackexchange",
"id": 44041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, asynchronous, boost, ipc",
"url": null
} |
c++, asynchronous, boost, ipc
// Create a "Connector" object and pass the file descriptors to it.
// Also specify the number of threads it should use.
auto node = make_unique<Connector>(pipe_fd2[0], pipe_fd1[1], 1);
// Provide a callback function that gets called
// whenever a new message is received.
node->AssignHandler([](const string& data)
{
cout << "[Server] " << data << endl;
});
// Read messages from the terminal and send them to the "Client".
string message;
do
{
cin >> message;
node->SendData(message);
}
// Send the message "die" to make both processes exit.
// The child process ("Client") sends back "die" to the
// parent process ("Server") to tell it to exit as well.
while(message != "die");
// Wait for the child process to exit. This is probably
// not necessary since the parent process won't exit
// until it receives "die" from the child process.
waitpid(cpid, NULL, 0);
}
example_client.cpp
#include "Connector.hpp"
#include <memory>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
// Receive the pipe file descriptors from the "server".
int reader_fd = atoi(argv[0]);
int writer_fd = atoi(argv[1]);
// Create a "Connector" object and pass the file descriptors to it.
// Also specify the number of threads it should use.
auto node = make_unique<Connector>(reader_fd, writer_fd, 1);
// Provide a callback function that gets called
// whenever a new message is received.
node->AssignHandler([](const string& data)
{
cout << "[Client] " << data << endl;
});
// Send a messsage to the "Server".
node->SendData("hello, this is the client.");
} | {
"domain": "codereview.stackexchange",
"id": 44041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, asynchronous, boost, ipc",
"url": null
} |
c++, asynchronous, boost, ipc
// Send a messsage to the "Server".
node->SendData("hello, this is the client.");
}
Connector.hpp
#pragma once
#include <queue>
#include <memory>
#include <string>
#include <functional>
#include <boost/asio/readable_pipe.hpp>
#include <boost/asio/writable_pipe.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/system/error_code.hpp>
#include <boost/asio/thread_pool.hpp>
typedef std::shared_ptr<boost::asio::io_service> io_ptr;
class Connector
{
public:
Connector(int reader_fd, int writer_fd, int numThreads);
~Connector();
void CleanUp();
// Used to send simple string.
void SendData(const std::string& data);
// NOT IMPLEMENTED YET.
// Used in order to send the name of a function that exists
// in the other process to run it remotely.
// Planning to implement it using a map since reflection
// doesn't exist in c++.
void SendCommand(const std::string& command);
// "AssignHandler" takes in a function which is called
// everytime a message is received.
void AssignHandler(const std::function<void(const std::string&)>& func);
// This queue stores incoming messages. Messages are
// "pop"ed after they are passed to the user provided handler.
std::queue<std::string> data_queue;
private:
// Stores the messages and commands that have been
// received before the user provided a callback function.
std::queue<std::string> pending;
// handler function provided by the user.
std::function<void(const std::string&)> handler;
// The class receives an integer with the size
// of the message or command that is about to be received,
// and allocates an appropriately sized string.
int32_t size_of_incoming_buffer;
// Shows whether we're waiting for the size of the message,
// or for the message itself.
bool getting_size = true; | {
"domain": "codereview.stackexchange",
"id": 44041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, asynchronous, boost, ipc",
"url": null
} |
c++, asynchronous, boost, ipc
// The incoming message or command is stored in this string.
std::string buffer;
// Create boost objects that provide async functionality.
std::shared_ptr<boost::asio::io_service> io_service;
std::shared_ptr<boost::asio::readable_pipe> reader;
std::shared_ptr<boost::asio::writable_pipe> writer;
std::shared_ptr<boost::asio::thread_pool> threads;
std::shared_ptr<boost::asio::io_service::work> work;
// Reads a certain amout of bytes from the read-end of the pipe.
void Receive(int32_t bytes = 4);
// Gets called when "Receive" succussfully reads the specified
// number of bytes from the pipe.
void ReceiveHandler(const boost::system::error_code& ec, size_t bytes);
// Gets called when we succussfully write to the pipe.
// Currently doesn't actually do anything.
void SendHandler(const boost::system::error_code& ec, size_t bytes);
// Create the pipe objects used for communication.
// Could be overloaded to work with sockets and stuff too.
void InitializeCommMethod(int reader_fd, int writer_fd);
// Posts the specified tasks to the io_service object for execution.
// Currently only performs "Receive".
void PerformTasks();
// Calls the user provided handler function with the appropriate arguments.
void CallHandler();
// Gets called when the user provides the handler function.
// Runs the handler on all the pending messages.
void PerformPending();
};
Connector.cpp
#include "Connector.hpp"
#include <boost/asio/post.hpp>
#include <boost/bind/bind.hpp>
#include <boost/bind/placeholders.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/read.hpp>
#include <iostream>
using namespace std;
using namespace boost::placeholders; | {
"domain": "codereview.stackexchange",
"id": 44041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, asynchronous, boost, ipc",
"url": null
} |
c++, asynchronous, boost, ipc
#include <iostream>
using namespace std;
using namespace boost::placeholders;
Connector::Connector(int reader_fd, int writer_fd, int numThreads)
{
// Initialize boost related objects that will help us
// perform asynchronous io operations.
// The io_service objects provides async_io functionality.
io_service = make_shared<boost::asio::io_service>();
// The "work" object doesn't allow io_service to
// exit when it runs out of tasks.
work = make_shared<boost::asio::io_service::work>(*io_service);
// Create pipe objects used for communication, from native pipe
// handles.
InitializeCommMethod(reader_fd, writer_fd);
threads = make_shared<boost::asio::thread_pool>(numThreads);
// Post io_service->run to the thread pool.
boost::asio::post(*threads, [this]()
{
this->io_service->run();
});
// Perform a number of predefined tasks.
PerformTasks();
}
Connector::~Connector()
{
// When the destructor is called, it doesn't allow the main thread
// to exit until all the worker threads have finished.
threads->join();
}
void Connector::CleanUp()
{
// Allow the worker threads to exit by
// removing the work object.
work.reset();
threads->join();
}
void Connector::SendData(const string& data)
{
// First sends the size of the message, then sends
// the message itself.
int32_t size = data.length();
boost::asio::async_write(*writer, boost::asio::buffer((void*)&size, 4), boost::bind(&Connector::SendHandler, this, _1, _2));
boost::asio::async_write(*writer, boost::asio::buffer(data), boost::bind(&Connector::SendHandler, this, _1, _2));
}
void Connector::SendHandler(const boost::system::error_code& ec, size_t bytes)
{
// Gets called whenever we write to the pipe.
return;
}
void Connector::Receive(int32_t bytes)
{
// Allocate an appropriately sized string ("buffer"),
// read "bytes" bytes from the pipe and put it in
// said string. | {
"domain": "codereview.stackexchange",
"id": 44041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, asynchronous, boost, ipc",
"url": null
} |
c++, asynchronous, boost, ipc
// OR, read the size of the incoming message and put it
// in "size_of_incoming_buffer".
buffer = string(bytes, '\0');
if(getting_size)
{
boost::asio::async_read(*reader, boost::asio::buffer((void*)&size_of_incoming_buffer, 4), boost::bind(&Connector::ReceiveHandler, this, _1, _2));
return;
}
boost::asio::async_read(*reader, boost::asio::buffer(buffer), boost::bind(&Connector::ReceiveHandler, this, _1, _2));
}
void Connector::ReceiveHandler(const boost::system::error_code& ec, size_t bytes)
{
// If we've already received the size of the incoming message,
// read "size_of_incoming_buffer" bytes from the pipe, which is the
// size of the message.
if(getting_size)
{
getting_size = false;
Receive(size_of_incoming_buffer);
return;
}
// If getting_size is false, then the last thing we received
// was the message, which is currently in "buffer".
// We push the message to "data_queue", and wait for the size
// of the next message.
getting_size = true;
data_queue.push(buffer);
// If the message is "die", exit.
if(buffer == "die")
{
// Tell the other process to exit as well.
SendData("die");
CleanUp();
return;
}
// Call the user provided handler function for when we receive
// a new message.
io_service->post(boost::bind(&Connector::CallHandler, this));
// Wait for the size of the next message.
// (The default value of the "Receive" function is 4 bytes, or an int32_t).
Receive();
}
void Connector::InitializeCommMethod(int reader_fd, int writer_fd)
{
// Create boost pipe objects from native pipe handles.
reader = make_shared<boost::asio::readable_pipe>(*io_service, reader_fd);
writer = make_shared<boost::asio::writable_pipe>(*io_service, writer_fd);
}
void Connector::PerformTasks()
{
// Receive the size of the first message.
Receive();
} | {
"domain": "codereview.stackexchange",
"id": 44041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, asynchronous, boost, ipc",
"url": null
} |
c++, asynchronous, boost, ipc
void Connector::PerformTasks()
{
// Receive the size of the first message.
Receive();
}
void Connector::AssignHandler(const function<void(const string&)>& func)
{
// Assign the user provided function to "handler".
handler = func;
// Run "handler" on all pending message, received before the user
// provided a handler function.
PerformPending();
}
void Connector::CallHandler()
{
// If handler is provided, run it on the
// last message in the queue.
if(handler)
{
handler(data_queue.front());
data_queue.pop();
}
// Otherwise, add the message to the pending queue.
else
{
pending.push(data_queue.front());
data_queue.pop();
}
}
void Connector::PerformPending()
{
// Gets called when the user provides a handler.
// Runs the handler on all pending messages.
string pending_message;
for(int i = 0; i < pending.size(); i++)
{
pending_message = pending.front();
pending.pop();
io_service->post([this, pending_message]()
{
this->handler(pending_message);
});
}
}
Answer: Unnecessary use of smart pointers
You are using std::unique_ptr and std::shared_ptr in places where there is no need for them. For example, the client can just declare the Connector like so:
int main(...) {
...
Connector node(reader_fd, writer_fd, 1);
node.AssignHandler(...);
node.SendData("Hello, this is the client.");
} | {
"domain": "codereview.stackexchange",
"id": 44041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, asynchronous, boost, ipc",
"url": null
} |
c++, asynchronous, boost, ipc
But many more things in your code are using smart pointers unnecessarily.
Unnecessary use of this->
You are using this-> twice in the code, but there is no reason to use it.
Thread safety
Your code starts multiple I/O processing loops. However, nothing in class Connector is thread-safe. If you are going to use multiple threads, I would expect to see a mutex guarding the queues at the very least. However, it seems you only enqueue a single async_read() at a time, so in that sense the code is probably safe, but then what's the point of the async I/O? But still, you could receive messages faster than they can be handled, in which case there are multiple threads running CallHandler(), and those do modify data_queue and pending.
Missing error checking
Things can go wrong, but nothing in your code does error checking. What if the server or the client is killed before "die" has been sent? What if ReceiveHandler() is called when getting_size == false but bytes is not the same as size_of_incoming?
Make sure you check the return value of any system calls like fork() and execl(), and for ASIO callbacks check the boost::system::error_code parameter.
In case of an error, make sure you handle it appropriately; if you cannot recover from it at the place it occurs, throw an exception so the error can be handled at a higher level, or if it's really fatal, print an error message to std::cerr and call std::exit(EXIT_FAILURE).
Use '\n' instead of std::endl
Prefer to use '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is often unnecessary and may negatively impact performance. | {
"domain": "codereview.stackexchange",
"id": 44041,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, asynchronous, boost, ipc",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.