text stringlengths 1 2.12k | source dict |
|---|---|
c++, math-expression-eval
Rvalue Reference Overloads Would be More Efficient
Currently, all or nearly all the operators that return temporaries make a copy of the first operand and update that in place. However, if either operand is moveable (Binary_Register&& instead of const Binary_Register&), you can optimize out the copy. Since nearly all the operations are commutative, modulo an inversion here or there, you can do this if either operand is moveable.
The gain is especially noticeable in an expression such as a = w + x + y + z;. The current operation would need to make four copies, but adding an overload for && on the left operand would reduce that to one: w would need to be copied, in the first addition, but then every other sum would have an xvalue (the temporary returned by the previous addition) as its left operand, so it could keep updating that in place, then move the result to a.
Do You Really Want Two’s-Complement?
The main motivation for using it in the CPU is that, for fixed-width unsigned types, the CPU can use the same logic for signed and unsigned addition and subtraction. However, here, you don’t want to do both signed and unsigned addition and subtraction. You end up making subtraction more complex by copying and inverting the second operand, and likewise the other arithmetic.
The classic solution is therefore to use a sign-and-magnitude representation for this purpose.
Some of the Individual Functions Can be Optimized
To give just one example, &= pads the destination operand to the length of the source with a loop that calls push_back(0) on the vector of words, then does element-wise &=.
First, when you know the total size, it’s much more efficient to pad with zeroes by calling resize once than by calling push_back repeatedly.
But second, bitwise and where one of the operands is 0 will always return 0, so you could have done the &= loop only up to the lesser of the two operands’ sizes, and then either zero-extended the left operand or zeroed out its remaining words. | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
Minor Cosmetic Suggetions
Either PascalCase or snake_case is much more common for class names than Whatever_This_Is. I’d recommend you pick one of the first two.
Avoid misleading whitespace such as while (i --> 0). That one does kind of work, but --> is not an operator, and is easy to confuse for ->, which is. | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
java
Title: How do I ensure my Java method never returns null?
Question: I've been reading Uncle Bob's Clean Code and have read many articles on the use of Optionals whenever you are faced with returning a null in a Java method. I'm currently refactoring my code and I just don't know how to optimize it with Optionals. Can someone give me some pointers?
public UserLog selectById(String userid) throws DataException {
List<UserLog> logs = selectUserLogs(SQL_SELECT_BY_ID, userid);
return logs.isEmpty() ? null : logs.get(0);
}
private List<UserLog> selectUserLogs(String sql, Object... args) throws DataException {
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql, args);
return rows.stream().map(this::toUserLogs)
.collect(Collectors.toList());
}
private UserLog toUserLogs(Map<String, Object> row) {
UserLog userLog = new UserLog("Steven Wozniak", 65, "Male");
return userLog;
}
/**
* Below shows how selectById is being used in another class
*/
...
public void callingMethod() {
if(starttime != null && FIVE_HOUR <= durationSinceStartTime() &&
userLogDao.selectById(userid) != null &&
userLogDao.selectById(userid).getStartTime() != null) {
log.warn("Logs came in late");
}
}
I'm having trouble optimizing the selectById method. Since I'm doing a Collector.toList() in the selectUserLogs method, I can be sure that I will ALWAYS get a List back. It could be an empty list, but never a null.
My initial attempt was:
public Optional<UserLog> selectById(String userid) throws DataException {
List<UserLog> logs = selectUserLogs(SQL_SELECT_BY_ID, userid);
return Optional.ofNullable(logs.get(0));
}
However, I completely have no idea how I'm going to optimize the calling of this method and performing the null checks in the callingMethod(). How would I re-write that so that it looks a tad more elegant? | {
"domain": "codereview.stackexchange",
"id": 44631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
Answer: Firstly, if you make I/O call as database request, I suggest you to call selectById only one time and not 2 time in the if (and maybe a thrid time after).
Then, for the no-null content, it depend of :
If you can create default value. It doesn't seems to be your case here, but as we don't know your full project, it's possible. You can create temporary value not saved in database which said it's empty like this:
public UserLog selectById(String userid) throws DataException {
List<UserLog> logs = selectUserLogs(SQL_SELECT_BY_ID, userid);
return logs.isEmpty() ? new UserLog(null, 0, "Unknow") : logs.get(0);
}
If you want that selectUserLogs return a list, you can do like this for the selectById method:
public UserLog selectById(String userid) throws DataException {
List<UserLog> logs = selectUserLogs(SQL_SELECT_BY_ID, userid);
return logs.isEmpty() ? Optional.empty() : Optional.of(logs.get(0));
}
If the selectUserLogs is only used here, I suggest you to use the Stream#findFirst method do like this:
private Optional<UserLog> selectById(String userid) throws DataException {
List<Map<String, Object>> rows = jdbcTemplate.queryForList(SQL_SELECT_BY_ID, userid);
return rows.stream().map(this::toUserLogs).findFirst();
}
A combination of the 2 and 3: 2 methods but using findFirst method:
public UserLog selectById(String userid) throws DataException {
List<UserLog> logs = selectUserLogs(SQL_SELECT_BY_ID, userid);
return logs.stream().findFirst();
} | {
"domain": "codereview.stackexchange",
"id": 44631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
Here you create a useless stream (which were created before...) but you keep both method. It's fine if the selectUserLogs is used somewhere else, and the actual result is what other method are looking for.
Finally, with optional you can do like this in your callingMethod() method:
public void callingMethod() {
if(starttime != null && FIVE_HOUR <= durationSinceStartTime()) {
userLogDao.selectById(userid).ifPresent(userLog -> {
if(userLog.getStartTime() != null) {
log.warn("Logs came in late");
}
})
}
} | {
"domain": "codereview.stackexchange",
"id": 44631,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java, parsing, xml
Title: Retrieve data from an XML file in Java
Question: few months back I did a code test for a company and I quickly managed to solve it within 5-10 minutes. But, I got rejected because it wasnt "good enough".
What is good enough? they said its mainly how I wrote the code and that I was missing exception handling..
Anyways I was supposed to retrieve data from an XML file and store it into a file. Here is my code:
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
xmlDataToFile("src/resources/xml-File.xml", "41");
}
static void xmlDataToFile(String url, String value) throws ParserConfigurationException, IOException, SAXException {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = documentBuilder.parse(url);
NodeList nodeList = document.getElementsByTagName("target");
for (int i = 0; i < nodeList.getLength(); i++){
Node node = nodeList.item(i);
if (node.getParentNode().getAttributes().item(0).getTextContent().equals(value)){
Files.write(Paths.get("textFile.txt"), Collections.singleton(nodeList.item(i).getTextContent()));
}
}
How can I improve this ? | {
"domain": "codereview.stackexchange",
"id": 44632,
"lm_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, parsing, xml",
"url": null
} |
java, parsing, xml
How can I improve this ?
Answer: Well, there's a problem here, which is that your question is being read here by people who know the subject far better than your assessors; so you're not actually asking for what the experts consider to be best practice, but for what your assessors, who aren't experts, consider to be best practice.
Many experts will tell you not to use DOM for this. 90% of Java programmers probably would use DOM (as you are doing), but there are far better libraries available (for example JDOM2 or XOM). The only reason anyone uses DOM is because they haven't bothered to look at alternatives. But your assessors are probably expecting a DOM solution.
Now the only thing that strikes me as really bad about your code (and it's hard to judge without seeing the specification of the input XML) is
getParentNode().getAttributes().item(0).getTextContent().equals(value)
because that's looking at the first attribute of the parent of the current target element, and the order of attributes is unpredictable. Even if you know that the parent element will always have exactly one attribute, it's best not to make that assumption in your code. I would expect to see you accessing a specific attribute of the parent element by name, for example
value.equals(getParentNode().getAttibute("name"))
which is also written so it doesn't fail if the attribute is absent.
Another thing I'm not keen on in your answer is the repeated opening of the file in
Files.write(Paths.get("textFile.txt") | {
"domain": "codereview.stackexchange",
"id": 44632,
"lm_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, parsing, xml",
"url": null
} |
java, parsing, xml
That feels thoroughly inefficient to me, though I've no idea if it's really a problem or just my imagination.
Personally, and I have no idea whether your assessors would be satisfied with the answer, I would do this with a one-line XPath 3.1 expression. For example, using the Saxon API because it's the one I know best:
Processor proc = new Processor(false):
XPathCompiler xp = proc.newXPathCompiler();
XdmItem sourceDoc = proc.newDocumentBuilder().build(
new StreamSource("src/resources/xml-File.xml"));
XdmItem result = xp.evaluate(
"string-join(//target[../@name='42'], '\n')",
sourceDoc);
Files.write(Paths.get("textFile.txt"), result.getStringValue()); | {
"domain": "codereview.stackexchange",
"id": 44632,
"lm_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, parsing, xml",
"url": null
} |
javascript, programming-challenge, html, css
Title: Split the Bill and calculate the Tip
Question: I have created a Bill Splitter page that asks for the total bill amount, tip percentage, and the number of people. Then it displays the tip and the total amount (including the tip) each person has to pay out of that bill. I have used simple vanilla JavaScript to complete this project. Being a beginner in front-end development, I want to adapt to all the best practices. I am looking forward to all your feedback.
My Website should have the following features:
Users should be able to view the optimal layout for the app depending on their device's screen size
See hover states for all interactive elements on the page
Calculate the correct tip and total cost of the bill per person
let bill_amount = document.getElementById("amount");
let humans = document.getElementById("people");
let tip_buttons = Array.from(document.getElementsByClassName("tip"));
let reset_button = document.getElementById("reset");
let custom_tip_button = document.getElementById("custom");
let tip_percentage, tip_person, total_bill_person;
let bill_amountFilled = false;
let humansFilled = false;
let buttonClicked = false;
tip_buttons.forEach(function(button) {
button.addEventListener("click", function(event) {
tip_buttons.forEach(function(otherbtns) {
otherbtns.classList.remove("btn-selected");
})
button.classList.add("btn-selected");
tip_percentage = parseFloat(button.innerHTML);
buttonClicked = true;
calculateTip();
});
});
custom_tip_button.addEventListener("input", function(event) {
tip_buttons.forEach(function(button) {
button.classList.remove("btn-selected");
})
tip_percentage = parseFloat(event.target.value);
buttonClicked = true;
calculateTip();
}); | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
javascript, programming-challenge, html, css
function calculateTip() {
if (bill_amountFilled && humansFilled && buttonClicked) {
tip_person = (parseFloat(bill_amount.value) * (0.01 * parseFloat(tip_percentage))) /
parseFloat(humans.value);
total_bill_person = parseFloat(bill_amount.value) / parseFloat(humans.value) +
tip_person;
document.getElementById("tipPerPerson").value = tip_person.toFixed(2);
document.getElementById("totalPerPerson").value = total_bill_person.toFixed(2);
}
}
bill_amount.addEventListener("input", function(event) {
if (bill_amount.value.trim() !== "") {
bill_amountFilled = true;
calculateTip();
} else {
bill_amountFilled = false;
}
});
humans.addEventListener("input", function(event) {
if (humans.value.trim() !== "") {
humansFilled = true;
calculateTip();
} else {
humansFilled = false;
}
});
reset_button.addEventListener("click", function() {
location.reload();
});
document.addEventListener("click", function(event) {
event.preventDefault();
});
body {
background-color: hsl(185, 41%, 84%);
font-family: "Space Mono";
}
h4 {
color: hsl(183, 100%, 15%);
letter-spacing: 15px;
margin: 5% 50% 0% 45%;
}
h5 {
font-size: small;
color: #fff;
display: inline-block;
}
h6 {
margin: 3%;
color: hsl(185, 22%, 45%);
}
.line2 {
margin-top: 0%;
}
.calculator {
display: flex;
margin: 4% 15% 0% 20%;
background-color: #fff;
border-radius: 2.5%;
z-index: 1;
width: 60%;
padding: 0.9%;
}
.left-box {
float: left;
background-color: #fff;
width: 50%;
padding: 2%;
box-sizing: border-box;
}
.left-input {
background-color: hsl(189, 41%, 97%);
border: none;
margin-bottom: 5px;
text-align: right;
color: hsl(183, 100%, 15%);
width: 80%;
}
.left-input:focus {
outline: none !important;
border: 1px solid aquamarine;
box-shadow: 0 0 10px #719ECE;
} | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
javascript, programming-challenge, html, css
#custom {
display: inline-block;
background-color: hsl(189, 41%, 97%);
color: hsl(183, 100%, 15%);
width: 25%;
height: 11%;
text-align: center;
border-radius: 5%;
cursor: pointer;
}
.btn {
width: 80px;
margin-right: 20px;
margin-bottom: 10px;
background-color: hsl(183, 100%, 15%);
border: none;
}
.btn-selected {
background-color: hsl(166, 61%, 39%);
}
.custom:focus {
background-color: hsl(161, 28%, 62%);
color: #fff;
}
.right-box {
float: right;
width: 50%;
box-sizing: border-box;
background-color: hsl(183, 100%, 15%);
padding: 2.5%;
border-radius: 5%;
}
.right-input {
width: 50%;
background-color: hsl(183, 100%, 15%);
border: none;
outline: none;
color: hsl(161, 42%, 58%);
text-align: right;
height: 30px;
font-size: xx-large;
}
.btn-lg {
background-color: hsl(161, 42%, 58%);
width: 100%;
margin-top: 100px;
} | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
javascript, programming-challenge, html, css
.btn-lg {
background-color: hsl(161, 42%, 58%);
width: 100%;
margin-top: 100px;
}
@media only screen and (max-width: 600px) {
h4 {
margin: 5% 30% 5% 40%;
}
.calculator {
display: inline-block;
width: 100%;
margin-left: 0%;
}
.left-box {
display: inline-block;
width: 100%;
margin-left: 0%;
}
.right-box {
display: inline-block;
width: 100%;
margin-left: 0%;
}
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- displays
site properly based on user's device -->
<link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
<title>Tip Calculator App</title>
<!--Font Awesome Links-->
<script src="https://kit.fontawesome.com/fd6cc398e6.js" crossorigin="anonymous">
</script>
<!--Google Fonts-->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?
family=Space+Mono:ital,wght@0,700;1,700&display=swap" rel="stylesheet">
<!--Bootstrap Links-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-
rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
</head>
<body>
<div class="top-heading">
<h4 class="line1">SPLI</h4>
<h4 class="line2">TTER</h4>
</div>
<main>
<div class="calculator"> | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
javascript, programming-challenge, html, css
<main>
<div class="calculator">
<div class="left-box">
<h6>Bill</h6>
<span class="text-addon"><i class="fa-solid fa-dollar-sign"></i></span>
<input type="text" class="left-input" id="amount">
<h6>Select Tip %</h6>
<button type="button" class="btn btn-primary tip">5%</button>
<button type="button" class="btn btn-primary tip">10%</button>
<button type="button" class="btn btn-primary tip">15%</button>
<button type="button" class="btn btn-primary tip">25%</button>
<button type="button" class="btn btn-primary tip">50%</button>
<input type="text" class="left-input" id="custom" placeholder="Custom">
<h6>Number of People</h6>
<span class="people-addon"><i class="fa-solid fa-person"></i></span>
<input type="text" class="left-input" id="people">
</div>
<div class="right-box">
<h5>Tip Amount / person</h5>
<input type="text" id="tipPerPerson" class="right-input" readonly placeholder="$0.00"><br><br><br>
<h5>Total / person</h5>
<input type="text" id="totalPerPerson" class="right-input" style="margin-left:
40px;" readonly placeholder="$0.00"><br><br><br>
<button type="button" class="btn btn-primary btn-lg" id="reset">Reset</button>
</div>
</div>
</main>
</body>
Live Site URL
Problem Statement
Solution Repository
Answer: 1 HTML
Your markup is completely valid according to W3C and WHATWG markup rules. The Markup validation return no flags. However, I have to flag, that the code you submitted for review differs from the code you used on your web server. If I would purely review the code you submitted, I would need to flag the missing <!DOCTYPE HTML>, <html> tags, and the lang attribute.
1.1 Conventions | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
javascript, programming-challenge, html, css
I see no usage of conventions and only a few comments within the
<head> element. Overall your code is freestyle and harder than
necessary to read.
The naming of your IDs and classes for large parts is not self-explaining. left-input is a poor name. Neither from the naming nor from the visual example I would understand what the classes are for.
You using Bootstap-5 but your class names indicate that for most parts you are not using it and rather rely on a long custom CSS file. While it is acceptable to mix both you rather should decide if you really need Bootstrap and if, then you should use it to the full extent and cut down your custom CSS to that part that can't be solved with Bootstrap.
As you already use Bootstrap and custom CSS you should stick to them. You should never mix them with inline-style!
1.2 Accessibility & Semantics
Your code is for most parts inaccessible. With the exception of <main> I see no specific semantic tag or attribute. | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
javascript, programming-challenge, html, css
<div class="top-heading> would be a <header>
In your header you decided to split your headline into 2 lines by using 2 separate headline elements. You rather should split it to the next line with either <br> or <wbr>. As of now, a screen reader would recognize it as 2 independent headlines that will be pronounced incorrectly: headline: S P L I /pause/ headline: Double T E R
Your Select Tip % section could be improved. Semantically, you should wrap them in a fieldset and use Select Tip % as the legend. Also, you should only be able to make one selection. As such the usage of radio buttons would have been more appropriate than the usage of different buttons and inputs. It also would improve the accessibility as then the percentages would be directly connected to the legend.
Inputs should always have a label connected to them. Even if you hide the label within CSS, you should have them for screen readers.
You are using incorrect input types. Your inputs are supposed to be type=number to only allow numbers. For people, you need integers as you can't have 6.5 people. For money amounts, you want inputs with a max of 2 decimal places.
Neither Bill (should be Bill amount) nor Number of People or the other h5 is a headline. It is a label for the input.
You used inputs and set them to readonly while those elements are actually <output>s.
1.3 Head Element | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
javascript, programming-challenge, html, css
1.3 Head Element
IMHO your <head> is overfilled. You using a lot of dependencies for a very small web application.
In the code you submitted you miss the custom CSS link
In the code you submitted you miss the custom JS link while on the web server, it is at the end of the body. You can't make use of asynchronous loading and overall it would have been better to include it also within your head element.
<meta name="viewport" content="width=device-width, initial-scale=1.0"> should only be used if you actually know what it does and how you counter the downsides of it. It is not a tool to properly display the site on every device. It is a tool that removed DPR (Device Pixel Ratio) features to make it easier for developers as they don't need actual devices to test for the cost of poorer UX. Especially in your case, it adds no responsivness but poor UX on high-resolution mobile devices.
Also if you are intending to operate within the EU, you would also be required to provide a disclaimer for your Google API usage.
1.4 Body Element
Within semantics and accessibility, I already said a lot about your markup and element decisions.
What I still want to add are your buttons. As said before, you should not use buttons here in the first place. If you do, then don't get the value by reading out their text node. Add a data attribute instead and read out that.
your container <div class="calculator"> seems unnecessary to me. Why not use the <main> element directly?
<br> is a linebreak to break a text instantly to the next line. It is not a tool to create visual spacing! Visual spacings have to be included through CSS.
2 CSS
Your CSS is unordered and repetitive. Your design choices are well thought through but missing accessibility. Overall they could be improved on your coding methods.
2.1 Accessibility | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
javascript, programming-challenge, html, css
The inputs have a slightly different background color and especially
for colo-blind will not be recognized as such. a stronger contrast
would have been better.
the buttons and the input for the tip amount have different sizes. This is caused by their nature and does not look smooth. You should decide on a uniform size and form to look the same with exception of the background color.
2.2 Responsivness
Your web application is not responsive at all or at least has never been correctly tested. While I think you read about responsive web design you properly misunderstood the rules or pieces of advice. While you should use relative units, % is not a unit that should be used for everything. em and rem would have been more appropriate in most cases and would have caused fewer issues.
A good responsive design starts with mobile first, then tablets, then laptops, then desktops.
2.3 Structure
While it is correct to start with the general tags, you should continue then with classes and then with ids and those in the order of their first appearance. Alternatively, you should block the classes, IDs, and tags according to their first appearance to have at least some kind of logical order.
A lot of your code is repetitive. select multiple classes, tags, or IDs and apply all the styles to them that are the same for all those elements.
As example:
before:
@media only screen and (max-width: 600px) {
h4 {
margin: 5% 30% 5% 40%;
}
.calculator {
display: inline-block;
width: 100%;
margin-left: 0%;
}
.left-box {
display: inline-block;
width: 100%;
margin-left: 0%;
}
.right-box {
display: inline-block;
width: 100%;
margin-left: 0%;
}
}
after:
@media only screen and (max-width: 600px) {
h4 {
margin: 5% 30% 5% 40%;
}
.calculator,
.left-box,
.right-box {
display: inline-block;
width: 100%;
margin-left: 0%;
}
} | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
javascript, programming-challenge, html, css
Make usage of the :root selector and then use CSS variables. Especially on things like colors, margins/paddings, and gaps you could include your CSS variable which would make maintenance a lot easier.
Use properties only within their scope. float is for floating an element within a text-block. Something like pictures in a newspaper. float is not a property to align items next to each other!
3 JS
Overall your JS is very basic and still acceptable to read while it still could be improved.
3.1 Conventions
Make use of constants. Especially if you reference elements then it is to be expected that the elements do not change. As such a const would be appropriate.
declare const at the very top of the JS and use capital names to differentiate them from variables.
be consequent with the mentioned points from above. At the end you still used document.element.value = ... which is harder to read while you could have declared the element itself as const at the top.
Make parameters visual by adding underscores to it __param. This makes the code easier to read and as such easier to maintain by others.
choose names that are self-explaining even if they are longer
don't spare with comments. While your code should be self-explaining while reading it, carefully placed comments with short descriptions will significantly improve readability.
Do not use innerHTML as they pose a security risk (XSS) and are slow (require the reparsing of the DOM).
3.2 Input validation
Inputs should always be validated. Validated for their correctness and plausibility. As an example you can insert twenty as the value of the Bill amount. twenty however, is a string and will return a NaN (Not a Number) error. Same I could insert a 20e10 which is a valid number. Or I could include a negative number which also is a valid number. So you should always check if the input is plausible. If it is not, throw an error message at the user.
3.3 Logic | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
javascript, programming-challenge, html, css
3.3 Logic
You have a major logic error. If I have to divide a 100$ bill through 3 persons then every person would need to pay 33.33$. By division rules, it would be correct after rounding. However, if you multiply 33.33$ by 3 then you would be 1 cent short. You always need to round up here as otherwise, you might be short because of the rounding. It is legal to pay a few cents more than needed but it is illegal to pay less than the bill.
If you select no tip which is completely plausible then the program will not start.
Only if bill amount, tip, and amount of persons is filled out correctly, the calculation will start. If not, the program will simply do nothing. You should always throw an error message at the user and explain to him why the program does not start.
3.4 Coding Style
I do not understand why you used Array.from(document.getElementsByClassName('tip')) which is unnecessary and code-wise ugly. getElementsByClassName would return an HTML Collection Object while querySelectorAll would return a Node List. Both are array-like objects that can be iterated over without converting them specifically to an array.
location.reload() is to reload a document. It should never be used to reset inputs and calculations to the original state. It will spam the history of a user for no reason. | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
javascript, programming-challenge, html, css
4 Rating
4.1 Hobby Programmer
This web application shows sufficient planning. In general, it seems to me that a hobby programmer knew what he did. I would assume that a hobby programmer codes to the best of his abilities but was missing heavily on cleanness, simplicity, and necessity. A good approach to improve would be to overthink the resources of learning and by getting regular supervision from a senior developer.
Grade: B- - C+
4.2 Developer Trainee
For a Trainee the planning phase would still be sufficient. However, a trainee should have already learned about the economic effect of programming. The code misses not only cleanness, simplicity, and necessity but also up-to-date coding. Missing conventions on top will have a harder impact on the economic value which even for a trainee is not acceptable. A trainee should know better and know that coding is the smallest part of program development.
Grade: D
4.3 Junior Developer
A Junior Developer should have already rock solid foundations. Especially the methods implemented as well as the technologies are not to be expected by a Junior Developer. Missing input validation is not excusable for a Junior Developer.
Grade E - E- | {
"domain": "codereview.stackexchange",
"id": 44633,
"lm_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, programming-challenge, html, css",
"url": null
} |
c++, beginner, tree, pointers
Title: Port Node and TreeBuilder from Python to C++
Question: I am trying to port a TreeBuilder Python class to C++, keeping the structure as close as possible to the original. Here is a simplified Python version: https://onlinegdb.com/I4dg0hCtg
The purpose of tree is to represent a generic game tree (Chess, Go, Checkers, etc.) It is passed forward to a class (Whatever), which builds an another representation based on some depth-wise statistics.
Environment here is a mock class. In the real application, actions are passed back based on the game's rules
The main reason of porting the code is speed. I am very new to C++, but as I know dynamic allocation on the heap costs more. I do not know if it worth (or even possible) to build such a tree without dynamic initialization.
As far as I know using raw pointers has a little benefit of performance over smart pointers, but GC should be done by hand. My plan is after the trees are generated, and used by Whatever class (see my first point), Whatever class has to destroy the tree's node recursively. (Node's destructor should delete its children)
main.cc
#include "Node.h"
#include "Environment.h"
#include "Options.h"
#include "TreeBuilder.h"
int main() {
Node* node = new Node();
Environment* environment = new Environment();
node->environment = environment;
Options* options = new Options();
options->root = node;
TreeBuilder* treeBuilder = new TreeBuilder();
Node* tree = treeBuilder->buildTree(options);
tree->printTree();
return 0;
}
Node.h
#pragma once
#include <vector>
#include <iostream>
// Environment and Node has circular dependency, forward declaration
class Environment;
class Node
{
public:
Node * parent = nullptr;
int depth = 0;
std::vector < Node * >children;
Environment *environment = nullptr;
void printTree ();
~Node();
};
Node.cc
#include "Node.h" | {
"domain": "codereview.stackexchange",
"id": 44634,
"lm_label": 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, tree, pointers",
"url": null
} |
c++, beginner, tree, pointers
void printTree ();
~Node();
};
Node.cc
#include "Node.h"
void Node::printTree ()
{
// Print this node's depth
for (int i = 0; i < this->depth; i++)
{
std::cout << "\t";
}
std::cout << "- Depth: " << this->depth << std::endl;
// Recursively print the children
for (Node * child:this->children) {
child->printTree ();
}
}
Node::~Node() {
for (Node* child : children) {
delete child;
}
}
Environment.h
#pragma once
#include <vector>
#include "Node.h"
class Environment
{
public:
std::vector < int >getActions (Node * parent);
};
Environment.cc
#include "Environment.h"
std::vector<int> Environment::getActions(Node* parent) {
std::vector<int> actions;
if (parent->depth != 3) {
for (int x = 0; x <= parent->depth; x++) {
actions.push_back(x * 100);
}
}
return actions;
}
Options.h
#pragma once
#include "Node.h"
#include "Environment.h"
class Options
{
public:
Node * root = nullptr;
Environment *environment = nullptr;
};
TreeBuilder.h
#pragma once
#include "Node.h"
#include "Environment.h"
#include "Options.h"
class TreeBuilder
{
public:
Environment * environment = nullptr;
std::vector < Node * >getChildren (Node * parent);
void _buildTree (Node * node);
Node *buildTree (Options * options);
};
TreeBuilder.cc
#include "TreeBuilder.h"
#include <iostream>
std::vector < Node * >TreeBuilder::getChildren (Node * parent)
{
std::vector < Node * >children;
std::vector < int >
actions = this->environment->getActions (parent);
for (int x = 0; x < actions.size (); x++)
{
Node* node = new Node ();
node->parent = parent;
node->depth = parent->depth + 1;
node->environment = parent->environment;
children.push_back (node);
}
return children;
} | {
"domain": "codereview.stackexchange",
"id": 44634,
"lm_label": 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, tree, pointers",
"url": null
} |
c++, beginner, tree, pointers
void
TreeBuilder::_buildTree (Node * node)
{
std::vector < Node * >children = this->getChildren (node);
node->children = children;
for (int i = 0; i < children.size (); i++)
{
this->_buildTree (children[i]);
}
}
Node* TreeBuilder::buildTree (Options * options)
{
Node *root = new Node ();
root->environment = options->root->environment;
this->environment = root->environment;
this->_buildTree (root);
return root;
}
Here is a playground version, https://onlinegdb.com/eHbJGXqN4, to see it in action.
Answer: Initial usage
This is not C++ like. You are using dynamic allocation where it is not needed. Simply make things local variables. Also use the constructor to make sure the objects are correctly initialized on construction (don't use a two step initialization of create then set up).
The tree you eventually build will have to be dynamic but you should use smart pointers to manage the nodes. There is absolutely zero cost of std::unique_ptr over a RAW pointer it simply makes sure the memory is managed correctly (and release is much more well-defined compared to Garbage collected languages (think of it as fine grain garbage collection that happens immediately when the object is no longer needed)).
This is how I would have the main function look.
#include "Node.h"
#include "Environment.h"
#include "Options.h"
#include "TreeBuilder.h"
int main()
{
Environment environment;
Node node(environment);
Options options(node);
TreeBuilder treeBuilder;
std::unique_ptr<Node> tree = treeBuilder.buildTree(options);
tree->printTree();
}
Statements:
As far as I know using raw pointers has a little benefit of performance over smart pointers, but GC should be done by hand.
There are no benifits to using RAW pointers.
GC should NOT be done by hand (this is not C).
Use smart pointers or containers to handle resource management.
There is no cost of std::unique_ptr over a RAW pointer. BUT lots of benifits. | {
"domain": "codereview.stackexchange",
"id": 44634,
"lm_label": 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, tree, pointers",
"url": null
} |
c++, beginner, tree, pointers
My plan is after the trees are generated, and used by Whatever class (see my first point), Whatever class has to destroy the tree's node recursively. (Node's destructor should delete its children)
I don't think it will be a problem.
Here you are making a Node a container (its responsible for resource managment). This does mean you need to know the rule of 3/5 to make sure you do resource management correctly.
Code Review
Hate this:
#pragma once
It is non-standard.
Use include guards. It's standard and works as expected everywhere.
#ifndef MY_NAMESPACE_MY_CLASS_H
#define MY_NAMESPACE_MY_CLASS_H
// STUFF
#endif
Don't see streams being used in Node.h
#include <iostream>. //remove this.
// Environment and Node has circular dependency, forward declaration
Unless you explicitly use a class in a header file, or its size is needed then you should always use forward declaration.
class Environment;
why are all the members public?
Data members should always be private (unless you are making a simply property bag).
class Node
{
public:
Node * parent = nullptr;
int depth = 0;
std::vector < Node * >children;
Environment *environment = nullptr;
void printTree (); // only for debugging
};
Personally. Assuing that the Node always needs an environment I would make that a reference (not a pointer).
But either way I would allow you to pass the environment as a parameter in the constructor (see main description above).
You have not obeyed the rule of three.
std::vector < Node * >children;
If your class does resource management (which it does with children). Then you need to make sure you either define the copy semantics or disable them. Otherwise you are going to run into issues.
I vote for diabling at this point as it is simpler:
Node(Node const&) = delete;
Node& operator=(Node const&) = delete;
Some Style pointers:
Types are very important in C++. So all the type information is usually grouped together away from the name.
Node * parent = nullptr; | {
"domain": "codereview.stackexchange",
"id": 44634,
"lm_label": 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, tree, pointers",
"url": null
} |
c++, beginner, tree, pointers
Normally I would put the * with the Node like this:
Node* parent = nullptr;
Not fond of the extra white space here:
std::vector < Node * >children;
I would write it like this:
std::vector<Node*> children;
Environment.h
You don't use Node or need the Node size in the Environment.h header. So don't include the header file.
#include "Node.h"
Just forward declare the Node inside the header.
You may have to include it inside the source file (but try not to include it in the header file).
Again public Data Members is a bad idea.
class Environment
{
public:
std::vector < int >getActions (Node * parent);
};
Options.h
You don't use the Node or Environment objects or depend on their size. So use forward declaration inside the header file.
#include "Node.h"
#include "Environment.h"
Not sure. But if either of these is required then they should be references not pointers. Add a constructor that allows you to initialize the references on construction.
class Options
{
public:
Node * root = nullptr;
Environment *environment = nullptr;
};
I see a couple of places where you use this->.
STOP THAT.
If you need to use this-> it means you have done a bad job naming something and you need to explicitly make sure you are using the member. This is a sure way to have bugs in your code.
Make sure all objects are uniquely defined and don't shadow other variables. Also make sure the names are meaningful so you can quickly identify that you are using the correct variable. | {
"domain": "codereview.stackexchange",
"id": 44634,
"lm_label": 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, tree, pointers",
"url": null
} |
c++, math-expression-eval
Title: Updated Per Feedback - C++ Binary Mathematics Class
Question: Below is the updated binary mathematics class from the feedback provided here.
It was decided that the project should simply be written with an expectation of using C++20 as the minimum version to use.
The template was removed. Once removed I found there was a binary overflow happening in a bit shift that was masked by the template. Lesson learned. Make what you need now, and don’t worry about what you may need later.
Added friend overloads for move semantics on operators. Please let me know if additional changes are needed.
Converted the comp method to the <=> operator.
I had been under the impression that the compiler would automatically create the needed move, and assignment operator and constructor overloads. This post clarified the misunderstanding on my part.
I am keeping twos compliment. It is primarily used later as a method for confirming commutations done using other methods through tests. It really isn’t used otherwise.
There are additional classes for whole number, up through complex numbers. But I need to cascade what was learned here to them before I post them. If there is no additional feedback, I will create a new post for whole numbers next, and go from there.
note - If this wasn't the right way to follow up on the class, please let me know. :-)
binary_register.h
#include <bitset>
#include <limits>
#include <vector>
#include "../support_files/Type_Defines.h"
namespace Olly { | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
#include "../support_files/Type_Defines.h"
namespace Olly {
/********************************************************************************************/
//
// 'binary_register' class
//
// The binary_register class implements a series of binary registers sized to
// the integral type passed during to the template at definition.
//
// Support for all of the binary operation is provides, along with binary
// based mathematical operations. The implementation is little endian.
//
/********************************************************************************************/
class binary_register {
public:
#if _WIN32 || _WIN64
#if _WIN64
using Word = unsigned long int;
using Double_Word = unsigned long long int;
#else
using Word = unsigned int;
using Double_Word = unsigned long int;
#endif
#endif
#if __GNUC__
#if __x86_64__ || __ppc64__
using Word = unsigned long int;
using Double_Word = unsigned long long int;
#else
using Word = unsigned int;
using Double_Word = unsigned long int;
#endif
#endif
using Register = std::vector<Word>;
static const Word MASK = ~Word(0);
static const std::size_t BITS = std::numeric_limits<Word>::digits;
binary_register();
binary_register(const Text& value, Text base = "10");
binary_register(const std::size_t& size, Word value);
explicit
binary_register(const std::size_t& size);
virtual ~binary_register();
binary_register(binary_register&& obj) = default;
binary_register(const binary_register& obj) = default;
binary_register& operator=(binary_register&& obj) = default;
binary_register& operator=(const binary_register& obj) = default; | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
friend void swap(binary_register& first, binary_register& second);
bool is() const; // bool conversion.
bool all() const; // bool test for all bits being set to 1.
std::size_t count() const; // The count of bits set to 1.
std::size_t lead_bit() const; // Return the lead bit.
std::size_t last_bit() const; // Return the last bit.
Word lead_reg() const; // Return the leading register.
Word last_reg() const; // Return the last register.
bool at_bit(std::size_t index) const; // Return the value of a bit at the index.
Word& at_reg(std::size_t index); // Return the word at the indexed register.
Word at_reg(std::size_t index) const;
Text to_string() const; // Return a string representation at radix 10.
Text to_string(Word base) const; // Return a string representation at radix 'base'.
void to_string(Text_Stream& stream) const; // Send a string representation to a stream_type.
std::size_t size_bits() const; // Get the total size in bits of the register.
std::size_t size_regs() const; // Get the total size of words in the register.
binary_register& resize_regs(std::size_t size); // Resize the register to 'size' number of elements.
binary_register& resize_regs(std::size_t size, Word n);
binary_register& set(); // Set all bits to true.
binary_register& set(std::size_t index); // Set a bit at 'index' to true. | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
binary_register& reset(); // Set all bits to false.
binary_register& reset(std::size_t index); // Set a bit at 'index' to false.
binary_register& flip(); // Flip the truth of every bit in the register.
binary_register& flip(std::size_t index); // Flip the truth of a bit at 'index'.
bool operator==(const binary_register& b) const;
bool operator!=(const binary_register& b) const;
std::partial_ordering operator<=>(const binary_register& b) const;
binary_register& operator&=(const binary_register& other);
binary_register& operator|=(const binary_register& other);
binary_register& operator^=(const binary_register& other);
binary_register operator&(const binary_register& b) const;
binary_register operator|(const binary_register& b) const;
binary_register operator^(const binary_register& b) const;
binary_register operator~() const;
friend binary_register operator&(binary_register&& a, const binary_register& b);
friend binary_register operator|(binary_register&& a, const binary_register& b);
friend binary_register operator^(binary_register&& a, const binary_register& b);
binary_register& operator<<=(std::size_t index);
binary_register& operator>>=(std::size_t index);
binary_register operator<<(std::size_t index) const;
binary_register operator>>(std::size_t index) const;
friend binary_register operator<<(binary_register&& a, std::size_t index);
friend binary_register operator>>(binary_register&& a, std::size_t index); | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
binary_register& operator+=(const binary_register& other);
binary_register& operator-=(const binary_register& other);
binary_register& operator*=(const binary_register& other);
binary_register& operator/=(const binary_register& other);
binary_register& operator%=(const binary_register& other);
binary_register operator+(const binary_register& b) const;
binary_register operator-(const binary_register& b) const;
binary_register operator*(const binary_register& b) const;
binary_register operator/(const binary_register& b) const;
binary_register operator%(const binary_register& b) const;
friend binary_register operator+(binary_register&& a, const binary_register& b);
friend binary_register operator-(binary_register&& a, const binary_register& b);
friend binary_register operator*(binary_register&& a, const binary_register& b);
friend binary_register operator/(binary_register&& a, const binary_register& b);
friend binary_register operator%(binary_register&& a, const binary_register& b);
binary_register& operator++();
binary_register operator++(int);
binary_register& operator--();
binary_register operator--(int);
template<typename I>
Word to_integral() const; // Cast the register to an integral of type T.
binary_register bin_comp() const; // Return the binary compliment of the register.
// Get both the qotient and the remainder of the regester divided by 'other'.
void div_rem(binary_register& other, binary_register& qot, binary_register& rem) const;
binary_register& trim(); // Remove all trailing zeros, from the register.
// But leave atleast one register, even if a value of zero.
private:
typedef std::bitset<BITS> single_prc_bitset;
static const Word ONE = 1;
Register _reg; | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
static const Word ONE = 1;
Register _reg;
void get_shift_index(std::size_t& index, std::size_t& reg_index, std::size_t& bit_index) const;
void divide_remainder(const binary_register& x, binary_register y, binary_register& q, binary_register& r) const;
Text get_string(Word base) const;
void left_shift_bits(std::size_t& word_index, std::size_t& bit_index);
void right_shift_bits(std::size_t& word_index, std::size_t& bit_index);
};
/********************************************************************************************/
//
// 'binary_register' template implimentation
//
/********************************************************************************************/
template<typename I>
binary_register::Word binary_register::to_integral() const {
static_assert(std::numeric_limits<I>::is_integer, "Integral required.");
if (!_reg.empty()) {
auto bits_of_I = std::numeric_limits<I>::digits;
if (bits_of_I >= BITS && !_reg.empty()) {
return I(_reg.front());
}
I n = 0;
for (int i = BITS / bits_of_I; i >= 0; i -= 1) {
n <<= bits_of_I;
n += at_reg(i);
}
return static_cast<Word>(n);
}
return I(0);
}
}
binary_register.cpp
#include "binary_register.h"
namespace Olly {
binary_register::binary_register() : _reg(1, 0) {
}
binary_register::binary_register(const std::size_t& size) : _reg((size > 0 ? size : 1), 0) {
}
binary_register::binary_register(const std::size_t& size, Word value) : _reg((size > 0 ? size : 1), value) {
}
binary_register::binary_register(const Text& value, Text base) : _reg(1, 0) {
binary_register::Word base_radix = to<Word>(base); // Get the base radix to use. | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
binary_register::Word base_radix = to<Word>(base); // Get the base radix to use.
binary_register radix(1, base_radix); // Define a binary_register to act as the radix.
for (auto i : value) { // Loop through each digit and add it to the binary_register.
Text digit_str = "";
digit_str.push_back(i);
binary_register::Word n = to<Word>(digit_str);
if (n < base_radix) {
binary_register digit(1, n);
operator*=(radix);
operator+=(digit);
}
}
}
binary_register::~binary_register() {
}
void swap(binary_register& left, binary_register& right) {
auto temp = std::move(left);
left = std::move(right);
right = std::move(temp);
}
bool binary_register::is() const {
for (auto i : _reg) {
if (i) {
return true;
}
}
return false;
}
bool binary_register::all() const {
for (auto i : _reg) {
if (i != MASK) {
return false;
}
}
return true;
}
std::size_t binary_register::count() const {
std::size_t count = 0;
for (const auto i : _reg) {
auto n = i;
while (n > 0) {
if (n & 1) {
count += 1;
}
n >>= 1;
}
}
return count;
}
std::size_t binary_register::lead_bit() const {
std::size_t word_index = _reg.size();
binary_register::Word mask = (ONE << (BITS - ONE));
for (auto i = _reg.crbegin(); i != _reg.crend(); ++i) {
word_index -= 1;
auto a = *i;
std::size_t bit_index = BITS;
while (a) { | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
auto a = *i;
std::size_t bit_index = BITS;
while (a) {
if (a & mask) {
return bit_index + (word_index * BITS);
}
a <<= 1;
bit_index -= 1;
}
}
return 0;
}
std::size_t binary_register::last_bit() const {
std::size_t word_index = 0;
binary_register::Word mask = 1;
for (auto i = _reg.cbegin(); i != _reg.cend(); ++i) {
auto a = *i;
std::size_t bit_index = 1;
while (a) {
if (a & mask) {
return bit_index + (word_index * BITS);
}
a >>= 1;
bit_index += 1;
}
word_index += 1;
}
return 0;
}
binary_register::Word binary_register::lead_reg() const {
if (_reg.empty()) {
return Word(0);
}
return _reg.back();
}
binary_register::Word binary_register::last_reg() const {
if (_reg.empty()) {
return Word(0);
}
return _reg.front();
}
bool binary_register::at_bit(std::size_t index) const {
std::size_t reg_index, bit_index;
get_shift_index(index, reg_index, bit_index);
if (reg_index < _reg.size()) {
return _reg[reg_index] & (ONE << (bit_index - ONE));
}
return false;
}
binary_register::Word& binary_register::at_reg(std::size_t index) {
if (index >= _reg.size()) {
_reg.resize(index + 1, 0);
}
return _reg[index];
}
binary_register::Word binary_register::at_reg(std::size_t index) const {
if (index < _reg.size()) {
return _reg[index];
}
return Word(0);
}
Text binary_register::to_string() const {
return to_string(10);
}
Text binary_register::to_string(Word base) const { | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
return to_string(10);
}
Text binary_register::to_string(Word base) const {
if (base > 360) {
return "Radix must be between 0 and 360.";
}
if (base == 0) {
Text_Stream stream;
to_string(stream);
return stream.str();
}
if (!is()) {
return "0";
}
return get_string(base);
}
void binary_register::to_string(Text_Stream& stream) const {
std::size_t i = _reg.size();
while (i-- > 1) {
stream << "word[" << i << "] = " << single_prc_bitset(_reg[i]).to_string() << "\n";
}
stream << "word[" << 0 << "] = " << single_prc_bitset(_reg[i]).to_string();
}
std::size_t binary_register::size_bits() const {
return _reg.size() * BITS;
}
std::size_t binary_register::size_regs() const {
return _reg.size();
}
binary_register& binary_register::resize_regs(std::size_t size) {
_reg.resize(size);
return *this;
}
binary_register& binary_register::resize_regs(std::size_t size, Word n) {
_reg.resize(size, n);
return *this;
}
binary_register& binary_register::set() {
for (auto i = _reg.begin(); i != _reg.end(); ++i) {
*i = MASK;
}
return *this;
}
binary_register& binary_register::set(std::size_t index) {
std::size_t reg_index, bit_index;
get_shift_index(index, reg_index, bit_index);
if (reg_index >= _reg.size()) {
_reg.resize(reg_index + 1, 0);
}
_reg[reg_index] |= (ONE << (bit_index - ONE));
return *this;
}
binary_register& binary_register::reset() {
for (std::size_t i = 0, end = _reg.size(); i < end; i += 1) {
_reg[i] = Word(0);
}
return *this;
}
binary_register& binary_register::reset(std::size_t index) { | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
return *this;
}
binary_register& binary_register::reset(std::size_t index) {
std::size_t reg_index, bit_index;
get_shift_index(index, reg_index, bit_index);
if (reg_index >= _reg.size()) {
_reg.resize(reg_index + 1, 0);
}
_reg[reg_index] &= ~(1 << (bit_index - 1));
return *this;
}
binary_register& binary_register::flip() {
for (std::size_t i = 0, end = _reg.size(); i < end; i += 1) {
_reg[i] = ~_reg[i];
}
return *this;
}
binary_register& binary_register::flip(std::size_t index) {
std::size_t reg_index, bit_index;
get_shift_index(index, reg_index, bit_index);
if (reg_index >= _reg.size()) {
_reg.resize(reg_index + 1, 0);
}
_reg[reg_index] ^= (1 << (bit_index - 1));
return *this;
}
bool binary_register::operator==(const binary_register& b) const {
return operator<=>(b) == std::partial_ordering::equivalent;
}
bool binary_register::operator!=(const binary_register& b) const {
return operator<=>(b) != std::partial_ordering::equivalent;
}
std::partial_ordering binary_register::operator<=>(const binary_register& b) const {
std::size_t i = size_regs() > b.size_regs() ? size_regs() : b.size_regs();
while (i-- > 0) {
auto x = at_reg(i);
auto y = b.at_reg(i);
if (x > y) {
return std::partial_ordering::greater;
}
if (x < y) {
return std::partial_ordering::less;
}
}
return std::partial_ordering::equivalent;
}
binary_register& binary_register::operator&=(const binary_register& other) {
if (_reg.size() < other._reg.size()) {
_reg.resize(other._reg.size(), 0);
} | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
_reg.resize(other._reg.size(), 0);
}
for (std::size_t i = 0, end = _reg.size(); i < end; i += 1) {
_reg[i] &= other.at_reg(i);
}
return *this;
}
binary_register& binary_register::operator|=(const binary_register& other) {
if (_reg.size() < other._reg.size()) {
_reg.resize(other._reg.size(), 0);
}
for (std::size_t i = 0, end = _reg.size(); i < end; i += 1) {
_reg[i] |= other.at_reg(i);
}
return *this;
}
binary_register& binary_register::operator^=(const binary_register& other) {
if (_reg.size() < other._reg.size()) {
_reg.resize(other._reg.size(), 0);
}
for (std::size_t i = 0, end = _reg.size(); i < end; i += 1) {
_reg[i] ^= other.at_reg(i);
}
return *this;
}
binary_register binary_register::operator&(const binary_register& b) const {
binary_register a(*this);
a &= b;
return a;
}
binary_register binary_register::operator|(const binary_register& b) const {
binary_register a(*this);
a |= b;
return a;
}
binary_register binary_register::operator^(const binary_register& b) const {
binary_register a(*this);
a ^= b;
return a;
}
binary_register binary_register::operator~() const {
binary_register a = *this;
for (std::size_t i = 0, end = a._reg.size(); i < end; i += 1) {
a._reg[i] = ~a._reg[i];
}
return a;
}
binary_register operator&(binary_register&& a, const binary_register& b) {
return a &= b;
}
binary_register operator|(binary_register&& a, const binary_register& b) {
return a |= b;
}
binary_register operator^(binary_register&& a, const binary_register& b) {
return a ^= b;
}
binary_register& binary_register::operator<<=(std::size_t index) { | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
binary_register& binary_register::operator<<=(std::size_t index) {
std::size_t word_index, bit_index;
get_shift_index(index, word_index, bit_index);
if (word_index) {
_reg.insert(_reg.begin(), word_index, 0);
}
if (bit_index) {
left_shift_bits(word_index, bit_index);
}
return *this;
}
binary_register& binary_register::operator>>=(std::size_t index) {
std::size_t word_index, bit_index;
get_shift_index(index, word_index, bit_index);
if (word_index) {
if (word_index < _reg.size()) {
_reg.erase(_reg.begin(), _reg.begin() + word_index);
}
else {
for (auto i = _reg.begin(), end = _reg.end(); i != end; ++i) {
*i = 0;
}
return *this;
}
}
if (bit_index) {
right_shift_bits(word_index, bit_index);
}
return *this;
}
binary_register binary_register::operator<<(std::size_t index) const {
binary_register a(*this);
a <<= index;
return a;
}
binary_register binary_register::operator>>(std::size_t index) const {
binary_register a(*this);
a >>= index;
return a;
}
binary_register operator<<(binary_register&& a, std::size_t index) {
return a <<= index;
}
binary_register operator>>(binary_register&& a, std::size_t index) {
return a >>= index;
}
binary_register& binary_register::operator+=(const binary_register& other) {
binary_register b(other);
binary_register c;
while (b.is()) {
c = (*this & b) << 1;
*this ^= b;
b = c;
}
return *this;
}
binary_register& binary_register::operator-=(const binary_register& other) {
if (other >= *this) {
return reset();
} | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
if (other >= *this) {
return reset();
}
binary_register b = other;
if (b.size_regs() < size_regs()) {
b._reg.resize(size_regs(), 0);
}
b = b.bin_comp();
b._reg.push_back(0); // Add a word to handle the two's compliment overflow.
*this += b;
_reg.pop_back(); // Get rid of the two's compliment overflow.
return *this;
}
binary_register& binary_register::operator*=(const binary_register& other) {
*this = *this * other;
return *this;
}
binary_register& binary_register::operator/=(const binary_register& other) {
*this = *this / other;
return *this;
}
binary_register& binary_register::operator%=(const binary_register& other) {
*this = *this % other;
return *this;
}
binary_register binary_register::operator+(const binary_register& b) const {
binary_register a = *this;
a += b;
return a;
}
binary_register binary_register::operator-(const binary_register& b) const {
binary_register a = *this;
a -= b;
return a;
}
binary_register binary_register::operator*(const binary_register& b) const {
std::size_t count = 0;
binary_register x;
binary_register y = b;
while (y.is()) {
if (y.at_bit(1)) {
x += (*this << count);
}
count += 1;
y >>= 1;
}
return x;
}
binary_register binary_register::operator/(const binary_register& b) const {
binary_register q;
binary_register r = *this;
divide_remainder(*this, b, q, r);
return q;
}
binary_register binary_register::operator%(const binary_register& b) const {
binary_register q;
binary_register r = *this;
divide_remainder(*this, b, q, r);
return r;
} | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
divide_remainder(*this, b, q, r);
return r;
}
binary_register operator+(binary_register&& a, const binary_register& b) {
return a += b;
}
binary_register operator-(binary_register&& a, const binary_register& b) {
return a -= b;
}
binary_register operator*(binary_register&& a, const binary_register& b) {
return a *= b;
}
binary_register operator/(binary_register&& a, const binary_register& b) {
return a /= b;
}
binary_register operator%(binary_register&& a, const binary_register& b) {
return a &= b;
}
binary_register& binary_register::operator++() {
binary_register one(1, 1);
operator+=(one);
return *this;
}
binary_register binary_register::operator++(int) {
binary_register a(*this);
operator++();
return a;
}
binary_register& binary_register::operator--() {
binary_register one(1, 1);
operator-=(one);
return *this;
}
binary_register binary_register::operator--(int) {
binary_register a(*this);
operator--();
return a;
}
binary_register binary_register::bin_comp() const {
binary_register a = ~*this;
binary_register one(1, 1);
a += one;
return a;
}
void binary_register::div_rem(binary_register& other, binary_register& qot, binary_register& rem) const {
rem = *this;
divide_remainder(*this, other, qot, rem);
}
binary_register& binary_register::trim() {
while (!_reg.empty() && _reg.back() == 0) {
_reg.pop_back();
}
if (_reg.empty()) {
_reg.push_back(0);
}
return *this;
}
void binary_register::get_shift_index(std::size_t& index, std::size_t& reg_index, std::size_t& bit_index) const {
if (index) {
if (index >= BITS) { | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
if (index) {
if (index >= BITS) {
reg_index = index / BITS;
bit_index = index % BITS;
if (!bit_index) {
--reg_index;
bit_index = BITS;
}
return;
}
reg_index = 0;
bit_index = index;
return;
}
reg_index = 0;
bit_index = 0;
}
void binary_register::divide_remainder(const binary_register& x, binary_register y, binary_register& q, binary_register& r) const {
if (!y.is() || !x.is() || x < y) {
return;
}
std::size_t lead_x = x.lead_bit();
std::size_t lead_y = y.lead_bit();
std::size_t bit_dif = (lead_x - lead_y);
y <<= bit_dif;
bit_dif += 2;
while (bit_dif-- > 1) {
if (r >= y) {
q.set(bit_dif);
r -= y;
}
y >>= 1;
}
}
Text binary_register::get_string(Word base) const {
binary_register radix(1, base);
binary_register n = *this;
Text_Stream stream;
while (n.is()) {
binary_register q;
binary_register r = n;
divide_remainder(n, radix, q, r);
n = q;
stream << r.at_reg(0);
}
Text res = stream.str();
std::reverse(res.begin(), res.end());
return res;
}
void binary_register::left_shift_bits(std::size_t& word_index, std::size_t& bit_index) {
std::size_t i = _reg.size();
_reg.push_back(0);
auto bit_mask = Double_Word(MASK);
while (i-- > 0) {
auto buffer = Double_Word();
buffer |= Double_Word(_reg[i]);
buffer <<= bit_index;
_reg[i] = static_cast<Word>(buffer & bit_mask);
buffer >>= BITS;
buffer |= Double_Word(_reg[i + 1]); | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
buffer >>= BITS;
buffer |= Double_Word(_reg[i + 1]);
_reg[i + 1] = static_cast<Word>(buffer);
}
if (_reg.back() == 0) {
_reg.pop_back();
}
}
void binary_register::right_shift_bits(std::size_t& word_index, std::size_t& bit_index) {
bool pop_back = word_index ? false : true;
if (word_index) {
word_index -= 1;
}
_reg.push_back(0);
auto inv_index = BITS - bit_index;
std::size_t end = (_reg.size() - 1);
auto bit_mask = Double_Word(MASK);
for (std::size_t i = 0; i < end; i += 1) {
auto buffer = Double_Word();
buffer |= Double_Word(_reg[i + 1]);
buffer <<= inv_index;
_reg[i] >>= bit_index;
_reg[i] |= static_cast<Word>(buffer & bit_mask);
}
_reg[end] >>= bit_index;
while (word_index-- > 0) {
_reg.push_back(0);
}
if (pop_back) {
_reg.pop_back();
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
Answer: Use fixed-width integer types
Your type aliases for Word and Double_Word are wrong. They may work on your platform, but there is no guarantee that a Double_Word is larger than a Word on all platforms. I recommend that you use the standard fixed-width integer types instead, like std::uint32_t and std::uint64_t.
There are also problems with your #ifdefs: consider for example that one can build Windows binaries using the GNU compiler, so both _WIN32 and __GNUC__ would be set simultaneously.
Naming
I would reconsider using the word "Register" here. In the context of computers, register has a specific meaning. A vector of integers is not a register.
Since the goal is to have a vector where you can access and manipulate individual bits, I think a better name would be bitvector. The standard library already has a type std::bitset which has similar functionality, except that its size is fixed, and your type has a dynamic size like std::vector.
There are also type aliases defined somewhere that you didn't include in the code you posted, like Text and Text_Stream. Are those std::string and std::stringstream? I strongly suggest that you do not create aliases for standard types, it makes it very hard for someone else reading your code to know what is going on, and they'd have to search your code base for the definition of those aliases. Just use std::string and std::stringstream.
Bits or words?
Some member functions work on both bits and words, some don't. Any calling code would need to check sizeof(binary_register::Word) to safely know how big a "word" is. I would simplify things and not expose Word at all in the public API, only allow bit-wise access or let the caller provide an integer type if they want to access multiple bits at once. For example, to_integral<I>() should just remove an I instead of a Word.
Avoid using strings to pass integers | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
Avoid using strings to pass integers
The constructor has an overload that takes a string as input. While this is fine for value to support very large integers, why is base passed as a string? It's immediately converted back to a Word. Why not pass it as a regular integer instead? | {
"domain": "codereview.stackexchange",
"id": 44635,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, math-expression-eval",
"url": null
} |
python, beginner, rock-paper-scissors
Title: "Rock, paper, scissors" game in python
Question: To fulfil the requirements of the instructions, this version of rock, paper, scissors game works by taking a number from the user and the computer to represent their hand. (0 = rock, 1 = paper, 2 = scissors) From the numbers we then get the string representations of their hands. Next, we determine the winner by comparing the string representations of their hands. Lastly, we print out the result of the game to announce the winner.
I tried to make the function determine_winner() as simple as possible and this is how far I could get. Do you think it is a good idea to use dictionary there? Any comments to improve in general would be appreciated.
import random
user_hand = None
computer_hand = None
winner = None
result = None
def get_hand(num: int) -> str:
"""Get str representation of the user or the computer's hand."""
if num == 0:
return "rock"
elif num == 1:
return "paper"
elif num == 2:
return "scissors"
def determine_winner() -> str:
"""Get str representation of the winner."""
user_win_combinations = {"rock": "scissors", "paper": "rock", "scissors": "paper"}
if user_hand == computer_hand:
winner = "Draw"
elif (user_hand, computer_hand) in user_win_combinations.items():
winner = "You"
else:
winner = "Computer"
return winner
# take in a number 0-2 from the user that represents their choice
print("Rock = 0, paper = 1, scissors = 2")
while True:
user_input = input("Please enter your choice: ")
if user_input in ["0", "1", "2"]:
break
else:
print("Incorrect input!")
# get str representations of user's hand and computer's hand.
user_hand = get_hand(int(user_input))
computer_hand = get_hand(random.randint(0,2))
# determine who wins
winner = determine_winner()
# print out the result
print(f"Your choice ({user_hand}) vs Computer's choice ({computer_hand})") | {
"domain": "codereview.stackexchange",
"id": 44636,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, rock-paper-scissors",
"url": null
} |
python, beginner, rock-paper-scissors
# print out the result
print(f"Your choice ({user_hand}) vs Computer's choice ({computer_hand})")
if winner == "Draw":
result = "It's a draw!"
else:
result = f"{winner} won!"
print(result)
Output examples:
# Draw
Rock = 0, paper = 1, scissors = 2
Please enter your choice: 1
Your choice (paper) vs Computer's choice (paper)
It's a draw!
# User wins
Rock = 0, paper = 1, scissors = 2
Please enter your choice: 2
Your choice (scissors) vs Computer's choice (paper)
You won!
# Computer wins
Rock = 0, paper = 1, scissors = 2
Please enter your choice: 2
Your choice (scissors) vs Computer's choice (rock)
Computer won!
Answer: Your code is working, but it needs a lot of improvements.
The function get_hand is redundant, there is no need to convert from int to str just to perform checks.
You can just compare ints directly.
If you need to print the result human readably, just use a list to keep track of the strs and use indexing to retrieve them when needed.
And you absolutely shouldn't use (key, val) in dict.items() to check if dict[key] == val, it is terribly inefficient and unpythonic, as it defeats the purpose of having a dict in the first place. Instead use the correct syntax I mentioned.
And since you already used functions, you should put the game inside a function to increase reusability.
And don't use globals for function arguments, pass them as arguments to functions properly.
There are still a lot room for improvements, but fixing aforementioned issues would make the code good for a beginner.
Suggested code:
import random
HANDS = ['rock', 'paper', 'scissors']
USER_WIN_COMBINATIONS = {0: 2, 1: 0, 2: 1}
def determine_winner(user_hand, computer_hand):
if user_hand == computer_hand:
return "It's a draw!"
winner = "Computer"
if computer_hand == USER_WIN_COMBINATIONS[user_hand]:
winner = "You"
return f"{winner} won!"
def game()
print("Rock = 0, paper = 1, scissors = 2") | {
"domain": "codereview.stackexchange",
"id": 44636,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, rock-paper-scissors",
"url": null
} |
python, beginner, rock-paper-scissors
def game()
print("Rock = 0, paper = 1, scissors = 2")
while True:
user_input = input("Please enter your choice: ")
if user_input in {"0", "1", "2"}:
break
else:
print("Incorrect input!")
user_hand = int(user_input)
computer_hand = random.randrange(3)
print("Your choice ({0}) vs Computer's choice ({1})".format(HANDS[user_hand], HANDS[computer_hand])
print(determine_winner(user_hand, computer_hand))
if __name__ == '__main__':
game() | {
"domain": "codereview.stackexchange",
"id": 44636,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, rock-paper-scissors",
"url": null
} |
python, python-3.x, selenium
Title: Python script that reboots the router every 600 seconds
Question: This is a Python script I wrote to reboot the router every 600 seconds.
Why did I do it? Well, in case you don't know, I live in China, and I use VPNs to browse the international internet.
My ISP frequently interrupts my VPN connection, don't ask me why, they really have no better things to do. So I have to constantly reboot the router and reconnect VPN.
The router I am currently using takes a very short period of time to reboot, and rebooting doesn't disconnect the VPN, and I discovered somehow rebooting the router prevents my ISP from disconnecting my VPN, so I wrote this.
The script:
import time
from selenium import webdriver
from selenium.common.exceptions import ElementClickInterceptedException, ElementNotInteractableException, JavascriptException, MoveTargetOutOfBoundsException, NoAlertPresentException, NoSuchElementException, TimeoutException, UnexpectedAlertPresentException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC | {
"domain": "codereview.stackexchange",
"id": 44637,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, selenium",
"url": null
} |
python, python-3.x, selenium
Firefox = webdriver.Firefox()
wait = WebDriverWait(Firefox, 3)
def auto_reboot(n):
while True:
Firefox.get('http://192.168.0.1/login.html')
time.sleep(1)
while True:
try:
wait.until(EC.visibility_of_element_located(('id', "login-password"))).send_keys('U2VsZg1999')
break
except (TimeoutException, NoSuchElementException):
time.sleep(1)
while True:
try:
wait.until(EC.element_to_be_clickable(('id', "save"))).click()
break
except (ElementNotInteractableException, NoSuchElementException, TimeoutException):
time.sleep(1)
while True:
try:
wait.until(EC.element_to_be_clickable(('id', "system"))).click()
break
except (ElementNotInteractableException, NoSuchElementException, TimeoutException):
time.sleep(1)
while True:
try:
reboot = wait.until(EC.element_to_be_clickable(('id', "reboot")))
break
except (ElementNotInteractableException, NoSuchElementException, TimeoutException):
time.sleep(1)
while True:
try:
Firefox.execute_script("arguments[0].scrollIntoView();", reboot)
reboot.click()
break
except (ElementNotInteractableException, JavascriptException, MoveTargetOutOfBoundsException, TimeoutException):
time.sleep(1)
while True:
try:
Firefox.switch_to.alert
break
except NoAlertPresentException:
while True:
try:
reboot.click()
break
except ElementClickInterceptedException:
time.sleep(1)
time.sleep(1) | {
"domain": "codereview.stackexchange",
"id": 44637,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, selenium",
"url": null
} |
python, python-3.x, selenium
time.sleep(1)
time.sleep(1)
while True:
try:
Firefox.switch_to.alert.accept()
break
except UnexpectedAlertPresentException:
time.sleep(1)
time.sleep(n) | {
"domain": "codereview.stackexchange",
"id": 44637,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, selenium",
"url": null
} |
python, python-3.x, selenium
while True:
try:
auto_reboot(600)
except:
pass
I think my script is pretty self-explanatory, as you can see I use selenium to do exactly what I do manually using the GUI. Why don't I use telnet? Because my current router doesn't support it.
As you can see I use loads of try-except blocks inside while loops, why did I do that? Because if I don't, the script will eventually be stopped by exceptions, and I need the script to be running all the time. If I don't write the script like this, I can manually paste it into the console to run it and I never encountered exceptions, but if the script keeps running it always will be stopped by exceptions.
I have caught most exceptions and this version is much more stable than its predecessors, it can run hours without stopping, but the script still managed to throw exceptions, so I had to add another loop to catch everything.
I don't think my script can get any more efficient, but I think it can be more concise and elegant, how can I make it more concise and elegant?
Answer: Interesting script.
Let's talk about reliability.
You have a pair of concerns:
A reboot (attempt) must happen every ten minutes, no matter what.
Four .wait.until()'s will be tried, then retried at one-second intervals, until success, plus similar interactions.
Here's my perspective on those. Clearly there's more than one right answer.
Separate out item (1).
Turn the while / try mainline into
just a single auto_reboot() call
so it's a one-shot script that exits
within twenty seconds,
and have a "nanny" parent process spawn it.
Could be in python, but likely bash is simpler:
#! /bin/bash
while true
do
python reboot.py &
PID=$!
sleep 20
# Usually the child has succeeded and exited by this point.
jobs %% 2> /dev/null && (kill $PID; sleep 1; kill -9 $PID)
sleep 580
done
Very simple. | {
"domain": "codereview.stackexchange",
"id": 44637,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, selenium",
"url": null
} |
python, python-3.x, selenium
Very simple.
Now on to the second concern.
I am no Selenium expert, but I have to believe
that this requirement comes up all the time.
Apparently it has a RetryAnalyzer that
overrides onTestFailure, but you're
not within a test framework so let's look
outside the Selenium ecosystem.
You could write a while / try / do / sleep
wrapper for the repeated motif.
But tenacity
already offers wrappers for this common concern.
from tenacity import retry
@retry
def send_credentials():
wait.until(EC.visibility_of_element_located(('id', "login-password"))).send_keys('xxxx') # passwords never belong in the source code
@retry
def click(target: str):
wait.until(EC.element_to_be_clickable(('id', target))).click()
def auto_reboot(n):
Firefox.get('http://192.168.0.1/login.html')
time.sleep(1)
send_credentials()
click("save")
click("system")
...
It's clear you do not yet understand the occasional failure modes.
There's very little logging.
We don't announce we're about to attempt an interaction.
On success we don't report elapsed time, and
on failure we don't report how it failed.
Consider reporting interaction details to the console
or to a log file. The idea is to identify steps that
fail more often so you can better examine and understand them.
Also, elapsed time figures could help you to intelligently
choose a strategy for sleeping "just long enough" to win.
Consider adding import logging so you'll get timestamps
on each message.
This codebase achieves many of its design goals.
There is room to improve its
DRY
issues and lack of logging. | {
"domain": "codereview.stackexchange",
"id": 44637,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, selenium",
"url": null
} |
python
Title: Simple variation on a Trie for prefix search in a large list of words
Question: I've been looking into ways of performing a prefix search in a large list of words (for example, return all words that start with "as"). I noticed that a Trie is recommended often for this purpose.
I came up with a simple variation on the Trie-idea though. The premise of the idea is that in Python, key lookup in a dict is extremely fast. So how about simply storing all occurring prefixes of the entire word list as keys, and as values have the matching words in a list per prefix?
from collections import defaultdict
import nltk
# For the example I use the entire English word list of the nltk library, but this could be any list of words:
nltk.download('words')
english_words = [word.lower() for word in nltk.corpus.words.words()]
# Create prefix-dict for the words in english_words:
prefixes = defaultdict(list)
for word in english_words:
for i in range(1, len(word) + 1):
prefix = word[0:i]
prefixes[prefix].append(word)
# Find all words with the same prefix:
def find_words(user_input: str) -> list | str:
return prefixes.get(user_input, "no matches found")
I was worried that the prefix-dict would blow up to ridiculous dimensions (the theoretical maximum amount of keys would be 26 + 26^2 + 26^3 + 26^4....), but the word list used in the example containing 236736 words gave me a prefix-dict with a still-reasonable 758681 keys, and a not-terrible memory use of 131.7 MiB (according to tracemalloc).
My question is, is this a valid approach? What would be the downsides of this approach compared to a Trie as it is usually implemented, when used for a prefix search? And are there better/faster alternatives to this idea in Python? | {
"domain": "codereview.stackexchange",
"id": 44638,
"lm_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
Answer: To answer your first question, yes, it is a valid approach: it works, and the logic is fairly straightforward.
Looking at the code, you should encapsulate your logic into function, making it easily reusable, including for testing:
def build_prefix_dict(words):
'''
Create prefix dictionary for the given word list:
'''
prefixes = defaultdict(list)
for word in words:
for i in range(1, len(word) + 1):
prefix = word[0:i]
prefixes[prefix].append(word)
return prefixes
def find_words(prefix_dict, user_input: str) -> list:
'''
Find all words in a prefix dictionary starting with the given prefix
'''
return prefix_dict.get(user_input, []) | {
"domain": "codereview.stackexchange",
"id": 44638,
"lm_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
Note that I replaced your comments with proper docstrings and changed the default value for find_words to an empty list, making it a bit friendlier to work with down the line.
Now, how does it compare to other solutions?
Since you mentioned tries, I implemented a simple Trie class:
class Trie:
'''
A simple prefix tree (or trie)
'''
def __init__(self):
self._root = dict()
self._len = 0
def append(self, word: str):
'''
Append a word to the Trie
'''
if word in self:
return
current_node = self._root
for letter in word:
if letter not in current_node:
current_node[letter] = dict()
current_node = current_node[letter]
current_node[None] = None
self._len += 1
def __len__(self):
return self._len
def __contains__(self, word: str):
current_node = self._root
for letter in word:
if letter not in current_node:
return False
current_node = current_node[letter]
return None in current_node
def __iter__(self):
yield from self._iterate(self._root, '')
def _iterate(self, node, prefix):
if None in node:
yield prefix
for letter, child in node.items():
if child is None:
continue
yield from self._iterate(child, prefix + letter)
def find_words(self, prefix: str):
'''
Iterator for words starting with the given prefix
'''
current_node = self._root
for letter in prefix:
if letter not in current_node:
return
current_node = current_node[letter]
yield from self._iterate(current_node, prefix) | {
"domain": "codereview.stackexchange",
"id": 44638,
"lm_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
It uses dicts as nodes, with each key representing edges leaving the node, and None used as a word end marker. It allows to enumerate words quite easily, starting from the root or any prefix.
For testing purposes, I also wrapped your code into functions, which I recommend doing anyway:
Finally, a simple solution would be to use a flat list of word and find words with a prefix with list comprehension:
[word for word in words if word.startswith('<prefix>')]
Now, let's have a look at performance. I had text file with the French Scrabble dictionary on hand (411430 words, from 2 to 15 letters), so I used this for testing.
For benchmarking, I tried finding words starting with the empty string (411430 hits), starting with COU (1637 hits) and with COUAC (2 hits). I also looked at the time taken for building the object:
'' 'COU' 'COUAC' build
flat list 50ms 350ms 35ms 90ms
trie 500ms 2ms 0.001ms 1000ms
prefix dict 0.002ms 0.003ms 0.003ms 2500ms
As expected, the prefix dictionary takes constant time, no matter the size of the result, and is 4 to 5 orders of magnitudes faster than searching a flat list, and 5 orders of magnitudes faster than the trie in the worst case (and on par with best case).
Now, it takes significantly longer than a flat list to build. So looking at speed alone, the best option could be a flat list or a prefix dictionary, depending on how often it needs to be built vs how many searches are performed.
Memory wise, the dictionary I used weights 28MB as a flat list and 185MB as a trie or a prefix dictionary. A 6x memory usage vs a 10^5x speedup can definitely be an acceptable tradeoff for using a prefix trie, depending on your use case.
(I'll admit I'm surprised the trie isn't performing better, but it's basically many nested dictionaries, which imply a lot of overhead in Python.) | {
"domain": "codereview.stackexchange",
"id": 44638,
"lm_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
As for alternative approaches, you can look into a better implementation of the trie. From previous experience, I know for a fact that memory footprint and speed can be improved by several orders of magnitude by flattening the tree, at the cost of higher complexity and initial building time.
You can also look into directed acyclic word graph (DAWG), aka deterministic acyclic finite state automaton (DAFSA) for a more compact memory footprint and similar performance than a trie, at the cost of even more complexity. | {
"domain": "codereview.stackexchange",
"id": 44638,
"lm_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, performance, file-system, hashcode
Title: Collecting hashes of all files in a folder and its subfolders into a dictionary in Python
Question: What I am doing here is iterating through all the files in the parentFolder and its subfolders collecting all the hashes of all the files and putting them into a dictionary where the key is the path of the file and the hash is the key:
def createDicts(parentFolder):
hashesDict = {}
for folderName, subFolders, fileNames in os.walk(parentFolder):
for fileName in fileNames:
filePath = os.path.join(folderName, fileName)
tempHash = getHash(filePath)
hashesDict.update({filePath : tempHash})
return hashesDict
getHash() function:
def getHash (fileName):
with open(fileName,"rb") as f:
bytes = f.read() # Read file as bytes
readableHash = hashlib.md5(bytes).hexdigest()
return(readableHash)
Is there a way to make this faster?
Answer: In terms of code there's not much here in this snippet to go on to tell you how to make it faster as getHash isn't defined.
Style
PEP-8 is the standard style recommendation for Python. In it, it includes things like how many blank lines, how much indentation, recommendations for variable naming and casing.
There are linters (Flake8, Pylint and others) which check your code against PEP-8 and issue useful warnings. In your case there are several simple and obvious things.
Standard indentation for Python is 4 spaces. Likewise variable names and function names should be lower_snake_case. You also have a tonne of whitespace and the end of your lines.
You may also want to look at pathlib instead of os.path as the more modern way of handling paths.
Temporaries
Instead of
hashesDict.update({filePath : tempHash})
you can use
hashesDict[filePath] = tempHash | {
"domain": "codereview.stackexchange",
"id": 44639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, file-system, hashcode",
"url": null
} |
python, performance, file-system, hashcode
you can use
hashesDict[filePath] = tempHash
which avoids creating the temporary.
You also aren't using subFolders so you can replace that with _ to say this is irrelevant.
Dict comprehension
To speed it up, you may find that a dict comprehension helps:
def create_dicts(parent_folder):
return {os.path.join(folder_name, file_name): getHash(file_path)
for folder_name, _, file_names in os.walk(parent_folder)
for file_name in file_names}
but as I have no idea as to the expense of getHash that may be taking the time.
getHash
Your getHash function loads the entire file into memory at once allocating and clearing large chunks of memory constantly, particularly if you have any large files this will be killer. The cleaner way of doing this is loading memory in chunks.
def getHash(filename: str, *, buffer_size: int = 65536) -> str:
fhash = hashlib.md5()
with open(filename, 'rb') as in_file:
while chunk := in_file.read(buffer_size):
fhash.update(chunk)
return fhash.hexdigest()
N.B Choosing the right buffer_size can give some speedup, but will not be essential, md5 isn't necessarily the best or fastest hash, alternatives are available. | {
"domain": "codereview.stackexchange",
"id": 44639,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, file-system, hashcode",
"url": null
} |
python, generator, context-manager
Title: Is using a generator of context managers kosher?
Question: I know this is not necessarily a problem question but more of a style question. I understand that it doesn't have to be pretty for the most part.
In general, context managers are used for mutexing, acquiring resources, and many other things. The context managers usually yield the acquired resource or just provide wrapping functionality.
In general, generators are very capable us directing flow with conditionally yielding and custom iteration.
In my situation, I am writing a pipeline for an automatic probe station with a source and sink, but the probe station may or may not be able to probe multiple pins at the same time. That is, either iterating through each pair or being capable of connecting all pairs at the same time.
For a given pin group there is a list or pin pairs to be stressed. There is also a set of corresponding pins that are tested to determine pass or fail of the pin group given the stress level.
I have implemented a context manager for connecting to pins, yielding for testing, and then disconnecting on clean up.
Given a flag for the moment, I can control whether the loop connects all at once versus iterating through each. In the actual implementation the probe_context_generator will live in a concrete class that will offer only what is needed. The multi flag would only be offered if the concrete class can actually do either
Here is the code.
import contextlib
import random
import time
from itertools import product
from typing import ContextManager, Generator
# Business Logic
@contextlib.contextmanager
def probe_context(p): # Belongs to device specific probe station class
try:
print(f'Connecting pins to {p}')
time.sleep(0.1)
print(f'Connected')
yield p
finally:
print(f'Disconnecting {p}')
time.sleep(0.1)
print('Disconnected') | {
"domain": "codereview.stackexchange",
"id": 44640,
"lm_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, generator, context-manager",
"url": null
} |
python, generator, context-manager
def probe_context_generator(*pin_pairs, multi=False):
if multi:
yield probe_context(pin_pairs)
else:
for pin_pair in pin_pairs:
yield probe_context(pin_pair)
# Application Code
def probe_for_pulse(multi, p_level, pulse_pin_pairs):
for probe_pulse_pins_con in probe_context_generator(*pulse_pin_pairs, multi=multi):
with probe_pulse_pins_con as pulse_pins:
yield p_level, pulse_pins
def check_leakage(multi, leakage_pin_pairs):
leakage_results = []
for probe_leakage_pins_con in probe_context_generator(*leakage_pin_pairs, multi=multi):
with probe_leakage_pins_con as leakage_pin_pair:
print(f'Checking leakage on {leakage_pin_pair=}')
leakage_results.append(random.choice([True, False]))
return leakage_results
def ready_next_pulse_generator(p_levels, pin_groups: list[PinGroup], multi=False):
for pin_group in pin_groups:
print(f"\n!!!!! Pin Group {pin_group.group_num} !!!!!")
for p_level in p_levels:
# Measure Pass fail
leakage_results = check_leakage(multi, pin_group.leakage_pin_pairs)
print("broadcast leakage data to plots and data saving thread")
if not all(leakage_results):
print(f"Pin Group {pin_group.group_num} failed {p_level}")
break
yield from probe_for_pulse(multi, p_level, pin_group.pulse_pin_pairs)
print(f"Pin Group {pin_group.group_num} passed {p_level}")
PINS = ["A1", "B1", "C1"]
pulse_levels = [125, 250, 500]
class PinGroup:
pulse_pin_pairs = [
(force, sense) for force, sense in product(PINS, PINS) if force != sense
]
leakage_pin_pairs = [("Leakage force pin", "Leakage sense pin")]
def __init__(self, group_num):
self.group_num = group_num | {
"domain": "codereview.stackexchange",
"id": 44640,
"lm_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, generator, context-manager",
"url": null
} |
python, generator, context-manager
def __init__(self, group_num):
self.group_num = group_num
print("##### Probe Single #####")
for pulse_level, connected_pin in ready_next_pulse_generator(pulse_levels, [PinGroup(i) for i in range(5)]):
print(f'\tarm scope for {connected_pin}')
time.sleep(0.1)
print(f"\tpulse {connected_pin=}, {pulse_level=}")
time.sleep(0.1)
print(f"\tread data for {connected_pin}")
time.sleep(0.1)
print("\n" * 2)
print("##### Probe Multi #####")
for pulse_level, connected_pins in ready_next_pulse_generator(pulse_levels, [PinGroup(i) for i in range(5)], multi=True):
print(f'\tarm scope for {connected_pins}')
time.sleep(0.1)
print(f"\tpulse {connected_pins=}, {pulse_level=}")
time.sleep(0.1)
print(f"\tread data for {connected_pins}")
time.sleep(0.1)
My main question is, I guess, is the probing_context sufficient need for utilizing the contextmanager functionality? Would making the arming of the scope and reading the data also contextmanager increase the chances of this code being used correctly, or does it seem like I'm overusing a cool thing? Subjective, I know. But I haven't seen a lot of things like this. The probing_context, for a robotic probe station, will handle path planning and doing the actual moving.
Answer: You asked essentially, "is this weird?" or... "am I doing this right?"
You are doing it right.
That looks like very nice idiomatic python code to me.
The pattern is:
connect
stimulate the SUT and record measurements
disconnect
with the requirement that disconnect() must
happen no matter what.
A perfect match for a context manager.
Are you overusing a cool thing?
No, I don't believe so.
Would making the arming of the scope and reading the data also a contextmanager increase the chances of this code being used correctly | {
"domain": "codereview.stackexchange",
"id": 44640,
"lm_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, generator, context-manager",
"url": null
} |
python, generator, context-manager
I didn't exactly follow that.
It appears to me that step (1) arming is what the caller wants
and you've packaged that up nicely,
and then step(3) disconnect is the invariant we're
trying to preserve, even in the face of misbehaving user code.
If the step (2) user code that reads data has its own
concerns, then sure, it might use a context manager.
But the OP doesn't show me anything that seems to motivate that.
increase the chances of this code being used correctly
I really like the way you're thinking.
Arrange for the Right way to be the Path of Least Resistance,
and client code will tend to do what you were hoping for.
Along those lines, take some care to export only a limited
number of public entry points.
In python we're all grownups and it's never impossible to
reach in for some _private() function, but you can offer
strong hints which will be respected during code reviews.
Take care to write a couple of """docstrings""" that
span a few paragraphs, so callers will see how you
expect them to call into the Public API of your library.
This is very clear, solid code that achieves its design goals.
I would be happy to delegate or accept maintenance tasks
on this codebase. | {
"domain": "codereview.stackexchange",
"id": 44640,
"lm_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, generator, context-manager",
"url": null
} |
c++, multithreading, locking
Title: Least Recently Used Cache with TTL
Question: I found this problem in a book and found it interesting. wrote this class to implement a Least Recently Used Cache with TTL.
Goal -
LRU cache with TTL
Multithreaded.
Functions: Get(key), Put(key,value), average()
Runtime of get and put can be compromised (but still as fast as possible) for fast run time of avg()
Any inputs on correctness of the code, locking correctness, potential improvement in finer locking would be really helpful. Thank you.
#include <iostream>
#include <vector>
#include <unordered_map>
#include <list>
#include <map>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <atomic>
const int TTLSeconds = 20;
/*Node that holds the key, value and the expiry time of a key, value pair*/
struct Node
{
int key;
int value;
time_t expiryTime;
Node(int key, int val, time_t expiryTime = time(nullptr) + TTLSeconds) : key(key), value(val), expiryTime(expiryTime) {}
};
struct IteratorsContainer
{
std::list<Node>::iterator cacheIterator;
std::list<int>::iterator keyIteratorInTimeBucket;
}; | {
"domain": "codereview.stackexchange",
"id": 44641,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, locking",
"url": null
} |
c++, multithreading, locking
class LRUCache
{
private:
int capacity;
/* MRU to LRU. Holds the nodes */
std::list<Node> cache;
/* TimeBuckets. <expiryTime, list<keys that expire at expiryTime> */
std::map<time_t, std::list<int>> timeBuckets;
/* Holds iterator to cache and timeBuckets for each key
Could have used pair<list<Node>::iterator, list<int>::iterator> but
created a struct for better readability
*/
std::unordered_map<int, IteratorsContainer> keyIteratorsMap;
/* To calculate average */
std::atomic<double> sum;
std::atomic_int count;
std::mutex mtx;
/* cleanUpThread wakes up every n seconds and removes expired nodes */
std::thread cleanUpThread;
std::atomic_bool stopCleanUpThread;
//Evict expired nodes
void evictExpired();
//Updates cache and moves entry to cache[0]
void updateCache(int key, int value);
//Evict the least recently used. cache.back()
void evictLRU();
public:
LRUCache(int capacity = 3) : capacity(capacity), sum(0.0), count(0)
{
stopCleanUpThread = false;
cleanUpThread = std::thread(&LRUCache::evictExpired, this);
}
~LRUCache()
{
stopCleanUpThread = true;
if (cleanUpThread.joinable())
{
cleanUpThread.join();
}
}
void stopCleanUp();
int get(int key);
void put(int key, int value);
void printAverage();
void callAverageEveryNSeconds();
}; | {
"domain": "codereview.stackexchange",
"id": 44641,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, locking",
"url": null
} |
c++, multithreading, locking
void LRUCache::evictExpired()
{
while (!stopCleanUpThread)
{
//Wake up and check every 1.5 seconds
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
{
std::lock_guard<std::mutex> lk(mtx);
auto it = timeBuckets.begin();
//worst case run time - O(nlogn)
while (it != timeBuckets.end())
{
auto currentTime = time(nullptr);
if (it->first > currentTime)
{
// entries beyond these haven't expired
break;
}
//Evict expired keys
for (int key : it->second)
{
std::cout << "Key " << key << " expired. Evicting\n";
IteratorsContainer temp = keyIteratorsMap[key];
int val = temp.cacheIterator->value;
cache.erase(temp.cacheIterator);
sum = sum - val;
--count;
}
auto current = it;
++it;
timeBuckets.erase(current);
}
}
}
}
void LRUCache::stopCleanUp()
{
stopCleanUpThread = true;
}
void LRUCache::updateCache(int key, int value)
{
IteratorsContainer temp = keyIteratorsMap[key];
int currentValue = temp.cacheIterator->value;
auto currentExpiryTime = temp.cacheIterator->expiryTime;
auto newExpiryTime = time(nullptr) + TTLSeconds;
cache.erase(temp.cacheIterator);
cache.push_front(Node(key, value, newExpiryTime));
timeBuckets[currentExpiryTime].erase(temp.keyIteratorInTimeBucket); //O(logn)
if (timeBuckets[currentExpiryTime].empty())
{
timeBuckets.erase(currentExpiryTime);
}
timeBuckets[newExpiryTime].push_front(key); | {
"domain": "codereview.stackexchange",
"id": 44641,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, locking",
"url": null
} |
c++, multithreading, locking
keyIteratorsMap[key] = {cache.begin(), timeBuckets[newExpiryTime].begin()};
sum = sum - currentValue;
sum = sum + value;
}
int LRUCache::get(int key) // O(logn)
{
if ( keyIteratorsMap.find(key) == keyIteratorsMap.end())
{
return -1;
}
IteratorsContainer temp = keyIteratorsMap[key];
auto currentTime = time(nullptr);
auto expiryTime = temp.cacheIterator->expiryTime;
int value = temp.cacheIterator->value;
if (expiryTime < currentTime)
{
return -1;
}
std::lock_guard<std::mutex> lk(mtx);
updateCache(key, value); //O(logn)
return value;
}
void LRUCache::evictLRU()
{
Node evictionCandidate = cache.back();
IteratorsContainer temp = keyIteratorsMap[evictionCandidate.key];
timeBuckets[evictionCandidate.expiryTime].erase(temp.keyIteratorInTimeBucket);
if (timeBuckets[evictionCandidate.expiryTime].empty())
{
timeBuckets.erase(evictionCandidate.expiryTime);
}
cache.pop_back();
keyIteratorsMap.erase(evictionCandidate.key);
sum = sum - evictionCandidate.value;
--count;
std::cout << "Capacity reached. Key " << evictionCandidate.key << std::endl;
}
void LRUCache::put(int key, int value) // O(logn)
{
/* For Testing */
int sleepTime = rand() % 10000;
std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime));
/* Test code ends */
std::lock_guard<std::mutex> lk(mtx);
if (keyIteratorsMap.find(key) != keyIteratorsMap.end())
{
std::cout << "Key exists. Update cache\n";
updateCache(key, value); //O(logn)
return;
}
if ((int)keyIteratorsMap.size() == capacity)
{
evictLRU(); //O(logn)
}
auto expiryTime = time(nullptr) + TTLSeconds;
cache.push_front(Node(key, value, expiryTime));
timeBuckets[expiryTime].push_front(key);
keyIteratorsMap[key] = {cache.begin(), timeBuckets[expiryTime].begin()}; | {
"domain": "codereview.stackexchange",
"id": 44641,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, locking",
"url": null
} |
c++, multithreading, locking
sum = sum + value;
++count;
std::cout << "Key " << key << " inserted. Value = " << value << " . Expiry = " << expiryTime << std::endl;
}
void LRUCache::printAverage() //O(1)
{
if (count == 0)
{
std::cout << "Averge = " << 0.0 << std::endl;
return;
}
std::cout << "Averge = " << sum/count << std::endl;
}
//Test function
void LRUCache::callAverageEveryNSeconds()
{
int n = 0;
int interval = 1500;
while (n < 20)
{
std::this_thread::sleep_for(std::chrono::milliseconds(interval));
printAverage();
++n;
}
}
int main()
{
const int CACHE_SIZE = 5;
const int MAX_THREADS = 6;
LRUCache cache(CACHE_SIZE);
//std::vector<std::thread> threadPool(6);
std::thread threadPool[MAX_THREADS];
for (int i = 0; i < MAX_THREADS; ++i)
{
int key = rand() % 100;
int val = 100 + rand() % 100;
threadPool[i] = std::thread(&LRUCache::put, &cache, key, val);
}
std::thread callAverage(&LRUCache::callAverageEveryNSeconds, &cache);
std::this_thread::sleep_for(std::chrono::seconds(25));
for (int i = 0; i < MAX_THREADS; ++i)
{
threadPool[i].join();
}
callAverage.join();
return 0;
}```
Answer: Move everything into class LRUCache
The constant TTLSeconds and the structs Node and IteratorsContainer are all just implementation details of LRUCache. Move everything into the latter, like so:
class LRUCache
{
const int TTLSeconds = 20;
struct Node {
...
};
struct IteratorsContainer {
...
}
int capacity;
...
}; | {
"domain": "codereview.stackexchange",
"id": 44641,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, locking",
"url": null
} |
c++, multithreading, locking
struct IteratorsContainer {
...
}
int capacity;
...
};
This avoids polluting the global namespace, which is especially important for things with a generic name like Node.
Use std::chrono for everything related to time
It's weird to see you use std::chrono in some parts your code, but for the expiry times you use time_t and int. Use std::chrono for all things related to time. Note however that std::chrono supports multiple clocks, and you probably want to use std::chrono::steady_clock to measure time. This is how it can be used:
using clock = std::chrono::steady_clock;
using duration = clock::duration;
using time_point = clock::time_point;
const duration TTL = std::chrono::seconds(20);
struct Node {
int key;
int value;
time_point expiryTime;
Node(int key, int value, time_point expiryTime = clock::now()): ... {}
};
std::map<time_point, std::list<int>> timeBuckets;
Make it a template
Your LRUCache uses ints for keys and values. But what if you want to store something else? The solution is to make LRUCache a template, with the key and value types being template parameters:
template <class Key, class T>
class LRUCache {
struct Node {
Key key;
T value;
...
};
struct IteratorsContainer {
std::list<Node>::iterator cacheIterator;
std::list<Key>::iterator keyIteratorInTimeBucket;
};
std::map<time_point, std::list<Key>> timeBUckets;
std::unordered_map<Key, IteratorsContainer> keyIteratorsMap;
...
public:
T get(Key key);
void put(Key key, T value);
...
}; | {
"domain": "codereview.stackexchange",
"id": 44641,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, locking",
"url": null
} |
c++, multithreading, locking
Remove code related to averages
Your LRUCache not only implements a LRU cache, but also has some functionality to calculate the average of the elements in the cache. Keep things simple and reduce the number of responsibilities of this class. By adding features like this, you actually make the code less generic and less useful. Ideally, LRUCache should just expose enough functionality that an external function can iterate over all the items in the cache and calculate something.
Evict expired events without using a thread
It should be possible to have an LRU cache that doesn't need a thread to clean up expired items. Instead, evict as necessary during put() and get(). In put(), you already do this. In get(), you check the expiry time of the node you are looking for, but you could make it so that if you find an expired item, you delete it immediately.
The thread doesn't make things more efficient. Either the interval it sleeps for is too large for the rate at which put() is called, in which case put() will do all the eviction work anyway, or it is too short and wastes CPU cycles for nothing, and even if the interval is perfectly balanced with regards to the frequency of put() and get() calls, the latter two functions still can't rely on the thread to have kicked in at the right time.
Without a thread you also don't have to deal with thread cleanup, and avoid having to wait 0.75 seconds on average when destroying an instance of LRUCache.
Use std::size_t for count, capacity and indices
An int might not be large enough to represent the maximum size a container can be. Furthermore, specifying a negative capacity leads to disaster. The right type for storing counts, sizes and indices is std::size_t.
Don't use a special value to indicate that an item was not in the cache | {
"domain": "codereview.stackexchange",
"id": 44641,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, locking",
"url": null
} |
c++, multithreading, locking
Don't use a special value to indicate that an item was not in the cache
When your get() doesn't find an item or if it is already expired, it returns -1. But -1 is a valid int. What if I did a put(..., -1) before? The proper way to solve this is to use a separate value to indicate whether the item was found or not. For example (very simplified):
bool LRUCache::get(int key, int& value) {
if (/* key in map and not expired */) {
value = temp.cacheIterator->value;
return true;
} else {
return false;
}
} | {
"domain": "codereview.stackexchange",
"id": 44641,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, locking",
"url": null
} |
c++, multithreading, locking
If you can use C++17 or later, consider returning a std::optional type.
Missing locking in get()
In get(), you only take the lock right before updating the cache, but you don't use it for the part where you look up the value. Since another thread could be modifying the cache at the same time, bad things can happen. Just move the lock guard to the top of the function.
Simplifying cache management
There is a lot going on in your cache. There's lists and maps everywhere. Consider simplifying it. You should need only two things:
An unordered map of keys to values and their expiry times.
A container with the keys sorted on expiry time.
To insert an item, add it to the unordered map first, then add the key of the item you just inserted to the sorted container of expiry times. To evict the least recently used item, you just need to pop the first key from the sorted container of expiry times, and use that key to erase the corresponding element from the unordered map.
There are several ways to have a sorted container. A std::map is one way. However, as you probably noticed, you have an issue if you want to insert two items with the same timestamp. You can use std::multimap in that case, so you don't need to use a std::list yourself. | {
"domain": "codereview.stackexchange",
"id": 44641,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, locking",
"url": null
} |
programming-challenge, hash-map, rust
Title: Find the longest palindromic subsequence - Using a hashmap in Rust
Question: This is a leetcode question which I wanted to solve using Rust as I'm learning Rust at the moment. I would appreciate some feedback on how to write it idiomatically.
Link to the question: https://leetcode.com/problems/longest-palindromic-subsequence/
Things that I'm particularly unsure about:
Should I be using String or &str?
Am I using the hashmap correctly? In particular, am I handling the Option output from the get method in an idiomatic way?
My solution:
use std::cmp::max;
use std::collections::HashMap;
pub fn longest_palindrome_subseq(s: String) -> i32 {
fn solve(s: String, cache: &mut HashMap<String, i32> ) -> i32 {
if cache.contains_key(&s) {
return *cache.get(&s).unwrap();
}
let length = s.len();
if length == 0 {
return 0;
}
if length == 1 {
return 1;
}
let first_letter = &s[..1];
let last_letter = &s[length-1..];
let solution: i32;
if first_letter == last_letter {
solution = 2 + solve(s[1..s.len()-1].to_string(), cache);
} else {
solution = max(
solve(s[1..s.len()].to_string(), cache),
solve(s[..s.len()-1].to_string(), cache),
);
}
cache.insert(s, solution);
solution
}
let mut cache: HashMap<String, i32> = HashMap::new();
solve(s, &mut cache)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_empty() {
let actual = longest_palindrome_subseq("".to_string());
assert_eq!(actual, 0);
}
#[test]
fn test_single() {
let actual = longest_palindrome_subseq("a".to_string());
assert_eq!(actual, 1);
}
#[test]
fn test_double_not_same() {
let actual = longest_palindrome_subseq("ab".to_string());
assert_eq!(actual, 1);
} | {
"domain": "codereview.stackexchange",
"id": 44642,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, hash-map, rust",
"url": null
} |
programming-challenge, hash-map, rust
assert_eq!(actual, 1);
}
#[test]
fn test_double_same() {
let actual = longest_palindrome_subseq("aa".to_string());
assert_eq!(actual, 2);
}
#[test]
fn test_triple() {
let actual = longest_palindrome_subseq("aba".to_string());
assert_eq!(actual, 3);
}
#[test]
fn test_1() {
let actual = longest_palindrome_subseq("bbbab".to_string());
assert_eq!(actual, 4);
}
#[test]
fn test_2() {
let actual = longest_palindrome_subseq("cbbd".to_string());
assert_eq!(actual, 2);
}
}
Answer: Good questions!
Yes, You Should be Using &str
In this algorithm, all of your hash-map keys are substrings of the same input string, which will outlive the hash map. It is much more efficient to copy and work with slices of the input string than it is to allocate new String objects and make a deep copy of each substring.
Doing it this way means you will need to create two lifetimes: one for the HashMap and a longer one for the substring slices, including the keys of the HashMap, which may not outlive its keys. The substrings similarly may not outlive the string they index. It’s common practice to give these lifetimes names like 'a and 'b, but you could name them anything, such as:
fn solve<'substrings, 'map>(
s: &'substrings str,
cache: &'map mut HashMap<&'substrings str, i32>,
) -> i32
You could also make the constraint that the map keys outlive the map that contains them explicit, although this is not necessary for the code to compile:
fn solve<'map, 'substrings: 'map>(
s: &'substrings str,
cache: &'map mut HashMap<&'substrings str, i32>,
) -> i32 | {
"domain": "codereview.stackexchange",
"id": 44642,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, hash-map, rust",
"url": null
} |
programming-challenge, hash-map, rust
This is initially called as solve(s, &mut cache) from longest_palindrome_subseq(s: &str). The local variable cache expires when the function returns, and it’s declared to have a type of Hashmap<&str, i32>, so the lifetime 'substrings is inferred to be the lifetime of its keys, which is at least as long as the lifetime of cache and no longer than the lifetime of s, and everything works. (If the compiler were not able to infer all this, you could also give the lifetime of the input slice a name, e.g. s: &'input str, and explicitly declare the lifetime of the keys as cache: HashMap<&'input str, i32>. Again, that complexity is not necessary here.)
This necessitates a few syntactic changes to the body and tests (see below) to match the new type, such as removing every call to .to_string(). That’s a concrete sign of the improved efficiency: you’re removing expensive operations and replacing them with cheap, constant-time ones.
Prefer Pattern Matching on the Output
Again, great question, and exactly what I would have addressed.
Rather than make two calls to the HashMap, and using an unwrap that theoretically shouldn’t fail, you would be better off using a pattern guard, such as:
if let Some(&result) = cache.get(s) {
return result;
} | {
"domain": "codereview.stackexchange",
"id": 44642,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, hash-map, rust",
"url": null
} |
programming-challenge, hash-map, rust
This is not only more succinct, it eliminates all the branches of control flow that would be logic errors (but which the compiler, or a maintainer, cannot prove are impossible).
I would similarly suggest making solution a static single assignment, rather than declaring it uninitialized and then trying to make sure it is assigned exactly once in every possible branch before being used. Initializing it to an if or match expression makes several tricky types of bug impossible to write (although at least the compiler should be able to catch them).
You could also combine the tests for a usize value of 0 or 1 into a single comparison.
In the Real World, Remember that Not All Strings are ASCII
Part of the LeetCode problem statement is that the string contains only “English letters,” encoded as a single byte in UTF-8. (In the future, please copy all relevant requirements into the post, rather than giving an external link that could change or go dead.)
If, however, you ever passed this function a string containing a non-ASCII character, the recursive calls would create a substring that did not start and end on a valid UTF-8 boundary. That would crash the program at runtime. If you don’t want that to happen, you might want to test the input for validity, to return an error Result or fail fast and gracefully.
if s.bytes().any(|b| {b > 127}) {
unimplemented!("Input must be ASCII!");
} | {
"domain": "codereview.stackexchange",
"id": 44642,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, hash-map, rust",
"url": null
} |
programming-challenge, hash-map, rust
A fix might be to replace every expression that indexes a substring by bytes with one that iterates over its chars. For example. s.len() would become s.chars().count(), and returning a substring with the first or last char removed might use str::split and str::rsplit, respectively. In fact, even this might not be correct in the general case: you might want to check graphemes instead of Unicode codepoints for canonical equivalence. This, however, goes beyond what is provided in the Rust standard library.
Putting it all Together
Compare this version and see if it works for you:
use std::cmp::max;
use std::collections::HashMap;
pub fn longest_palindrome_subseq(s: &str) -> i32 {
fn solve<'map, 'substrings: 'map>(
s: &'substrings str,
cache: &'map mut HashMap<&'substrings str, i32>,
) -> i32 {
if let Some(&result) = cache.get(s) {
return result;
}
let length = s.len();
if length < 2 {
return length as i32;
}
// We have already checked that the length is greater than 1.
let first_letter = s.chars().next().unwrap();
let last_letter = s.chars().rev().next().unwrap();
let solution =
if first_letter == last_letter {
2 + solve(&s[1..s.len()-1], cache)
} else {
max(
solve(&s[1..s.len()], cache),
solve(&s[..s.len()-1], cache)
)
};
cache.insert(s, solution);
solution
}
if s.bytes().any(|b| {b > 127}) {
unimplemented!("Input must be ASCII!");
}
let mut cache: HashMap<&str, i32> = HashMap::new();
solve(s, &mut cache)
} | {
"domain": "codereview.stackexchange",
"id": 44642,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, hash-map, rust",
"url": null
} |
programming-challenge, hash-map, rust
pub fn main() {
assert_eq!(longest_palindrome_subseq(""), 0);
assert_eq!(longest_palindrome_subseq("a"), 1);
assert_eq!(longest_palindrome_subseq("ab"), 1);
assert_eq!(longest_palindrome_subseq("aa"), 2);
assert_eq!(longest_palindrome_subseq("aba"), 3);
assert_eq!(longest_palindrome_subseq("bbbab"), 4);
assert_eq!(longest_palindrome_subseq("cbbd"), 2);
} | {
"domain": "codereview.stackexchange",
"id": 44642,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, hash-map, rust",
"url": null
} |
php, classes, pagination, php7
Title: PHP Pagination class (Clase para paginar resultados)
Question: This is my first question in Code Review. I apologize in advance for using Spanish (my native language). I thought there was a spanish version of Code Review.
This class is meant for pagination. It produces the desired results and I forced errors to check and everything seems ok to me.
Here is the code:
(Edited to suit CR language policy)
/*
* Usage:
*
* $query = "select id, razon_social, nombre_comercial, esta_habilitado, fecha_alta from clientes";
* $headers = array("ID", "R. Social", "N. Comercial", "Habilitado?", "Fecha Alta");
* require("Pagination.php");
* $pagination = new Pagination($query, 10, $_GET['page'] ?? 1, 1, $headers);
* echo "<br>Results: " . $pagination->get_total_results() . " (pages: " . $pagination->get_total_pages().")";
* echo "<br>" . $pagination->get_results();
* echo "<br>" . $pagination->get_navigator();
*
*/
class Pagination {
/** Data source can be either a MySQL query or a multidimensional array
* this variable is overwritten after validation so it holds the selected data
* overwrite occurs around lines 78 and 102
*/
private $data_source = null;
/** amount of results */
private $total_results = 0;
/** total pages */
private $total_pages = 0;
/** results per page */
private $results_per_page = 10;
/** URL for navigator */
private $url = null;
/** HTML navigator */
private $navigator = null;
/** resulting HTML output */
private $html_output = null;
/** page number */
private $page = 1;
/** output format: 1:table (default), 2:multidimensional array */
private $format = 1;
/** column headers (depends on $this->format) */
private $headers = array(); | {
"domain": "codereview.stackexchange",
"id": 44643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, classes, pagination, php7",
"url": null
} |
php, classes, pagination, php7
/**
*
* @param string|array $data_source MySQL query o multidimensional array
* @param number $results_per_page Number of results per page
* @param number $page Page number to show
* @param number $format 1: HTML table (default), 2: multidimensional array
* @param array $headers If $format==1 array with column headers. If the amount doesn't equal field count it will be ignored
* @throws Exception
*/
function __construct($data_source=null, $results_per_page=10, $page=1, $format=1, $headers=array()) {
global $mysqli;
if (!filter_var($results_per_page, FILTER_VALIDATE_INT) or ($results_per_page < 1)) {
throw new exception("Incorrect number of results per page");
}
$this->results_per_page = $results_per_page;
if (!filter_var($page, FILTER_VALIDATE_INT) or ($page < 1)) {
throw new Exception("Incorrect page number");
}
$this->page = $page;
if (($format != 1) and ($format != 2)) $this->format = 1;
if (!is_array($headers)) {
throw new Exception("Invalid headers");
}
if (!isset($data_source) or
(is_string($data_source) and (strlen($data_source) == 0)) or
(is_array($data_source) and (count($data_source) < 1))) {
throw new exception("Incorrect data source");
} | {
"domain": "codereview.stackexchange",
"id": 44643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, classes, pagination, php7",
"url": null
} |
php, classes, pagination, php7
if (is_array($data_source)) { // not implemented yet
if (!es_multidimensional($data_source)) {
throw new exception("Data source isn't a multidimensional array");
} else {
$this->total_results = count($data_source);
$this->data_source = $data_source;
$this->total_pages = ceil($this->total_results / $results_per_page);
}
} else {
try {
$mysqli->query($data_source);
} catch (Exception $e) {
throw new Exception("Error on data source");
}
$this->total_results = $mysqli->affected_rows;
if ($this->total_results < 1) throw new Exception("No results");
$this->total_pages = ceil($this->total_results / $results_per_page);
$offset = ($page - 1) * $this->results_per_page;
if ($page == 1) $data_source .= " limit 0, " . $this->results_per_page;
elseif (($page > 1) and ($page <= $this->total_pages)) $data_source .= " limit " . $offset . ", " . $this->results_per_page;
else {
throw new Exception("Unexpected error"); // don't figure out how to set this error message
}
try {
$resultados = $mysqli->query($data_source);
} catch (Exception $e) {
throw new Exception("Error on data source");
}
$this->data_source = $resultados->fetch_all(MYSQLI_ASSOC);
if (($this->format == 1) and isset($headers) and (count($headers) != $mysqli->field_count)) {
$this->headers = array();
} else {
$this->headers = $headers;
}
unset($offset);
unset($resultados);
}
}
function get_total_results() {
return $this->total_results;
}
function get_total_pages() {
return $this->total_pages;
} | {
"domain": "codereview.stackexchange",
"id": 44643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, classes, pagination, php7",
"url": null
} |
php, classes, pagination, php7
function get_total_pages() {
return $this->total_pages;
}
function get_results() {
/* in a nearby future this method will be available for several formats using templates
* for now this is more than enough
*/
if ($this->format == 1) { // tabla
$this->html_output = "\n".'<div class="table">';
if (isset($this->headers)) {
$this->html_output .= "\n" . '<div class="table-header">';
foreach($this->headers as $header) {
$this->html_output .= "\n" . '<div class="table-cell-header">'.$header.'</div>';
}
$this->html_output .= "\n" . '</div>';
}
$this->html_output .= "\n" . '<div class="table-body">';
foreach($this->data_source as $data) {
$this->html_output .= "\n" . '<div class="table-row">';
foreach($data as $value) {
$this->html_output .= "\n" . '<div class="table-row-cell">' . $value .'</div>';
}
$this->html_output .= "\n" . '</div>';
}
$this->html_output .= "\n" . '</div>';
$this->html_output .= "\n" . '</div>' . "\n";
return $this->html_output;
}
return $this->data_source; // array
}
function get_navigator() {
// prepare url for navigator
$this->url = ROOT_WEB . substr($_SERVER['PHP_SELF'], 1);
if (strlen($_SERVER['QUERY_STRING']) == 0) { $this->url .= "?page="; }
else {
$this->url .= '?';
foreach($_GET as $variable => $value) {
if ($variable != "page") $this->url .= $variable . "=" . $value . "&";
}
$this->url .= "page=";
}
// prepare navigator
if ($this->total_pages > 1) {
$previous = null;
$following = null;
$this->navigator = "<div id=\"paginator\">%1"; | {
"domain": "codereview.stackexchange",
"id": 44643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, classes, pagination, php7",
"url": null
} |
php, classes, pagination, php7
for ($count = 1; $count <= $this->total_pages; $count++) {
if ($this->page != $count) $this->navigator .= "<a href='" . $this->url. "$count'>$count</a>";
else {
$this->navigator .= "<a href='#'>$count</a>";
if ($this->page != 1) {
$previous = '<a href="' . $this->url.($count-1).'"><</a>';
$this->navigator = str_replace("%1", $previous, $this->navigator);
} else {
$this->navigator = str_replace("%1", "", $this->navigator);
}
if ($this->page < $this->total_pages) {
$following = '<a href="' . $this->url.($count+1).'">></a>';
}
}
}
$this->navigator .= $following;
$this->navigator .= "</div>";
}
return $this->navigator;
}
}
Are there any suggestions on improving my code?
Answer: Yes. So many things must be improved here that I don't even know where to start.
The class structure
Probably the most important issue of all. Strictly speaking, it is not a class. It's rather a collection of different functions that were accidentally put into a class.
a class should be doing exactly one thing. Yours does everything, from querying the database to outputting HTML.
a class should be using properties on purpose, not just a fancy way to call a variable.
a class should never ever use a global variable. Even for functions it's frowned upon, but for classes it's completely forbidden. A class should contain everything it needs, and never use some variable out of nowhere.
a class should be universal. It shouldn't be rewritten every time it is used on another site or when design is changed.
Database pagination.
There are two major flaws with database pagination: | {
"domain": "codereview.stackexchange",
"id": 44643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, classes, pagination, php7",
"url": null
} |
php, classes, pagination, php7
Database pagination.
There are two major flaws with database pagination:
Your class doesn't support prepared statements, which means your SQL is prone to SQL injection.
You should never ever select all rows to count them. A separate query using SELECT count(*) FROM ... MUST be used instead.
Suggestions
It seems your class is not much about pagination but rather about outputting HTML tables. So you got to make it so. Running SQL queries looks absolutely alien here. You can always get an array from SQL query using some other code, and pass it as array already. It will make your code more specific and on purpose.
My advise would be to put classes away for a while, and concentrate on learning basic programming principles such as SQL, security, code structure, separation of concerns.
I would suggest to make just a set of functions each doing its distinct job:
a function that runs SQL query and returns an array. But you must remember that such a function MUST support using parameters in SQL. Here is one I wrote and recommend.
a function that accepts an array and outputs an html table from array
a function that accepts the total number of rows, the page size, the current page number - and displays navigation
Some pseudocode:
// some input validation
$current_page = ...
$offset = ...
$num_records = query(...);
$page_records = query(... $offset, $page_size);
$html_table = html_table($page_records);
$navigation = html_pagination_navigation($num_records, $page_size, $current_page);
After some learning, you may take a look at this class, that indeed does some pagination, in the sense of database pagination.
Other improvements
It's a very good thing that you are using exceptions. But you must use them properly | {
"domain": "codereview.stackexchange",
"id": 44643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, classes, pagination, php7",
"url": null
} |
php, classes, pagination, php7
use appropriate exception type. For example, when input argument is invalid, PHP has an exception exactly for this occasion: InvalidArgumentException
never ever use exceptions to hide the actual error message. Your "Error on data source" is a really bad idea. Instead of informative and helpful error message from mysql, you have just useless text that that doesn't tell you how to fix the error.
let PHP to do some input validation for you: add type hinting for function arguments. If you write a function definition like this function navigation(int $total_pages) and PHP will do that FILTER_VALIDATE_INT (or is_array() etc.) validation for you and throw appropriate exception.
when table headers aren't provided, you can use array_keys($data_source[0]) | {
"domain": "codereview.stackexchange",
"id": 44643,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, classes, pagination, php7",
"url": null
} |
c++, object-oriented, tic-tac-toe
Title: Tic Tac Toe console game in c++
Question: For learning purposes i wrote a Tic Tac Toe game in object oriented manner.
I have question about storing players in game class - Players(cpu and human) are derived from virtual class players and stored in vector as unique pointers to common class. Is there more elegant way to achieve this?
Also, feel free to point out things i could improve or i do in wrong way.
For convenience purposes here is repo with whole project: repo
main.cpp
#include "TicTacToe.h"
#include <iostream>
int main()
{
int playersAmount;
std::cout << "0 - two CPU players" << std::endl
<< "1 - play with CPU" << std::endl
<< "2 - two players" << std::endl;
std::cin >> playersAmount;
TicTacToe::intro();
do {
TicTacToe game(playersAmount);
game.clearConsole();
game.printBoard();
while (game.isRunning()) {
game.step();
};
char input;
std::cout << "Play again?(y/n)";
std::cin >> input;
if (input != 'y') {
break;
}
} while (true);
}
TicTacToe.h
#pragma once
#include "Board.h"
#include "Players.h"
#include <array>
#include <memory>
#include <string>
#include <vector>
class TicTacToe {
public:
TicTacToe(const int numberOfHumanPlayers);
static void intro();
static std::string getInputFromConsole();
static void clearConsole();
void printBoard() const;
void step();
bool isRunning() const;
void terminate();
private:
bool m_running { true };
int m_currentPlayer { 0 };
std::vector<std::unique_ptr<Player>> m_players;
Board m_board;
void nextPlayer();
char returnPlayerSign(const int player) const;
}; | {
"domain": "codereview.stackexchange",
"id": 44644,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, tic-tac-toe",
"url": null
} |
c++, object-oriented, tic-tac-toe
TicTacToe.cpp
#include "TicTacToe.h"
#include <iostream>
#include <memory>
#include <stdlib.h>
#include <string>
#include <vector>
TicTacToe::TicTacToe(const int numberOfHumanPlayers)
{
switch (numberOfHumanPlayers) {
case 0:
m_players.push_back(std::make_unique<PlayerCPU>("CPU 1"));
m_players.push_back(std::make_unique<PlayerCPU>("CPU 2"));
break;
case 1:
m_players.push_back(std::make_unique<PlayerHuman>("Player"));
m_players.push_back(std::make_unique<PlayerCPU>("CPU"));
break;
case 2:
default:
m_players.push_back(std::make_unique<PlayerHuman>("Player 1"));
m_players.push_back(std::make_unique<PlayerHuman>("Player 2"));
}
}
void TicTacToe::step()
{
std::cout << "Player: " << m_players[m_currentPlayer]->getName() << std::endl;
int selectedField;
while (true) {
selectedField = m_players[m_currentPlayer]->provideField(m_board);
if (m_board.isMoveAllowed(selectedField)) {
break;
} else {
std::cout << "Invalid move" << std::endl;
}
}
m_board.takeFieldOnBoard(selectedField, returnPlayerSign(m_currentPlayer));
clearConsole();
printBoard();
if (m_board.isGameWon()) {
std::cout
<< m_players[m_currentPlayer]->getName() << "(" << returnPlayerSign(m_currentPlayer) << ") won!" << std::endl;
terminate();
return;
}
if (!m_board.areThereFreeFields()) {
std::cout << "Game ended" << std::endl;
terminate();
return;
}
nextPlayer();
}
void TicTacToe::printBoard() const
{
m_board.printBoard();
}
char TicTacToe::returnPlayerSign(const int player) const
{
if (player == 0) {
return 'X';
}
return 'O';
}
void TicTacToe::nextPlayer()
{
m_currentPlayer += 1;
m_currentPlayer %= 2;
}
void TicTacToe::clearConsole()
{
system("clear");
}
void TicTacToe::intro()
{
std::cout << "Tic Tac Toe game" << std::endl; | {
"domain": "codereview.stackexchange",
"id": 44644,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, tic-tac-toe",
"url": null
} |
c++, object-oriented, tic-tac-toe
{
system("clear");
}
void TicTacToe::intro()
{
std::cout << "Tic Tac Toe game" << std::endl;
std::cout << "To make a move, enter number of field" << std::endl;
}
std::string TicTacToe::getInputFromConsole()
{
std::string input;
std::cin >> input;
return input;
}
bool TicTacToe::isRunning() const
{
return m_running;
}
void TicTacToe::terminate()
{
m_running = false;
} | {
"domain": "codereview.stackexchange",
"id": 44644,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, tic-tac-toe",
"url": null
} |
c++, object-oriented, tic-tac-toe
Board.h
#pragma once
#include <array>
#include <vector>
class Board {
public:
Board();
bool isGameWon() const;
bool isMoveAllowed(const int field) const;
bool areThereFreeFields() const;
const std::vector<int>& returnAllowedIds() const;
void takeFieldOnBoard(const int field, const char sign);
void printBoard() const;
private:
std::array<char, 9> m_board;
std::vector<int> m_allowedFieldsIds;
bool checkCol(const int) const;
bool checkRow(const int) const;
bool checkAllCols() const;
bool checkAllRows() const;
bool checkDiagonals() const;
};
Board.cpp
#include "Board.h"
#include <algorithm>
#include <iostream> | {
"domain": "codereview.stackexchange",
"id": 44644,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, tic-tac-toe",
"url": null
} |
c++, object-oriented, tic-tac-toe
Board::Board()
{
m_allowedFieldsIds.reserve(9);
for (int i = 0; i < 9; i++) {
m_board[i] = i + '0';
m_allowedFieldsIds.push_back(i);
};
}
const std::vector<int>& Board::returnAllowedIds() const
{
return m_allowedFieldsIds;
}
void Board::takeFieldOnBoard(const int field, const char sign)
{
m_board[field] = sign;
m_allowedFieldsIds.erase(std::remove(m_allowedFieldsIds.begin(), m_allowedFieldsIds.end(), field), m_allowedFieldsIds.end());
}
bool Board::isMoveAllowed(const int field) const
{
auto it = std::find(m_allowedFieldsIds.begin(), m_allowedFieldsIds.end(), field);
if (it != m_allowedFieldsIds.end()) {
return true;
}
return false;
}
bool Board::areThereFreeFields() const
{
return !m_allowedFieldsIds.empty();
}
bool Board::isGameWon() const
{
if (checkAllCols()) {
return true;
}
if (checkAllRows()) {
return true;
}
if (checkDiagonals()) {
return true;
}
return false;
}
bool Board::checkRow(const int row) const
{
if (m_board[row] == m_board[row + 1] && m_board[row + 1] == m_board[row + 2]) {
return true;
}
return false;
}
bool Board::checkAllRows() const
{
for (int i = 0; i < 9; i += 3) {
if (checkRow(i)) {
return true;
}
}
return false;
}
bool Board::checkCol(const int col) const
{
if (m_board[col] == m_board[col + 3] && m_board[col + 3] == m_board[col + 6]) {
return true;
}
return false;
}
bool Board::checkAllCols() const
{
for (int i = 0; i < 3; i++) {
if (checkCol(i)) {
return true;
}
}
return false;
}
bool Board::checkDiagonals() const
{
if (m_board[0] == m_board[4] && m_board[4] == m_board[8]) {
return true;
}
if (m_board[2] == m_board[4] && m_board[4] == m_board[6]) {
return true;
}
return false;
}
void Board::printBoard() const
{
for (int i = 0; i < 9; i += 3) { | {
"domain": "codereview.stackexchange",
"id": 44644,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, tic-tac-toe",
"url": null
} |
c++, object-oriented, tic-tac-toe
}
return false;
}
void Board::printBoard() const
{
for (int i = 0; i < 9; i += 3) {
std::cout << m_board[i] << '|' << m_board[i + 1] << '|' << m_board[i + 2] << std::endl;
if (i < 6) {
std::cout << "_____" << std::endl;
}
}
std::cout << std::endl;
} | {
"domain": "codereview.stackexchange",
"id": 44644,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, tic-tac-toe",
"url": null
} |
c++, object-oriented, tic-tac-toe
Players.h
#pragma once
#include "Board.h"
#include <array>
#include <string>
class Player {
public:
Player(const std::string& name)
: m_name(name) {};
virtual int provideField(const Board& board) const = 0;
const std::string& getName() const;
private:
const std::string m_name;
};
// Human player
class PlayerHuman : public Player {
public:
PlayerHuman(const std::string& name)
: Player(name) {};
int provideField(const Board& board) const override;
private:
int askForInput() const;
};
// CPU Player
class PlayerCPU : public Player {
public:
PlayerCPU(const std::string& name)
: Player(name) {};
int provideField(const Board& board) const override;
int returnFirstAllowedField(const Board& board) const;
int returnRandomField(const Board& board) const;
};
Players.cpp
#include "Players.h"
#include <algorithm>
#include <array>
#include <chrono>
#include <iostream>
#include <iterator>
#include <random>
#include <thread>
#include <vector>
// Player
const std::string& Player::getName() const
{
return m_name;
}
// PlayerHuman
int PlayerHuman::provideField(const Board& board) const
{
return askForInput();
}
int PlayerHuman::askForInput() const
{
int field;
std::cout << "Field #";
std::cin >> field;
return field;
}
// PlayerCPU
int PlayerCPU::provideField(const Board& board) const
{
using namespace std::chrono_literals;
std::this_thread::sleep_for(1000ms);
return returnRandomField(board);
return 0;
}
int PlayerCPU::returnFirstAllowedField(const Board& board) const
{
return board.returnAllowedIds()[0];
}
int PlayerCPU::returnRandomField(const Board& board) const
{
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> distr(0, board.returnAllowedIds().size() - 1);
return board.returnAllowedIds()[distr(gen)];
} | {
"domain": "codereview.stackexchange",
"id": 44644,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, tic-tac-toe",
"url": null
} |
c++, object-oriented, tic-tac-toe
Answer: This is quite good! I see some thought has gone into organizing things into classes, you thought about const parameters and functions, passing by reference, #included local headers before the standard ones, smart pointers, and you use C++'s random number generators correctly.
Use '\n' instead of std::endl
Prefer using '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually unnecessary and might hurt performance.
Avoid using system()
Using system() has a huge overhead: it starts a shell, parses the command you give it, and then starts another process that runs /usr/bin/clear. It is also non-portable; on Windows you would have to call cls instead of clear. Finally, it is unsafe; depending on the user's environment and the way their shell has been configured, clear might not do what you expect it to do.
Consider that /usr/bin/clear is written in C, you should be able to write C++ code yourself that clears the screen without having to call another program. On most operating systems, including the latest versions of Windows, you can just print an ANSI escape code. If you want to be even more portable, you can consider using a curses library. You could also consider not bothering clearing the screen; users will see past versions of the board, but it doesn't impact the game itself.
Reading input
When you are reading input from std::cin, you have to consider a few things. First, the user might enter things that are not valid. For example, when asking how many players there are, the user could enter "-1", "3", "two", and so on. If a valid integer is read, you only check if that integer is 0 or 1, and anything else you treat as if it was 2, which might result in unexpected behavior.
Also consider that entering "two" will result in playersAmount being equal to 0, and will start a two CPU player game. Again, that is unexpected. | {
"domain": "codereview.stackexchange",
"id": 44644,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, tic-tac-toe",
"url": null
} |
c++, object-oriented, tic-tac-toe
Finally, there could be an error reading anything from std::cin at all. For example, the terminal might be closed, or the input was redirected to something that doesn't allow reading, and so on. Again, ignoring this will result in unexpected behavior of your program.
The correct thing to do is to check whether the input was read correctly. You can check after reading something if std::cin.good() is true. There are other operations you can use to find out if it was an error reading anything at all, or whether it couldn't convert the input to the desired type. In the latter case, you could consider asking the user to try again. In the case of an error you cannot recover from, just print an error message and terminate the program.
Even if reading was succesful, make sure that the value that was read is valid for your program; if not you probably should ask the player to try again.
Reading one line at a time
You probably intend the player to write something and then press enter. That means they enter one line at a time. However, when you read somehting with std::cin >> variable, it doesn't read a whole line, instead it only reads one character, integer or word (depending on whether variable is a char, int or std::string). This can result into unexpected behavior if the user enters multiple things on one line.
Consider reading in a whole line at a time into a std::string, and then parse the string. You can do this with std::getline(). For example:
int playersAmount; | {
"domain": "codereview.stackexchange",
"id": 44644,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, tic-tac-toe",
"url": null
} |
c++, object-oriented, tic-tac-toe
while (true) {
std::string line;
if (!std::getline(std::cin, line)) {
std::cerr << "Error reading input!\n";
return EXIT_FAILURE;
}
playersAmount = std::stoi(line);
if (playersAmount >= 0 && playersAmount <= 2) {
break;
}
std::cerr << "Enter a number between 0 and 2!\n";
}
Storing the set of allowed fields
You use a std::vector<int> to store the IDs of allowed fields. While this works, an even better way would be to use a std::bitset<9>.
Tracking the current player
You have the variable m_currentPlayer to track whose turn it is. However, that information is actually also available in m_board.m_allowedFieldsIds: consider that if the number of allowed fields to place a mark in is odd, it's the first player's turn, and if it is even it is the second player's turn. After making a move, you'd have removed an ID from m_allowedFieldsIds, so it will already be updated to reflect that it is the next player's move.
Not all functions need to be in a class
In C++ you can have free functions that are not part of a class. One example is main() of course. Since clearing a console is not something that is specific to a tic-tac-toe game, I would move clearConsole() out of class TicTacToe, and make it a free function. You could put it in a separate file that contains console-related functions. getInputFromConsole() could also be put there.
Storing players
Players(cpu and human) are derived from virtual class players and stored in vector as unique pointers to common class. Is there more elegant way to achieve this?
This is the right way to do it when using inheritance, which is perfectly fine in this case.
Another way to do it would be to not use inheritance, but to store a vector of std::variants:
class PlayerHuman {…}; // no inheritance from Player
class PlayerCPU {…};
using Player = std::variant<PlayerHuman, PlayerCPU>;
class TicTacToe {
…
std::vector<Player> m_players;
…
}; | {
"domain": "codereview.stackexchange",
"id": 44644,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, tic-tac-toe",
"url": null
} |
c++, object-oriented, tic-tac-toe
class TicTacToe {
…
std::vector<Player> m_players;
…
};
TicTacToe::TicTacToe(const int numberOfHumanPlayers)
{
…
m_players.push_back(PlayerHuman("Player"));
m_players.push_back(PlayerCPU("CPU"));
…
}
That looks much more elegant, and no pointers are needed. However, accessing the players is not so simple. You cannot write:
std::cout << "Player: " << m_players[m_currentPlayer].getName() << '\n';
Instead, you would have to use std::visit():
std::cout << "Player: "
<< std::visit([](auto& player) { return player.getName(); },
m_players[m_currentPlayer])
<< '\n';
Having to write a visitor every time you need to do something with a player is going to be cumbersome and thus inelegant. However, in your code you actually only need to call std::visit() once:
void TicTacToe::step()
{
std::visit([&](auto& player) {
std::cout << "Player: " << player.getName() << '\n';
// All the rest of step() here
…
}, m_players[m_currentPlayer]);
}
Is this more elegant? You can decide for yourself. I think it doesn't matter much for this game. However, each way has its own pros and cons, and which one to choose will depend on the situation. | {
"domain": "codereview.stackexchange",
"id": 44644,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, tic-tac-toe",
"url": null
} |
python, beginner
Title: Beginner - Python BlackJack
Question: I am brand new to coding, and am just working my way through the basics. This is the Day 11 project for the 100 days of code on Angela Yu's course on Udemy. I am not familiar with classes yet, so none were used. I definitely feel like I overused if elif statements, like a lot, and probably could have utilized functions better, but had trouble getting them to work when I tried them in various places. I wanted to do this one on my own, so I skipped all of the hints and tutorials and just did it. I know it's a mess, but any feedback would be very much appreciated. Thanks for looking!
Main
from day_11_library import *
from os import system
from time import sleep
player_wallet = 0
def blackjack(player_wallet):
# deposits money if player hits $0
if player_wallet <= 0:
player_wallet += 100
#creates empty list for dealer hand, sets flag for wile loop and sets dealer total to 0
dealer_hand = []
dealer_total = 0
dealer_flag = True | {
"domain": "codereview.stackexchange",
"id": 44645,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
python, beginner
#draws cards for dealer and returns result
while dealer_flag == True:
if dealer_total == 0:
dealer_card_1 = draw()
dealer_card_2 = draw()
dealer_total += dealer_card_1[1] + dealer_card_2[1]
dealer_hand.append(dealer_card_1[0])
dealer_hand.append(dealer_card_2[0])
elif dealer_total == 21 and len(dealer_hand) == 2:
dealer_result = "blackjack"
dealer_flag = False
elif dealer_total == 21:
dealer_result = "21"
dealer_flag = False
elif dealer_total < 17:
dealer_draw = draw()
dealer_total += dealer_draw[1]
dealer_hand.append(dealer_draw[0])
elif 17 <= dealer_total < 21:
dealer_result = 'stand'
dealer_flag = False
elif dealer_total > 21:
for card in dealer_hand:
if card == 'A':
dealer_hand[dealer_hand.index(card)] = 'x'
dealer_total -= 10
break
if dealer_total > 21:
dealer_result = "bust"
dealer_flag = False
#returns dealers remvoed aces
for ace in dealer_hand:
if ace == 'x':
dealer_hand[dealer_hand.index(ace)] = 'A'
print(f'\nThe dealer is showing:\n'
f'{dealer_hand[0]}')
# creates empty list for player hand, sets flag for wile loop and sets player total to 0
player_hand = []
player_split_1 = []
player_split_2 = []
player_total = 0
split_total_1 = 0
split_total_2 = 0
split_flag_1 = False
split_flag_2 = False
player_flag = True
player_wallet -= 5 | {
"domain": "codereview.stackexchange",
"id": 44645,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
python, beginner
while player_flag == True:
# Initial player draw
if player_total == 0:
player_card_1 = draw()
player_card_2 = draw()
player_hand.append(player_card_1[0])
player_hand.append(player_card_2[0])
player_total += player_card_1[1] + player_card_2[1]
print('\nYour hand is:')
hand = player_hand
print_cards(hand)
print(f'\n\nYour balance is:\n'
f'${player_wallet}\n')
# split 1 21 or blackjack
if split_total_1 == 21 and len(player_split_1) == 2:
split_1_result = 'blackjack'
elif split_total_1 == 21:
split_1_result = '21'
# split 2 21 or blackjack
if split_total_2 == 21 and len(player_split_2) == 2:
split_2_result = 'blackjack'
player_flag = False
sleep(.25)
system('clear')
elif split_total_2 == 21:
split_2_result = '21'
player_flag = False
sleep(.25)
system('clear')
# player 21 or blackjack
if player_total == 21 and len(player_hand) == 2:
player_result = 'blackjack'
player_flag = False
sleep(.25)
system('clear')
elif player_total == 21:
player_result = '21'
player_flag = False
sleep(.25)
system('clear') | {
"domain": "codereview.stackexchange",
"id": 44645,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
python, beginner
# player first round action
if player_total < 21 and len(player_hand) == 2:
player_choice = input(f'Would you like to Hit, Stand, Split, or Double Down?: ').lower()
sleep(.25)
system('clear')
if player_choice not in ['split', 'double', 'stand', 'hit']:
print('Please type one of the accepted words.')
#player split first round
elif player_choice == 'split':
player_wallet -= 5
split_flag_1 = True
split_flag_2 = True
draw_1 = draw()
draw_2 = draw()
player_split_1.append(player_hand[0])
player_split_2.append(player_hand[1])
player_split_1.append(draw_1[0])
player_split_2.append(draw_2[0])
split_total_1 += player_card_1[1] + draw_1[1]
split_total_2 += player_card_2[1] + draw_2[1]
del player_hand[0]
del player_hand[0]
sleep(.25)
system('clear')
print(f'\nThe dealer is showing:\n'
f'{dealer_hand[0]}')
hand = player_split_1
print('\nSplit 1 hand:')
hand = player_split_1
print_cards(hand)
print('\n')
hand = player_split_2
print('Split 2 hand:')
print_cards(hand)
print(f'\n\nYour current balance is:\n'
f'${player_wallet}\n')
# double down first round
elif player_choice == 'double':
sleep(.25)
system('clear')
player_wallet -= 5
card_draw = draw()
player_hand.append(card_draw[0])
player_total += card_draw[1]
if player_total > 21:
player_result = 'bust'
else: | {
"domain": "codereview.stackexchange",
"id": 44645,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
python, beginner
player_result = 'bust'
else:
player_result = 'double'
player_flag = False
sleep(.25)
system('clear')
# player stand first round
elif player_choice == 'stand':
player_result = 'stnd'
player_flag = False
sleep(.25)
system('clear')
#player hit first round
elif player_choice == 'hit':
card_draw = draw()
player_hand.append(card_draw[0])
player_total += card_draw[1]
print(f'\nThe dealer is showing:\n'
f'{dealer_hand[0]}')
print('\n')
print('Your hand:')
hand = player_hand
print_cards(hand)
print('\n\n')
# split 1 action prompt
elif split_total_1 < 21 and split_flag_1 == True:
split_1_choice = input(f'\n\nWould you like to Hit, or Stand on split 1?: ').lower()
sleep(.25)
system('clear') | {
"domain": "codereview.stackexchange",
"id": 44645,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.