body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>In my second post I am looking for the way to change answer dynamically.
As you can see there it changes when I completely fill the input. I want it to change for every letter typed . I will be gratefull guys !</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var passwordField = document.forms["takis"]["hero"];
var checkContrainer = document.getElementById("contrainer");
function sila(){
if(passwordField.value.length >= 8 && passwordField.value.match(/[0-9]+/)!= null && passwordField.value.match(/[a-z]+/)!= null && passwordField.value.match(/[A-Z]+/)!= null)
checkContrainer.innerHTML = '<h2 style="color:#449055"> Very Strong </h2>';
else if(passwordField.value.length >= 8 && passwordField.value.match(/[0-9]+/)!= null)
checkContrainer.innerHTML = '<h2 style="color:#AAEE99"> Strong </h2>';
else if((passwordField.value.length >= 8 && passwordField.value.match(/[a-z]+/)!= null && passwordField.value.match(/[A-Z]+/)!= null) || passwordField.value.length >= 6 && passwordField.value.length <= 7 && passwordField.value.match(/[0-9]+/)!= null && passwordField.value.match(/[a-z]+/)!= null && passwordField.value.match(/[A-Z]+/)!= null)
checkContrainer.innerHTML = '<h2 style="color:yellow"> Medium </h2>';
else
checkContrainer.innerHTML = '<h2 style="color:red"> Weak </h2>';
}
passwordField.addEventListener("change", sila);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body
{
background-color: #06619A;
margin: 0;
}
form
{
background-color: #30A4C8;
width: 25%;
margin: auto;
padding: 20px;
min-height: 80px;
border: 2px #114577 solid;
border-radius: 8px;
}
div
{
background-color: #444444;
border-radius: 12px;
text-align: center;
border: 1px #333333 solid;
margin-top: 2px;
height: 70px;
}
input
{
outline: 0;
border: 2px #114577 solid;
border-radius: 8px;
width: 80%;
}
input:hover
{
border-color: #996655;
transition: 0.5s;
}
input:not(:hover)
{
transition: 0.5s;
}
h1
{
font-size: 22px;
text-align: center;
font-family: "Arial Black";
color: white;
background-color: #30A4C8;
margin: 0;
margin-bottom: 20px;
border-bottom: 2px #114577 solid;
border-radius: 5px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="setaki.css" type="text/css">
</head>
<body>
<h1> Password Checker v26.5 <sup>Really hard work no scam !</sup></h1>
<form name="takis">
Hasło: <input type="password" name="hero">
<div id="contrainer">
</div>
</form>
<script src="mmn.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>Use data to control how password strength is decided. Make a list of objects with properties that describe each level of strength.</p>\n\n<p>This makes it easy to compare strengths. In your code, <code>12345678</code> is classified as \"Strong.\" It's not!</p>\n\n<p>Matching <code>[a-z]+</code> is the same as matching <code>[a-z]</code> if you aren't saving the match.</p>\n\n<p>Use CSS classes to control appearance.</p>\n\n<p>Use dot notation for constant property names: <code>object.thing</code> instead of <code>object[\"thing\"]</code>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const elemInput = document.forms.takis.hero;\nelemInput.addEventListener(\"input\", sila);\n\nfunction sila() {\n const elemStrength = document.getElementById(\"strength\"),\n strength = pwRate( elemInput.value ),\n classes = \"strength \" + strength.replace( /[^A-Za-z0-9]/g, '' );\n \n elemStrength.className = classes;\n elemStrength.textContent = strength;\n}\n\nfunction pwRate(pw) { \n const ranks = [ \n { rank: \"Very Strong\",\n minLength: 8,\n minParts: 3,\n },\n { rank: \"Strong\",\n minLength: 8,\n minParts: 2,\n mustMatch: \"digit\",\n },\n { rank: \"Medium\",\n minLength: 8,\n minParts: 2,\n },\n { rank: \"Medium\",\n minLength: 6,\n minParts: 3,\n },\n { rank: \"Weak\",\n minLength: 3 // let the user type a few before calling him weak\n }\n ];\n \n const parts = { digit: /[0-9]/,\n upper: /[A-Z]/,\n lower: /[a-z]/,\n other: /[^A-Za-z0-9]/\n };\n \n const hasParts = Object.keys( parts )\n .filter( p => parts[p].test(pw) )\n .reduce( (matches, key) => matches[key]=1 && matches, {} ),\n nParts = Object.keys( hasParts ).length;\n \n for (var rank of ranks) {\n if (\n (!rank.minLength || pw.length >= rank.minLength)\n &&\n (!rank.minParts || nParts >= rank.minParts)\n &&\n (!rank.mustMatch || hasParts[ rank.mustMatch ])\n ) return rank.rank\n }\n return \"\";\n} </code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.strength { background-color: #444444; }\n.strength.VeryStrong { color: #449055 }\n.strength.Strong { color: #aaee99 }\n.strength.Medium { color: yellow }\n.strength.Weak { color: red }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form name=\"takis\"> Password: <input type=\"password\" name=\"hero\"> </form>\n<div id=\"strength\" class=\"strength\" /></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T01:59:49.157",
"Id": "215894",
"ParentId": "215886",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T23:12:04.487",
"Id": "215886",
"Score": "1",
"Tags": [
"javascript",
"css",
"html5"
],
"Title": "Password Checker"
} | 215886 |
<p>I'm trying to write a program that stores usernames and passwords. So I have created a Record class. Each record has an id, title, username, and password field. I want to write each record to a text file. </p>
<p>However, I am having some issues. When I compile I get the following errors.</p>
<pre><code>'Record::getTitle': non-standard syntax; use '&' to create a pointer to member
'Record::getUsername': non-standard syntax; use '&' to create a pointer to member
'Record::getPassword': non-standard syntax; use '&' to create a pointer to member
</code></pre>
<p>The problem:</p>
<pre><code>writeToFile(firstRecord.getTitle, firstRecord.getUsername, firstRecord.getPassword);
</code></pre>
<p>The getTitle(and others) return a string. So I am not sure why this isn't working. Any suggestions would be appreciated.</p>
<p>Complete code (so far) below..</p>
<pre><code>#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include <functional>
using namespace std;
string GetInput();
void MainMenu();
void Title();
void AddRecord();
void writeToFile(string title, string username, string password);
class Record {
private:
string id;
string title;
string username;
string password;
static int numberOfRecords;
public:
void setTitle(string title) {
this->title = title;
}
string getTitle() {
return title;
}
void setUsername(string username) {
this->username = username;
}
string getUsername() {
return username;
}
void setPassword(string password) {
this->password = password;
}
string getPassword() {
return password;
}
static int GetNumberOfRecords() {
return numberOfRecords;
}
};
struct MenuAction {
string description;
function<void()> action;
};
static const map <string, MenuAction> actionTable{
{ "1",{ "Add entry", []() { AddRecord(); } } },
{ "2",{ "Edit entry", []() { cout << "Edit entry" << "\n"; } } },
{ "q",{ "Quit", []() { cout << "Quit" << "\n"; } } }
};
int main() {
Title();
MainMenu();
return 0;
}
void Title() {
cout << "======================================\n"
"| Database |\n"
"======================================\n\n";
}
void MainMenu() {
for (auto const& x : actionTable) {
cout << x.first << ". " << (x.second).description << "\n";
}
string input;
while (actionTable.count(input) == 0) {
input = GetInput();
}
actionTable.at(input).action();
}
void AddRecord() {
cout << "============= Add Record ============" << endl << endl;
string id;
string title;
string username;
string password;
cout << "Title: ";
getline(cin, title);
cout << "Username: ";
getline(cin, username);
cout << "Password: ";
getline(cin, password);
Record firstRecord;
firstRecord.setTitle(title);
firstRecord.setUsername(username);
firstRecord.setPassword(password);
writeToFile(firstRecord.getTitle, firstRecord.getUsername, firstRecord.getPassword);
}
string GetInput() {
string s = "";
cout << ">> ";
getline(cin, s);
return s;
}
void writeToFile(string title, string username, string password) {
ofstream outFile;
outFile.open("database.txt", ios_base::app);
outFile << title << "\t" << username << "\t" << password << "\n";
cout << "============= Record Added To Database ============" << endl;
}
</code></pre>
<p>Feel free to comment or nag other portions of my code :)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T02:43:05.760",
"Id": "417740",
"Score": "0",
"body": "What's the deal? Why is this getting down voted? I'm fairly new here and to c++ in general. Is there some protocol I'm not following?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T07:49:15.280",
"Id": "417774",
"Score": "1",
"body": "Hey, welcome to Code Review! Here we review real, working code and try to make it better. This is not the right place to ask for help fixing your code. For this, [so] is better suited (but be sure to consult their [help center](https://stackoverflow.com/help) first)."
}
] | [
{
"body": "<p><strong>firstRecord.getTitle, firstRecord.getUsername, firstRecord.getPassword</strong></p>\n\n<p>The params you are passing into your function are not properties, they are functions (getters) of your object.</p>\n\n<p>You need to access them like functions:\nwriteToFile(firstRecord.getTitle(), firstRecord.getUsername(), firstRecord.getPassword());</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T00:52:07.113",
"Id": "417736",
"Score": "0",
"body": "Wow. That was an embarrassing mistake. Thanks for the help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T00:48:35.673",
"Id": "215891",
"ParentId": "215890",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": "215891",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T00:31:49.577",
"Id": "215890",
"Score": "-3",
"Tags": [
"c++",
"beginner",
"object-oriented"
],
"Title": "C++ writing object data to file"
} | 215890 |
<p>I am a beginner programmer and would like some feedback on this Tic Tac Toe game I made on Python. Any feedback would be appreciated, as I really want to get better at programming and pick up good habits. Here is my code. Something I would add is <code>try</code> statements for invalid user input, but this is not important as I would like feedback on how to optimise this code. I would also love feedback on the <code>check_if_win()</code> function as I believe there might be a better way of doing this. Thank you!</p>
<pre><code>"""Tic Tac Toe"""
__author__ = "Enrique Gonzalez Aretos"
EMPTY = " "
PLAYER_1 = "X"
PLAYER_2 = "O"
# Create Board
def create_board():
"""
Function which creates an empty game board
:return: <list<list<str>>> Returns the game board
"""
return [
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]
]
# Show board
def show_board(board):
"""
Function which prints the board for the user
:param board: <list<list<str>>> The Tic Tac Toe board
:return: <str> A clean-looking version of the board
"""
for x in board:
# Find better way to print this
print("|".join(x))
# Place X on spot
def place_player(board, active_player, row, column):
"""
Function which places the player into the board
:param board:
:param active_player:
:param row:
:param column:
:return:
"""
if board[row-1][column-1] == EMPTY:
board[row-1][column-1] = active_player
# Check if someone has won
def check_if_win(board, active_player):
"""
Function which checks if the active player has won
:param board: <list<list<str>>> Tic Tac Toe Board
:param active_player: <str> The current active player
:return: <bool> Return True or False
"""
# Making lists which will store the diagonals and columns of baord
diagonal1 = []
diagonal2 = []
column1 = []
column2 = []
column3 = []
# Diagonal counter is used to index the different values in each row
diagonal_counter = 1
for row in board:
# When each row is checked, the different indexes are organised
# into the column and diagonal lists
column1.append(row[0])
column2.append(row[1])
column3.append(row[2])
diagonal1.append(row[diagonal_counter-1])
diagonal2.append(row[-diagonal_counter])
diagonal_counter += 1
if "".join(row) == active_player * 3:
return True
# If statement which checks if any list is full of the active
# player's symbol
if "".join(column1) == active_player * 3 or "".join(column2) ==
active_player * 3 or "".join(column3) == active_player * 3:
return True
elif "".join(diagonal1) == active_player * 3 or "".join(diagonal2)
== active_player * 3:
return True
else:
return False
def swap_player(active_player):
if active_player == PLAYER_1:
return PLAYER_2
else:
return PLAYER_1
def main():
# Creates board and assigns starting player
board = create_board()
active_player = PLAYER_1
while True:
show_board(board)
# Ask for player input
row = int(input("\nIt is {}'s turn play. Choose a row (1-3):
".format(active_player)))
column = int(input("Choose a column: "))
place_player(board, active_player, row, column)
# Checks if player has won
if check_if_win(board, active_player) is True:
show_board(board)
print("\n{} won!".format(active_player))
break
active_player = swap_player(active_player)
if __name__ == "__main__":
main()
</code></pre>
| [] | [
{
"body": "<h2><code>create_board()</code></h2>\n\n<p>You explicitly return a hard-coded board, using 5 lines of code. This could be written as one line, using list multiplication and list comprehension:</p>\n\n<pre><code>return [ [EMPTY]*3 for _ in range(3) ]\n</code></pre>\n\n<p><code>[EMPTY]*3</code> creates a list of 3 <code>EMPTY</code> values: <code>[EMPTY, EMPTY, EMPTY]</code>, and the outer <code>[ ... for _ in range(3) ]</code> repeats that operation 3 times, producing the required board. (As pointed out in the comments, using list multiplication for the outer loop doesn’t produce 3 unique rows, but 3 references to the same row.)</p>\n\n<h2><code>show_board()</code></h2>\n\n<p>This function does not return anything, so certainly does not <code>:return: <str> A clean-looking version of the board</code></p>\n\n<h2><code>place_player()</code></h2>\n\n<p>Despite the comment above the function, this method can be used to place an <code>\"O\"</code> on a spot on the board.</p>\n\n<p>Suggestion: indicate somehow if the move is invalid (beyond row 1..3 or column 1..3, or if the spot is not empty, such as by raising an exception or returning a success/failure code.</p>\n\n<h2><code>check_if_win()</code></h2>\n\n<p>This function is using <code>active_player * 3</code> in a total of six places. Instead of repeating this expression six times, you could assign the result to a local variable, and test against that variable instead:</p>\n\n<pre><code>win_pattern = active_player * 3\n# ...\nfor row in board:\n # ...\n if \"\".join(row) == win_pattern:\n return True\n# ... etc ...\n</code></pre>\n\n<p>But a winning pattern isn't actually a string; it is a list of cells each containing the <code>active_player</code> symbol: <code>['X', 'X', 'X']</code>. You've just used <code>\"\".join(...)</code> to convert the list into a string. Why create the string when you can just check for equality with the list?</p>\n\n<pre><code>win_pattern = [ active_player ] * 3\n# ...\nfor row in board:\n # ...\n if row == win_pattern:\n return True\n\nif column1 == win_pattern or column2 == win_pattern or column3 == win_pattern:\n return True\nelif diagonal1 == win_pattern or diagonal2 == win_pattern:\n return True\nelse:\n return False\n</code></pre>\n\n<p>But this code is still quite verbose. There is a pythonic way of testing if any item in a list of items matches a condition. It uses the <code>any(iterable)</code> call; if any of the iterable items is <code>True</code>, the resulting <code>any(...)</code> expression evaluates to <code>True</code>. Using this to test for any of the rows of the board matching the <code>win_pattern</code> is straight forward:</p>\n\n<pre><code>if any(row == win_pattern for row in board):\n return True\n</code></pre>\n\n<p>Your <code>for row in board:</code> loop also constructs the <code>column1</code>, <code>column2</code>, <code>column3</code>, <code>diagonal1</code> and <code>diagonal2</code> lists. Whenever you have a set of variables with the same prefix name and numeric suffixes, you aught to ask yourself if you could use a list (for example, <code>column[0]</code>, <code>column[1]</code>, and <code>column[2]</code>) or a loop. Let's start by making a single column in a loop:</p>\n\n<pre><code>column = []\nfor row in board:\n column.append(row[col])\n</code></pre>\n\n<p>If <code>col</code> was <code>0</code>, this would make your <code>column1</code> variable from your code. List comprehension can reduce this to one line:</p>\n\n<pre><code>column = [ row[col] for row in board ]\n</code></pre>\n\n<p>We actually only need the <code>column</code> variable for just the test against <code>win_pattern</code>, so we could actually eliminate it and perform the test directly:</p>\n\n<pre><code>if [ row[col] for row in board ] == win_pattern:\n return True\n</code></pre>\n\n<p>Doing that in a loop, for all 3 <code>col</code> values completes the test for a win in any column:</p>\n\n<pre><code>for col in range(3):\n if [ row[col] for row in board ] == win_pattern:\n return True\n</code></pre>\n\n<p>But above, we replaced a <code>for x in y:</code> and an inner <code>if condition:</code> with an <code>any(...)</code> statement; we can do the same thing here!</p>\n\n<pre><code>if any( [ row[col] for row in board ] == win_pattern for col in range(3)):\n return True\n</code></pre>\n\n<p>We can also do this for the forward diagonal:</p>\n\n<pre><code>if [ board[i][i] for i in range(3) ] == win_pattern:\n return True\n</code></pre>\n\n<p>And the reverse diagonal:</p>\n\n<pre><code>if [ board[i][2-i] for i in range(3) ] == win_pattern:\n return True\n</code></pre>\n\n<p>This looks a lot shorter, and simpler:</p>\n\n<pre><code>win_pattern = [ active_player ] * 3\n\nif any(row == win_pattern for row in board):\n return True\n\nif any( [ row[col] for row in board ] == win_pattern for col in range(3)):\n return True\n\nif [ board[i][i] for i in range(3) ] == win_pattern:\n return True\n\nif [ board[i][2-i] for i in range(3) ] == win_pattern:\n return True\n\nreturn False\n</code></pre>\n\n<p>... but I don't quite like it yet. We can get rid of the <code>win_pattern</code> list, and all the <code>[ ... for x in y ]</code> list creation, using something similar to <code>any(...)</code>: the <code>all(...)</code> function. It returns <code>True</code> when all elements are <code>True</code>. So instead of</p>\n\n<pre><code>if [ row[col] for row in board ] == [ active_player ] * 3:\n</code></pre>\n\n<p>which creates a list of 3 items on the left-hand-side and creates a list of 3 items on the right hand side and tests if the lists are the same, we'll test if the first element on the left-hand-side is the same as the first element on the right-hand-side, and ditto for the second elements, and ditto for the third elements. Of course, all 3 elements on the right-hand-side are the same element. So the <code>all(...)</code> statement will look like:</p>\n\n<pre><code>if all(row[col] == active_player for row in board):\n</code></pre>\n\n<p>Again, that is testing one particular column index: <code>col</code>. If we want to check if any column has the winning pattern, we'll wrap this in an <code>any</code> call:</p>\n\n<pre><code>if any( all(row[col] == active_player for row in board) for col in range(3)):\n return True\n</code></pre>\n\n<p>So, changing the implementation slightly, to exploit the duality nature of rows and columns, you might write this method as:</p>\n\n<pre><code>def check_if_win(board, active_player):\n\n if any( all(board[r][c] == active_player for c in range(3)) for r in range(3)):\n return True\n\n if any( all(board[r][c] == active_player for r in range(3)) for c in range(3)):\n return True\n\n if all(board[i][i] == active_player for i in range(3)):\n return True\n\n if all(board[i][2-i] == active_player for i in range(3)):\n return True\n\n return False\n</code></pre>\n\n<h2><code>main()</code></h2>\n\n<pre><code>if check_if_win(board, active_player) is True:\n</code></pre>\n\n<p>could be written without the <code>is True</code> portion:</p>\n\n<pre><code>if check_if_win(board, active_player):\n</code></pre>\n\n<p>Asking for user input, and converting it to an integer <code>int(input(...))</code> can lead to <code>ValueError</code> if the user enter bad values, such as <code>\"fish\"</code>. You should check for and catch exceptions. Moreover, you should range-check the input. A user could enter <code>42</code> <code>-1</code> for the row/column. Finally, the user could enter a valid, legal board position which is already used. If the user enters bad values (either not valid integers, or out-of-bound values, or already taken locations), the program should complain and ask the user to re-enter the row column input.</p>\n\n<p><strong>Bug</strong>: Finally, the game could end in a <strong>Tie</strong>, which is currently not handled.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T19:06:44.700",
"Id": "418316",
"Score": "0",
"body": "`[[EMPTY] * 3] * 3` does **not create copies** of the inner list. After `board[0][0] = PLAYER_1` you will end up with `[['X', ' ', ' '], ['X', ' ', ' '], ['X', ' ', ' ']]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T20:05:31.180",
"Id": "418318",
"Score": "0",
"body": "@Wombatz D’oh! I knew that. I should know better than adding a last second addition to the code review post, especially to the very start of the post no less!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T04:56:32.570",
"Id": "215900",
"ParentId": "215893",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T01:47:10.313",
"Id": "215893",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"tic-tac-toe"
],
"Title": "Beginner Tic Tac Toe Game for Python"
} | 215893 |
<p><a href="https://codereview.stackexchange.com/questions/214221/allow-console-draw-poker-game-to-output-more-hands">Further-developed followup to this question</a></p>
<p>Python beginner here.</p>
<p>I created a command-line program that generates poker hands (5-52 cards) and compares their strength. On my Macbook Pro, it generates and compares 1m 5-card hands in ~2m.</p>
<p>Here's my code:</p>
<pre><code>import copy
import distutils.core
from enum import Enum
from time import time
from random import shuffle
from math import floor
#Individual Cards
class Card:
def __init__ (self,value,suit):
self.value = value
self.suit = suit
self.vname = ''
self.sname = ''
def __str__(self):
return f'{self.sname}{self.vname}{self.sname}'
def __repr__(self):
if self.value <= 10:
return f'{self.value}{self.suit[0].lower()}'
if self.value > 10:
return f'{self.vname[0]}{self.suit[0].lower()}'
def vsname(self,value,suit):
if self.value == 2:
self.vname = 'Two'
elif self.value == 3:
self.vname = 'Three'
elif self.value == 4:
self.vname = 'Four'
elif self.value == 5:
self.vname = 'Five'
elif self.value == 6:
self.vname = 'Six'
elif self.value == 7:
self.vname = 'Seven'
elif self.value == 8:
self.vname = 'Eight'
elif self.value == 9:
self.vname = 'Nine'
elif self.value == 10:
self.vname = 'Ten'
elif self.value == 11:
self.vname = 'Jack'
elif self.value == 12:
self.vname = 'Queen'
elif self.value == 13:
self.vname = 'King'
elif self.value == 14:
self.vname = 'Ace'
if self.suit == "Hearts":
self.sname = '♥'
elif self.suit == "Spades":
self.sname = '♠'
elif self.suit == "Clubs":
self.sname = '♣'
elif self.suit == "Diamonds":
self.sname = '♦︎︎'
#All Decks
class Deck:
def __init__(self):
self.cards = []
self.create()
def create(self):
for _ in range(decks):
for val in (2,3,4,5,6,7,8,9,10,11,12,13,14):
for suit in ("Hearts", "Spades", "Clubs", "Diamonds"):
self.cards.append(Card(val,suit))
shuffle(self.cards)
def draw(self,x):
for y in range(x):
drawcards[y] = self.cards.pop()
drawcards[y].vsname(drawcards[y].value,drawcards[y].suit)
return drawcards
class BaseStrength(Enum):
ROYAL_FLUSH = 10000
STRAIGHT_FLUSH = 9000
QUADS = 8000
FULL_HOUSE = 7000
FLUSH = 6000
STRAIGHT = 5000
SET = 4000
TWO_PAIR = 3000
PAIR = 2000
HIGH_CARD = 1000
#Determine Values and Suits in Hand
def determine(hand):
values, vset, suits, all_cards = [], set(), [], []
for x in range(len(hand)):
values.append(hand[x].value)
vset.add(hand[x].value)
suits.append(hand[x].suit)
all_cards.append(hand[x])
return sorted(values,reverse=True),vset,suits,all_cards
#Message/Text Functions
def ss():
if show_strength: print(f'[{round(strength/10000,6)}]')
else: print()
def hnumber(max_v,msg):
while True:
try:
hn = input(msg)
if hn.lower() == 'm' or hn.lower() == 'max':
return max_v
elif 0 < int(hn) <= max_v:
return int(hn)
else:
print(f'Please enter an integer between 1 and {max_v}.')
except ValueError:
print('Please enter a positive integer.')
def decks(msg):
while True:
try:
d = int(input(msg))
if d > 0:
return d
else:
print('Please enter a positive integer.')
except ValueError:
print('Please enter a positive integer.')
def cph(msg):
while True:
try:
d = int(input(msg))
if 5 <= d <= 52:
return d
else:
print('Please enter a positive integer between 5 and 52.')
except ValueError:
print('Please enter a positive integer between 5 and 52.')
def sstrength(msg):
while True:
try:
ss = distutils.util.strtobool(input(msg))
if ss == 0 or ss == 1:
return ss
else:
print('Please indicate whether you\'d like to show advanced stats')
except ValueError:
print('Please indicate whether you\'d like to show advanced stats')
def get_inputs():
decks_ = decks('How many decks are there? ')
cph_ = cph('How many cards per hand? ')
max_v = floor((decks_*52)/cph_)
hnumber_ = hnumber(max_v,f'How many players are there (max {floor((decks_*52)/cph_)})? ')
sstrength_ = sstrength("Would you like to show advanced stats? ")
return (decks_,cph_,hnumber_,sstrength_)
def print_hand(user_hand):
print(f"\nPlayer {h_inc + 1}'s hand:")
print("| ",end="")
for c_x in user_hand: print(user_hand[c_x],end=" | ")
def post_draw():
hss = sorted(h_strength.items(), key=lambda k: k[1], reverse=True)
if not show_strength:
print(f'\n\n\nPlayer {hss[0][0] + 1} has the strongest hand!\nPlayer {hss[hnumber-1][0]+1} has the weakest hand :(')
if show_strength:
print(f'\n\n\nPlayer {hss[0][0]+1} has the strongest hand! [{round(hss[0][1]/10000,6)}]\nPlayer {hss[hnumber-1][0] + 1} has the weakest hand :( [{round(hss[hnumber-1][1]/10000,6)}]')
print('\n\n\n\n\nHand Occurence:\n')
for x in range(10): print(ho_names[x],hand_occurence[x],f'({round(100*hand_occurence[x]/len(hss),2)}%)')
print('\n\n\n\n\nFull Player Ranking:\n')
for x in range(len(hss)): print(f'{x+1}.',f'Player {hss[x][0]+1}',f'[{round(hss[x][1]/10000,6)}]')
print('\n\n\nComplete Execution Time:', "%ss" % (round(time()-deck_start_time,2)))
print('Deck Build Time:', '%ss' % (round(deck_end_time-deck_start_time,2)), f'({int(round(100*(deck_end_time-deck_start_time)/(time()-deck_start_time),0))}%)')
print('Hand Build Time:', '%ss' % (round(time()-deck_end_time,2)), f'({int(round(100*(time()-deck_end_time)/(time()-deck_start_time),0))}%)')
#Evaluation Functions
def valname(x):
if x == 2:
return 'Two'
elif x == 3:
return 'Three'
elif x == 4:
return 'Four'
elif x == 5:
return 'Five'
elif x == 6:
return 'Six'
elif x == 7:
return 'Seven'
elif x == 8:
return 'Eight'
elif x == 9:
return 'Nine'
elif x == 10:
return 'Ten'
elif x == 11:
return 'Jack'
elif x == 12:
return 'Queen'
elif x == 13:
return 'King'
elif x == 14 or x == 1:
return 'Ace'
def hcard(values):
global strength
strength = BaseStrength.HIGH_CARD.value + 10*values[0] + values[1] + .1*values[2] + .01*values[3] + .001*values[4]
return f'High-Card {valname(values[0])}'
def numpair(values):
global strength
pairs = list(dict.fromkeys([val for val in values if values.count(val) == 2]))
if not pairs:
return False
if len(pairs) == 1:
vp = values.copy()
for _ in range(2):
vp.remove(pairs[0])
strength = BaseStrength.PAIR.value + 10*pairs[0] + vp[0] + .1*vp[1] + .01*vp[2];
return f'Pair of {valname(pairs[0])}s'
if len(pairs) >= 2:
vps = values.copy()
pairs = sorted(pairs,reverse=True)
for _ in range(2):
vps.remove(pairs[0]); vps.remove(pairs[1])
strength = (BaseStrength.TWO_PAIR.value + 10*int(pairs[0]) + int(pairs[1])) + .1*vps[0]
return f'{valname(pairs[0])}s and {valname(pairs[1])}s'
def trip(values):
global strength
trips = [val for val in values if values.count(val) == 3]
if not trips:
return False
else:
vs = values.copy()
for _ in range(3):
vs.remove(trips[0])
strength = BaseStrength.SET.value + 10*trips[0] + vs[0] + .1*vs[1]
return f'Set of {valname(trips[0])}s'
def straight(vset,get_vals=False):
global strength
count = 0
if not get_vals:
straight = False
for rank in (14, *range(2, 15)):
if rank in vset:
count += 1
max_c = rank
if count == 5:
strength = BaseStrength.STRAIGHT.value + 10*min(vset)
straight = f'Straight from {valname(max_c-4)} to {valname(max_c)}'
break
else: count = 0
return straight
if get_vals:
sset = set()
for rank in (14, *range(2, 15)):
if rank in vset:
count += 1
sset.add(rank)
if count == 5:
return sset
else:
count = 0
sset = set()
raise Exception('No SSET')
def flush(suits,all_cards):
global strength
flushes = [suit for suit in suits if suits.count(suit) >= 5]
if flushes: flushes_vals = sorted([card.value for card in all_cards if card.suit == flushes[0]],reverse=True)
if not flushes:
return False
else:
strength = BaseStrength.FLUSH.value + 10*flushes_vals[0] + flushes_vals[1] + .1*flushes_vals[2] + .01*flushes_vals[3] + .001*flushes_vals[4]
flush = f'{valname(max(flushes_vals))}-High flush of {flushes[0]}'
return flush
def fullhouse(values):
global strength
trips = list(dict.fromkeys(sorted([val for val in values if values.count(val) == 3],reverse=True)))
if not trips:
return False
pairs = sorted([val for val in values if values.count(val) == 2],reverse=True)
if pairs and trips:
strength = BaseStrength.FULL_HOUSE.value + 10*trips[0] + pairs[0]
fh = f'{valname(trips[0])}s full of {valname(pairs[0])}s'
if len(trips) > 1:
if pairs:
if trips[1] > pairs[0]:
strength = BaseStrength.FULL_HOUSE.value + 10*trips[0] + trips[1]
fh = f'{valname(trips[0])}s full of {valname(trips[1])}s'
else:
strength = BaseStrength.FULL_HOUSE.value + 10*trips[0] + trips[1]
fh = f'{valname(trips[0])}s full of {valname(trips[1])}s'
if len(trips) == 1 and not pairs:
return False
return fh
def quads(values):
global strength
quads = [val for val in values if values.count(val) >= 4]
if not quads:
return False
else:
vq = values.copy()
for _ in range(4): vq.remove(quads[0])
strength = BaseStrength.QUADS.value + 10*quads[0] + vq[0]
return f'Quad {valname(quads[0])}s'
def straightflush(suits,vset,all_cards):
global strength
straight_= False
flushes = [suit for suit in suits if suits.count(suit) >= 5]
if flushes:
flushes_vals = sorted([card.value for card in all_cards if card.suit == flushes[0]],reverse=True)
if straight(flushes_vals):
straight_vals = straight(flushes_vals,True)
if {14,10,11,12,13} <= straight_vals: straight_ = "Royal"
if {14,2,3,4,5} <= straight_vals: straight_ = "Wheel"
else: straight_ = "Normal"
if straight_ == "Normal":
strength = BaseStrength.STRAIGHT_FLUSH.value + 10*max(flushes_vals)
sf = f'{valname(max(straight_vals))}-High Straight Flush of {flushes[0]}'
elif straight_ == "Wheel":
strength = BaseStrength.STRAIGHT_FLUSH.value
sf = f'Five-High Straight Flush of {flushes[0]}'
elif straight_ == "Royal":
strength = BaseStrength.ROYAL_FLUSH.value
sf = f'Royal Flush of {flushes[0]}'
else:
sf = False
return sf
def evalhand(values,suits,vset,all_cards):
x = straightflush(suits,vset,all_cards)
if not x: x = quads(values)
if not x: x = fullhouse(values)
if not x: x = flush(suits,all_cards)
if not x: x = straight(values)
if not x: x = trip(values)
if not x: x = numpair(values)
if not x: x = hcard(values)
return x
def count_hand_occurence(strength):
if strength < 2000: hand_occurence[0]+=1
elif strength < 3000: hand_occurence[1]+=1
elif strength < 4000: hand_occurence[2]+=1
elif strength < 5000: hand_occurence[3]+=1
elif strength < 6000: hand_occurence[4]+=1
elif strength < 7000: hand_occurence[5]+=1
elif strength < 8000: hand_occurence[6]+=1
elif strength < 9000: hand_occurence[7]+=1
elif strength < 10000: hand_occurence[8]+=1
elif strength == 10000: hand_occurence[9]+=1
hand_occurence = {0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
ho_names = ['High Card: ','Pair: ','Two-Pair: ','Three of a Kind: ','Straight: ','Flush: ','Full House: ','Four of a Kind: ','Straight Flush: ','Royal Flush: ']
drawcards, h_strength = {}, {}
decks, cards_per_hand, hnumber, show_strength = get_inputs()
deck_start_time = time()
deck = Deck()
deck_end_time = time()
#Hand Print Loop
for h_inc in range(hnumber):
user_hand = deck.draw(cards_per_hand)
print_hand(user_hand)
values,vset,suits,all_cards = determine(user_hand)
exact_hand = evalhand(values,suits,vset,all_cards)
print('\n'+exact_hand,end=" "); ss()
count_hand_occurence(strength)
h_strength[h_inc] = strength
post_draw()
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>When you have a long if/elif chain in Python it's a good idea to use a dictionary instead. For example: <code>{1: 'one', 2: 'two', 3: ...}</code>. This also makes exception handling easier with the <code>.get()</code> method.</p></li>\n<li><p>Try to use proper names rather than just <code>x</code> or <code>y</code>.</p></li>\n<li><p>Instead of:</p>\n\n<pre><code>for indx in range(len(some_list)):\n some_list[indx].do_something()\n</code></pre>\n\n<p>use:</p>\n\n<pre><code>for item in some_list:\n item.do_something()\n</code></pre></li>\n<li><p>Follow colons with a new line.</p></li>\n<li><p>The <code>while True ... try ... except ValueError</code> is a strange choice. Add a condition to your while loop and just increment some counter.</p></li>\n<li><p>Don't use exceptions to control the flow of the program. Exceptions are for catching exceptional behaviour, i.e. when something has gone wrong.</p></li>\n<li><p>Some of your lines are very long. Split up the printing if necessary.</p></li>\n<li><p>Try to be consistent with fstrings or <code>.format()</code>, not old formatting style (<code>%s</code>).</p></li>\n<li><p>Avoid using globals. There are various ways of getting rid of them such as wrapping hanging functions into a class and having the global as a class variable.</p></li>\n<li><p>Wrap your \"worker\" code (the code that does all the calling) in a function called something like <code>main()</code> (ideally more descriptive than that). Then use the standard: </p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre></li>\n<li><p>Using a dictionary you can rewrite <code>count_hand_occurance()</code> to be a simple generator expression.</p></li>\n<li><p>Try to add doctrings; as a minimum for the classes if not the functions/methods as well.</p></li>\n<li><p>Consider logging all of these messages rather than printing them. Debugging is far easier with logged information. As a start, you could write a simple file writing function (open file in append mode, 'a+') that is called instead of print.</p></li>\n<li><p>in <code>post_draw()</code> you have <code>if not condition:</code> followed by <code>if condition:</code>. Just use <code>if</code>, <code>else</code>.</p></li>\n<li><p>More comments are needed in logic-dense areas.</p></li>\n</ul>\n\n<p><strong>Edit, some explanations</strong></p>\n\n<p>Using a dictionary instead of if/else, instead of:</p>\n\n<pre><code>if cond_a:\n return a\nelif cond_b:\n return b\nelif cond_c:\n return c\n</code></pre>\n\n<p>create a dictionary where the conditions are the keys, and the return variables are the values:</p>\n\n<pre><code>some_dict = {cond_a: a, cond_b: b, cond_c: c}\n</code></pre>\n\n<p>then when it comes to using it, just do:</p>\n\n<pre><code>return some_dict[condition]\n</code></pre>\n\n<p>You can also add a default value for when the conditions isn't handled by the dictionary: <code>return some_dict.get(condition, default=None)</code>.</p>\n\n<p>Class instead of globals:</p>\n\n<p>The simplest example is to put the global into a class as you have done above with <code>Deck</code>:</p>\n\n<pre><code>class MyClass:\n\n def __init__(self, some_var):\n self.some_var = some_var\n</code></pre>\n\n<p>Then you can add your functions into that class as methods and they can all share <code>self.some_var</code> without putting it into the global scope.</p>\n\n<p>There is almost always a way around using globals, try to narrow down exactly what you want to use the global for. Most of the time there'll be a design pattern to handle that case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T10:24:37.733",
"Id": "417792",
"Score": "0",
"body": "These are all good ideas. Could you explain in more depth how to do some of them? Like what would be the best way to turn the large if statements into dictionaries and what would be a better way to catch invalid input? Also, what would be the best way to get rid of the globale using class wrappers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T11:20:17.837",
"Id": "417797",
"Score": "0",
"body": "I've edited my comment with some explanations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T23:35:27.870",
"Id": "417876",
"Score": "0",
"body": "I get an `int has no attribute value` error if I do for c in hand instead of for x in range(len(hand))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T23:36:08.977",
"Id": "417877",
"Score": "0",
"body": "`for c in hand:\n values.append(c.value);\n vset.add(c.value);\n suits.append(c.suit);\n all_cards.append(c)` doesn't work"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T10:20:56.470",
"Id": "215920",
"ParentId": "215896",
"Score": "7"
}
},
{
"body": "<p>In addition to what HoboProber already said in his <a href=\"https://codereview.stackexchange.com/a/215920/92478\">answer</a>, I would like to give you a little bit more feedback on the program logic itself.</p>\n\n<p>For the purpose of evaluating the selected number of random card draws you pregenerate a huge amount of card decks, which takes up a lot of memory (when I was running your code for a large number of decks, it was in the order of several GB). You then go on to operate on this large set of card decks sequentially, drawing a few cards from each set, then check them and go on to the next set.</p>\n\n<p>In reality you would usually have a single deck of cards, which you would shuffle randomly, then draw your hands, evaluate them, put them back and start all over again. I think, the same approach could be applied to your program as well. Doing it this way, you would save orders of magnitudes of memory and quite a lot of time spent on generating all the card decks. Since shuffling is already part of the program, there is no additional complexity.</p>\n\n<p>If you would go on to work on your program/simulation and would like to improve the performance further, you could look into <a href=\"https://docs.python.org/3/library/multiprocessing.html\" rel=\"nofollow noreferrer\">multiprocessing</a>. The second approach would scale quite well since you can give every worker its on card deck to operate on, minimizing the need of synchronization while keeping the memory usage on a sane level. But before thinking about this in any way, save yourself a lot of headache and have a thorough look on what other reviewers already told you on this and the previous question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T20:56:45.817",
"Id": "215957",
"ParentId": "215896",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "215920",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T02:23:10.777",
"Id": "215896",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"playing-cards"
],
"Title": "Command-Line Poker Showdown"
} | 215896 |
<p>Lots of Prim's algorithm implementations seem long, and rely on a priority queue implementation.</p>
<p>If I use an adjacency matrix I can then calculate the next item to take using functional programming in Swift.</p>
<pre><code>func prims (_ matrix : [[Int]]) {
var selected = 0
var selectedSoFar = Set<Int>()
selectedSoFar.insert( (matrix[selected].enumerated().min{ $0.element < $1.element }?.offset)! )
while selectedSoFar.count < matrix.count {
var minValue = Int.max
var minIndex = selected
var initialRow = 0
for row in selectedSoFar {
let candidateMin = matrix[row].enumerated().filter{$0.element > 0 && !selectedSoFar.contains($0.offset) }.min{ $0.element < $1.element }
if (minValue > candidateMin?.element ?? Int.max ) {
minValue = candidateMin?.element ?? Int.max
minIndex = (candidateMin?.offset) ?? 0
initialRow = row
}
}
print ("edge value \(minValue) with \(initialRow) to \(minIndex)")
selectedSoFar.insert(minIndex)
selected = (minValue)
}
}
let input = [[0,9,75,0,0],[9,0,95,19,42],[75,95,0,51,66],[0,19,51,0,31],[0,42,66,31,0]]
prims(input)
</code></pre>
<p>Essentially is there anything "wrong" with this implementation? This is not homework, my code runs correctly for the included output, I've stepped through the output with pen and paper, and I appreciate this is faster if I use an adjacency list. However the Ray Wenderlich implementation of Prims uses 7 files and >200 lines of code. Am I missing something?</p>
| [] | [
{
"body": "<blockquote>\n <p>Am I missing something?</p>\n</blockquote>\n\n<p>Each expansion of the tree visits every vertex, either as a member of <code>selectedSoFar</code> or as a candidate in <code>matrix[row]</code>. That makes the runtime <span class=\"math-container\">\\$O(n^2)\\$</span> in the number of vertices. </p>\n\n<p>An algorithm based on ordered data will tend toward <span class=\"math-container\">\\$O(n*log(n))\\$</span>. With a million vertices, that's 50 thousand times faster—the difference between an hour and six years.</p>\n\n<p>See also <a href=\"https://en.wikipedia.org/wiki/Prim%27s_algorithm#Time_complexity\" rel=\"nofollow noreferrer\">Wikipedia on Prim's</a>; there's a section on time complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T05:54:33.033",
"Id": "417747",
"Score": "0",
"body": "\"I appreciate this is faster if I use an adjacency matrix\" should have read \" appreciate this is faster if I use an adjacency list\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T06:16:34.983",
"Id": "417752",
"Score": "3",
"body": "Understood, but you're asking why it isn't done this way, and that's why. It's not slower as in \"*hey this is kind of slow*,\" it's slower as in \"*hey this was started when I was born and has yet to complete.*\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T05:15:05.997",
"Id": "215901",
"ParentId": "215897",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215901",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T02:41:26.790",
"Id": "215897",
"Score": "4",
"Tags": [
"algorithm",
"graph",
"swift"
],
"Title": "Swift Prim's algorithm"
} | 215897 |
<p>I got this question during my interview:</p>
<blockquote>
<p>Given an integer N, output an N x N spiral matrix with integers 1 through N. </p>
<p>Examples: Input: 3</p>
<p>Output: [[1, 2, 3],
[8, 9, 4],
[7, 6, 5]]</p>
<p>Input: 1</p>
<p>output: matrix filled out as a spiral [[1]]</p>
</blockquote>
<pre><code>/*PSEUDO:
rowMin = 0
rowMax = n - 1
colMin = 0
colMax = n - 1
counter = 1
matrix = []
create the matrix:
loop from 0 to n - 1
array
loop from 0 to n-1
push 0 into array
while rowMin <= rowMax and colMin <= colMax
loop on rowMin from colMin to colMax. col
matrix[rowMin][col] becomes counter++
rowMin++
loop on colMax and from rowMin to rowMax. row
matrix[row][colMax] becomes counter++
colMax--
loop on rowMax from colMax to colMin. col
matrix[rowMax][col] becomes counter++
rowMax--
loop on colMin from rowMax to rowMin. row
matrix[row][colMin] becomes counter++
colMin++
return matrix
*/
const spiralMatrix = (n) => {
const matrix = [];
let rowMin = 0,
rowMax = n - 1,
colMin = 0,
colMax = n - 1,
counter = 1;
for (let i = 0; i < n; i++) {
matrix.push(new Array(n).fill(0));
}
while (rowMin <= rowMax && colMin <= colMax) {
for (let col = colMin; col <= colMax; col++) {
matrix[rowMin][col] = counter++;
}
rowMin++;
for (let row = rowMin; row <= rowMax; row++) {
matrix[row][colMax] = counter++;
}
colMax--;
for (let col = colMax; col >= colMin; col--) {
matrix[rowMax][col] = counter++;
}
rowMax--;
for (let row = rowMax; row >= rowMin; row--) {
matrix[row][colMin] = counter++;
}
colMin++;
}
return matrix;
}
console.log(spiralMatrix(10));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T08:54:50.303",
"Id": "417783",
"Score": "0",
"body": "it would be interesting to see this problem solved without random access. Left to right, top to bottom, in the same order you'd output to a terminal."
}
] | [
{
"body": "<p>Seems mostly solid to me. I just have two small remarks:</p>\n\n<hr>\n\n<blockquote>\n<pre><code>const spiralMatrix = (n) => {\n</code></pre>\n</blockquote>\n\n<p>I'm not a big fan of using the arrow syntax here. The arrow syntax is (mostly) used for inline functions. For a \"top level\" function I'd prefer a normal, more readable (and hoisted) <code>function</code> declaration:</p>\n\n<pre><code>function spiralMatrix(n) {\n</code></pre>\n\n<p>The only disadvantage I see is that <code>const</code> prevents accidental overwriting, which I don't see as an serious problem in this case.</p>\n\n<hr>\n\n<p>And <code>.fill(0)</code> during initialization of the arrays is unnecessary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T12:12:36.297",
"Id": "215925",
"ParentId": "215902",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T05:45:34.087",
"Id": "215902",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Fill out a spiral matrix"
} | 215902 |
<p>I am looking for ways to make this code more "pythonic" and any issues with my implementation. This was designed to solve <a href="https://cryptopals.com/sets/2/challenges/10" rel="nofollow noreferrer">Crytopal's Challenge 10</a>. This challenge requires recreating the AES-CBC cipher using a library-provided AES-ECB function. <a href="https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS#5_and_PKCS#7" rel="nofollow noreferrer">PKCS7</a> padding is also used to align bytes to block boundaries.</p>
<pre><code>from Cryptodome.Cipher import AES
def xor(in1, in2):
ret = []
for i in range(0, max(len(in1), len(in2))):
ret.append(in1[i % len(in1)] ^ in2[i % len(in2)])
return bytes(ret)
def decrypt_aes_ecb(data, key):
cipher = AES.new(key, AES.MODE_ECB)
return cipher.decrypt(data)
def encrypt_aes_ecb(data, key):
cipher = AES.new(key, AES.MODE_ECB)
return cipher.encrypt(data)
def pkcs7(val, block_size=16):
remaining = block_size - len(val) % block_size
if remaining == block_size:
remaining = 16
ret = val + chr(remaining).encode() * remaining
return ret
def unpkcs7(val, block_size=16):
pad_amount = val[-1]
if pad_amount == 0:
raise Exception
for i in range(len(val) - 1, len(val) - (pad_amount + 1), -1):
if val[i] != pad_amount:
raise Exception
return val[:-pad_amount]
def decrypt_aes_cbc(data, key, iv = b'\x00' * 16, pad=True):
prev_chunk = iv
decrypted = []
for i in range(0, len(data), 16):
chunk = data[i : i + 16]
decrypted += xor(decrypt_aes_ecb(chunk, key), prev_chunk)
prev_chunk = chunk
if pad:
return unpkcs7(bytes(decrypted))
return bytes(decrypted)
def encrypt_aes_cbc(data, key, iv = b'\x00' * 16, pad=True):
if pad:
padded = pkcs7(data)
else:
padded = data
prev_chunk = iv
encrypted = []
for i in range(0, len(padded), 16):
chunk = padded[i : i + 16]
encrypted_block = encrypt_aes_ecb(xor(chunk, prev_chunk), key)
encrypted += encrypted_block
prev_chunk = encrypted_block
return bytes(encrypted)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T15:45:28.967",
"Id": "417822",
"Score": "0",
"body": "Links can rot. [Please include a description of the challenge here in your question.](//codereview.meta.stackexchange.com/q/1993)"
}
] | [
{
"body": "<ul>\n<li><p>Try to follow PEP8. Just a few little things like when assigning defaults to arguments don't put spaces around the <code>=</code>; two spaces between functions and imports; <code>[i : i + 16]</code> -> <code>[i: i + 16]</code>. Very minor stuff but adds up over a larger piece of code.</p></li>\n<li><p>Avoid assigning variables to small bits of logic if they're only going to be used once. e.g.:</p>\n\n<pre><code>ret = val + chr(remaining).encode() * remaining\nreturn ret\n</code></pre>\n\n<p>Could become:</p>\n\n<pre><code>return val + chr(remaining).encode() * remaining\n</code></pre></li>\n<li><p>Your names could be improved for clarity; avoid using vague names like key, var, data, etc.</p></li>\n<li><p>I like ternary operators so I'd change <code>encrypt_aes_cbc()</code> to:</p>\n\n<pre><code>padded = pkcs7(data) if pad else data\n</code></pre>\n\n<p>You can do something similar in <code>decrypt_aes_cbc()</code> with your returns.</p></li>\n<li><p>In fact, I'd extract the second part of the function to a generator and call it in <code>encrpyt_aes_cbc()</code>. By which I mean:</p>\n\n<pre><code>def gen_encrypted(key, iv):\n \"\"\"Maybe give this function a better name!\"\"\"\n\n for i in range(0, len(padded), 16): \n ...\n yield encrypted\n</code></pre>\n\n<p>Then change the second half of <code>encrypt_aes_cbc()</code> to call that generator. This nicely compartmentalises your code, removes the need for the <code>encrypted</code> list and should be faster. I can explain this more thoroughly if you're confused about <code>yield</code>. </p></li>\n<li><p>Your argument <code>block_size=16</code> in <code>unpkcs7</code> is not used.</p></li>\n<li><p>Your indentation is off in <code>pkcs7</code>.</p></li>\n<li><p>Try to be specific when raising exceptions. What error exactly are you catching? Exceptions also takes a string argument so you can explain the problem. e.g.:</p>\n\n<pre><code>raise IndexError('This is not a valid position in some_list')\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T21:09:57.170",
"Id": "417869",
"Score": "0",
"body": "Especially the comment on using specific exceptions and error messages is enormously important! Nothing is more annoying than having to read error messages (if any) that tell you nothing apart from \"It's broken!\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T11:55:12.313",
"Id": "215924",
"ParentId": "215904",
"Score": "6"
}
},
{
"body": "<p>In addition to Hobo's good answer, you can simplify the <code>xor</code> function</p>\n\n<blockquote>\n<pre><code>def xor(in1, in2):\n ret = []\n for i in range(0, max(len(in1), len(in2))):\n ret.append(in1[i % len(in1)] ^ in2[i % len(in2)])\n return bytes(ret)\n</code></pre>\n</blockquote>\n\n<p>You don't need the <code>0</code> in the range's first element because it will automatically start at <code>0</code>, secondly <code>bytes</code> will accept any iterable so you can feed it a comprehension</p>\n\n<pre><code>def xor(in1, in2):\n return bytes(in1[i % len(in1)] ^ in2[i % len(in2)] for i in range(max(len(in1), len(in2)))\n</code></pre>\n\n<p>You could also use <code>cycle</code> from the <code>itertools</code> module in combination with <code>zip</code></p>\n\n<pre><code>from itertools import cycle\n\ndef xor2(in1, in2):\n value, repeater = (in1, in2) if len(in1) > len(in2) else (in2, in1)\n return bytes(v ^ r for v, r in zip(value, cycle(repeater)))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T09:24:22.897",
"Id": "215986",
"ParentId": "215904",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215924",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T06:32:13.523",
"Id": "215904",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"reinventing-the-wheel",
"cryptography"
],
"Title": "Python AES-CBC implementation using AES-ECB"
} | 215904 |
<p>While trying to discover a way to calculate the digits of Pi faster with the <a href="https://en.wikipedia.org/wiki/Leibniz_formula_for_%CF%80" rel="nofollow noreferrer">Leibniz formula for Pi</a>, I noticed that, if I took two consecuent numbers in the series, and calculate their average, I would get a number incredibly closer to Pi compared to these other two numbers, and furthermore, if I took another consecuent two of these averaged values and, redundantly, average them, again the result would be closer to Pi.</p>
<p><strong>Explanation (Skip this part if you want to see the code)</strong></p>
<p>To understand it more, its like a tree of averages, where the original series is at the bottom, then, every two consecuent terms of the series will have a <strong>child</strong>, which is their averages. These <em>childs</em> will make another infinite series that converges faster to Pi in the same manner the Leibniz series do(that means bouncing up and down from Pi until slowly stopping into it, like a guitar chord resonating until it stops), so for these childs too we'll calculate the average of each two consecuent terms, and make another <em>child series</em> out of those new <em>childs</em>. This process will repeat until the final series results in only having one final child at the top of the tree, which means we can't average anymore since we need two terms to do so, meaning that that last child is the closest to Pi that this algorithm, if it can be said that way, can get.</p>
<p><strong>The program</strong></p>
<p>For this purpose I have made the following program, it functions with two threads called PiLoopThread and DisplayThread (named that way after my C++ Leibniz series calculator intent), in which the first is in charge of calculating Pi and its averages subseries, and the other of displaying information about the calculations and basically what's going on from time to time. At the start the program first sets up the UI, and then starts the two before mentioned threads.</p>
<p>The methods where the magic happens are <em>nextCicle()</em> and <em>updateAverages()</em>.</p>
<ul>
<li><em>nextCicle()</em> is in charge of updating <em>PI</em>, <em>LastPI</em> (for calculating the average), and the cicle <em>Count</em>.</li>
<li><em>updateAverages()</em> updates the averages tree by using an ArrayList of all the previous "top-most childs". It first appends the average of PI and LastPI at the end of the ArrayList ( i = listSize - 1 ), then if there is a previous element from that element ( i--; i >= 0 ), it becomes the average of those both elements (list.set( i , average( list.get(i), list.get(i+1) ) )), and that continues until there are no more previous elements to reaverage ( i >= 0 equals false ). That's made that way so the BigDecimals to store during the life of the program are the minimum.</li>
</ul>
<p><strong>The Problem</strong></p>
<p>What I want to know is if my code is precise and can perform relatively well. Since this is the first time I'm using BigDecimals, I'm not very confident in that I've used them well and that my program will use too much memory, so a review on them would be nice :)</p>
<p>All the important code is in the BDFuncs.java and, of course, Vars.java :</p>
<p><strong>Vars.java</strong></p>
<pre><code>package picalculator;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
public class Vars {
public static final BigDecimal ZERO = new BigDecimal("0" );
public static final BigDecimal ONE = new BigDecimal("1");
public static final BigDecimal TWO = new BigDecimal("2");
public static final BigDecimal FOUR = new BigDecimal("4");
public static BigDecimal LastPI = ZERO.plus();
public static BigDecimal PI = new BigDecimal( "0.0", MathContext.DECIMAL128 );
public static BigDecimal Count = new BigDecimal("0");
public static ArrayList<BigDecimal> PIAvgs = new ArrayList<>( 1000000 );
public static boolean shouldStop = false;
public static final Object piLock = new Object();
}
</code></pre>
<p><strong>BDFuncs.java</strong></p>
<p><em>-Note: nextCicle() is executed in a loop that looks like the following pseudocode: "while !shouldStop do nextCicle() and then sleep for 1ms".</em></p>
<pre><code>package picalculator;
import java.math.BigDecimal;
import java.math.MathContext;
import static picalculator.Vars.*;
public class BDFuncs {
// The magic happens here
// This function calculates the next PI in the series, as well as the actual child series while creating other news (see updateAverage()).
public static void nextCicle() {
synchronized ( piLock ) {
LastPI = PI.plus();
if ( shouldSubstract() ) PI = PI.subtract( getCicleTerm() );
else PI = PI.add( getCicleTerm() );
updateAverage();
Count = Count.add( ONE );
}
}
private static BigDecimal getCicleTerm() {
return ONE.divide( Count.multiply( TWO ).add( ONE ), MathContext.DECIMAL128 );
}
private static boolean shouldSubstract() {
if ( Count.remainder( TWO ).compareTo( ONE ) == 0 ) return true;
else return false;
}
// This function works by calculating ONLY the averages at the last side of the tree.
// It first calcles the last average of the first child series, and then using that
// average and the last average of the same child series(if any), calculates its average
// and sets it as the second child series' last child, repeating so until it reaches the
// top of the tree, or in this case, while the index is more or equal than 0.
private static void updateAverage() {
PIAvgs.add( average( LastPI, PI ) );
for ( int i = PIAvgs.size() - 2; i >= 0; i-- ) {
PIAvgs.set( i, average( PIAvgs.get( i ) , PIAvgs.get( i + 1 ) ) );
}
}
private static BigDecimal average( BigDecimal bd1, BigDecimal bd2 ) {
return bd1.add( bd2 ).divide( TWO );
}
public static BigDecimal[] getData() {
BigDecimal[] tempArr = new BigDecimal[3];
synchronized ( piLock ) {
tempArr[0] = PI.plus();
tempArr[1] = ( PIAvgs.isEmpty() ? ZERO : PIAvgs.get(0) );
tempArr[2] = Count.plus();
}
return tempArr;
}
}
</code></pre>
<p>Here is a screenshot of the working program:</p>
<p><a href="https://i.stack.imgur.com/1rba1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1rba1.png" alt="PiCalculator"></a></p>
<p>As you can see, it managed to get Pi with just averaging right up to the 34th digit in just 120 Leibniz term calculations that just took less than 1 sec, so, yeah, wow.</p>
<p>It just gets up to there though since apparently BigDecimal can only get up to 34 digits of exact precision using MathContext.DECIMAL128 :P</p>
<p>You can download the jar from <a href="http://www.mediafire.com/file/j4j6841d805r21q/PiCalculator.jar/file" rel="nofollow noreferrer">here</a>.</p>
<p>If you want the full source code ( plus the .jar ) you can download it from <a href="http://www.mediafire.com/file/unm970zifi5b1o7/PiCalculator_source.zip/file" rel="nofollow noreferrer">here</a> too for the NetBeans IDE.</p>
| [] | [
{
"body": "<blockquote>\n<pre><code>public class Vars {\n\n ...\n\n public static BigDecimal LastPI = ZERO.plus();\n public static BigDecimal PI = new BigDecimal( \"0.0\", MathContext.DECIMAL128 );\n public static BigDecimal Count = new BigDecimal(\"0\");\n\n public static ArrayList<BigDecimal> PIAvgs = new ArrayList<>( 1000000 );\n\n public static boolean shouldStop = false;\n</code></pre>\n</blockquote>\n\n<p>Why?</p>\n\n<p>Firstly, why are the variables deliberately placed in a different scope to the code which operates on them?</p>\n\n<p>Secondly, why are they <code>static</code>? For that matter, why is everything in <code>BDFuncs</code> static?</p>\n\n<p>Thirdly, why the inconsistency in the capitalisation? <code>ALL_CAPS</code> in Java convention is reserved for constants; other fields should be in <code>lowerCamelCase</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static void nextCicle() {\n</code></pre>\n</blockquote>\n\n<p>FWIW the correct spelling is <em>cycle</em>.</p>\n\n<blockquote>\n<pre><code> synchronized ( piLock ) {\n LastPI = PI.plus();\n</code></pre>\n</blockquote>\n\n<p>Why <code>.plus()</code>? That method literally does nothing.</p>\n\n<blockquote>\n<pre><code> if ( shouldSubstract() ) PI = PI.subtract( getCicleTerm() );\n else PI = PI.add( getCicleTerm() );\n</code></pre>\n</blockquote>\n\n<p>Why doesn't the term include its sign, so that you always add? That would be more mathematically coherent and would make it easier to understand the code because it would remove the requirement to call the methods in the right order.</p>\n\n<blockquote>\n<pre><code> updateAverage();\n Count = Count.add( ONE );\n</code></pre>\n</blockquote>\n\n<p>This seems like the appropriate place to ask why <code>Count</code> is a <code>BigDecimal</code> rather than just an <code>int</code>.</p>\n\n<hr>\n\n<p>If you want to minimise the errors then as a rule of thumb you should add the terms in increasing size, i.e. starting with the last one. This is a problem for iterative refinement: serious calculation would not just iterative refinement.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private static void updateAverage() {\n PIAvgs.add( average( LastPI, PI ) );\n for ( int i = PIAvgs.size() - 2; i >= 0; i-- ) {\n PIAvgs.set( i, average( PIAvgs.get( i ) , PIAvgs.get( i + 1 ) ) );\n }\n }\n</code></pre>\n</blockquote>\n\n<p>It's not clear to me from reading the code that it actually has the same tree structure as defined in the question. Comments giving the invariants might clarify this - or maybe it is not, in fact, the case.</p>\n\n<hr>\n\n<p>Finally, let me propose some reading for you:</p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Series_acceleration#Euler's_transform\" rel=\"nofollow noreferrer\">Euler's transform</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Van_Wijngaarden_transformation\" rel=\"nofollow noreferrer\">Van Wijngaarden's improvement</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T16:51:22.020",
"Id": "417837",
"Score": "0",
"body": "The Van Wijngaarden's Transform seems to be exactly what I'm doing, I'll dive into it in more detail. Sorry for my malformed and sometimes incoherent code, it's the first time I've used Java in a while and also the first time I used BigDecimals. I'm not exactly a pro when it comes to coding, that's why I was coming to this site, to see if I was heading my code the right way, but reading and tasting the answer policy of this site suggest there might be a better Stack Exchange site for that. Anyways, thanks for the review, I'll update my code and the question if possible :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T19:36:04.240",
"Id": "417857",
"Score": "0",
"body": "The subtle difference is that van Wijngaarden gets better results by not carrying it out fully. Don't update the question: the changes will be rolled back. However, once you've considered all the feedback received and applied that which you agree with, you can post a new question. See the meta FAQ on [options for follow-ups](https://codereview.meta.stackexchange.com/q/1763/1402)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T11:12:39.823",
"Id": "215923",
"ParentId": "215905",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "215923",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T06:40:48.733",
"Id": "215905",
"Score": "2",
"Tags": [
"java",
"numerical-methods"
],
"Title": "Java Pi Calculation using an Averaged-Leibniz formula"
} | 215905 |
<p>I'm currently reading Mastering Perl for Bioinformatics; I'm using the book for learning bioinformatics while implementing the code in C++. I came across a situation where I needed to use the minimum of three numbers, which the author did using a function call <code>min3</code> which, as expected, returns the minimum of three numbers.</p>
<p>Rather than using the canonical C-style macro <code>#define MIN(a,b) ...</code>, I wanted to try and write more idiomatic C++, first by staying away from macros, and second by using templates to write type-safe, variadic <code>Min</code> and <code>Max</code> functions.</p>
<pre><code>namespace Math
{
template <typename T1, typename T2>
constexpr inline auto Max(T1 a, T2 b) noexcept
{
return (a > b) ? a : b;
}
template <typename T1, typename T2, typename... Types>
constexpr inline auto Max(T1 a, T2 b, Types... args) noexcept
{
return Max(a, Max(b, args...));
}
template <typename T1, typename T2>
constexpr inline auto Min(T1 a, T2 b) noexcept
{
return (a < b) ? a : b;
}
template <typename T1, typename T2, typename... Types>
constexpr inline auto Min(T1 a, T2 b, Types... args) noexcept
{
return Min(a, Min(b, args...));
}
} // namespace Math
</code></pre>
<p>Example usage:</p>
<pre><code>std::cout << Math::Max(1,2) << std::cout.widen('\n');
std::cout << Math::Min(3,8,4,3,2) << std::cout.widen('\n');
</code></pre>
<p>Output:</p>
<pre><code>2
2
</code></pre>
<p>I'm using <code>std::cout.widen('\n')</code> so as to not call <code>std::fflush()</code> on each call to <code>std::endl</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T07:48:41.263",
"Id": "417773",
"Score": "0",
"body": "This happens to be extremely close to [this question](https://codereview.stackexchange.com/questions/215471/min-function-accepting-varying-number-of-arguments-in-c17). Which assumes C++17 though, maybe you could clarify whether C++17 is available to you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T10:38:39.817",
"Id": "417796",
"Score": "2",
"body": "There's a small bug in your code. `min(a, b)` should return `a` if `a == b`; it currently returns `b`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T11:26:10.107",
"Id": "417923",
"Score": "0",
"body": "@lubgr I completely missed that question when I was verifying this wasn't a repost. I can't use C++17 in production yet though, so I suppose I got lucky"
}
] | [
{
"body": "<p>Your implementation will work nicely for integers, however, it might be doing a lot of copies which could hurt you for more expensive types.</p>\n\n<p>An edge case that might sometimes be useful in case of calling this via a template: the min/max of 1 number.</p>\n\n<p>Your noexcept is wrong in case of throwing copy constructors. You could change this to <code>noexcept(std::is_nothrow_copy_constructable<T>)</code> or fix the remark above and prevent copies.</p>\n\n<p>Looking at the template arguments, you do allow T1 and T2 to be of a different type. I don't see much added value in that, as you would get an obscure error about the <code>?:</code> operator.</p>\n\n<p>And to end with a positive note: I really like the constexpr. This allows you to write a unit test as a static_assert.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T11:30:33.660",
"Id": "417925",
"Score": "0",
"body": "I thought allowing for different types might be handy in case you had to compare a long and a double, or something, but I do agree it doesn't seem great in retrospect. I really appreciate the feedback, this gave me a lot to think about"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T07:51:00.530",
"Id": "215912",
"ParentId": "215911",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "215912",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T07:30:41.697",
"Id": "215911",
"Score": "2",
"Tags": [
"c++",
"recursion",
"template",
"variadic"
],
"Title": "Replacing MIN and MAX macros with type-safe, recursive templates of variable arity"
} | 215911 |
<p>I have the following simple function:</p>
<pre><code>__device__
mirror(int index , int lB, int uB)
{
while(index < lB || index >= uB)
{
if(index < lB) {
index = lB + (lB-index);
}
if(index >= uB) {
index = uB-1 -(index-uB);
}
}
return index;
}
</code></pre>
<p>Assume <code>lb <= uB</code>.</p>
<p>It is used for every index to give it a mirror border behaviour and make sure the result is a valid index.</p>
<p>Are there ways to improve this, with or without changing the result for indices outside <code>[lB-d,uB+d)</code>, where <code>d >= uB-lB</code>.</p>
<p><code>mirror(i,lB,uB)</code> has to be in <code>[lB,uB)</code> of course.</p>
<p>What are concerns for performance? </p>
<ul>
<li>this function is called very often</li>
<li>it is called from an kernel (cuda things relevant? thread divergence?)</li>
</ul>
<p>Are there possible improvments for the special case <code>lB == 0</code>?</p>
<p>EDIT: added this small test example</p>
<pre><code>__global__
void driver(unsigned char* img_dest, unsigned char* img_src, int width, int height)
{
int x = blockIdx.x*blockDim.x+threadIdx.x;
int y = blockIdx.y*blockDim.y+threadIdx.y;
if(x >= 0 && x < width && y >= 0 && y < height)
{
int x_src = mirror(x*2-width/2,0,width);
assert(x_src >= 0);
assert(x_src < width);
int y_src = mirror(y+x,0,height);
assert(y_src >= 0);
assert(y_src < height);
img_dest[x+y*width] = img_src[x_src + y_src*width];
}
}
// let the images be gray images, with no pitch.
void callDriver(unsigned char* img_dest, unsigned char* img_src, int width,int height)
{
dim3 block(16,16);
dim3 grid((width+block.x-1)/block.x,(height+block.y-1)/block.y);
driver<<<grid,block>>>(img_dest,img_src,width,height);
cudaDeviceSynchronize();
}
main()
{
int width = 512;
int height = 256;
unsigned char* img_dest;
cudaMalloc(&img_dest,width*height);
unsigned char* img_src;
cudaMalloc(&img_src,width*height);
callDriver(img_dest,img_src,width,height);
}
</code></pre>
<p>My use case is similar to the driver example:
I have functions deforming where I would have to load pixel that would lay outside of the defined region. To provide meaningful values I want to define them by mirroring at the borders. </p>
<p>My use case are distortion, and linear filters. In both cases I have to use values for pixels that are not defined in the image. While in the case of linear filters, there are other possible solutions (starting extra kernel for border), I decided to work with one kernel for this time. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T09:37:43.193",
"Id": "417784",
"Score": "2",
"body": "Would you be able to also post a small driver program that shows a few cases for expected output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T09:43:08.840",
"Id": "417786",
"Score": "1",
"body": "Can `index` be less than zero, too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T09:44:38.147",
"Id": "417787",
"Score": "0",
"body": "@lubgr yes it can be less than zero."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T09:48:51.930",
"Id": "417789",
"Score": "0",
"body": "You've made a good start, but would it be possible to provide more context? How is this used? When is this used? Why the `while` approach, especially considering this is CUDA?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T10:22:03.243",
"Id": "417791",
"Score": "0",
"body": "@Mast does the edit answer your questions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T10:29:24.890",
"Id": "417794",
"Score": "1",
"body": "I haven't thought this through but I feel like mirroring is meaningful only in certain circumstances. If, for instance, `index` can have any values between `INT_MIN` and `INT_MAX`, but `lB` is `0` and `uB` is `10`, then mirroring is a waste of time. Or if `lB` is very high and `index` very low, then we have an overflow that would certainly deprive mirroring of any sense. Do we know anything about those values besides `lB <= uB`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T11:42:51.243",
"Id": "417800",
"Score": "0",
"body": "@papagaga the usall case is `lb == 0` und `ub < 10000` (4096 is the biggest that I encountered). `index` is the result some distortion applyed to a value between `lB` and `uB`. Good point with the overflow."
}
] | [
{
"body": "<pre><code>__device__\nmirror(int index , int lB, int uB)\n</code></pre>\n\n<p>You've got an extra space before the first comma, and I think you're missing the function's return type entirely. You should <em>always</em> compile your code with <code>-Wall</code> and fix <em>all</em> the warnings before posting it (or before running it). There's no point in shipping code with bugs.</p>\n\n<p>Similarly funky whitespace on this line:</p>\n\n<pre><code> index = uB-1 -(index-uB);\n</code></pre>\n\n<hr>\n\n<p>Anyway, if you're looking to speed up a piece of code with loops in it, your first thought should be, \"How do I get rid of these loops?\"</p>\n\n<p>Consider that after you \"mirror\" <code>index</code> off of both boundaries, you'll simply have reduced its overall value by <code>2*(uB - lB)</code>. Proof:</p>\n\n<pre><code>index = uB-1 - (index-uB);\nindex = lB + (lB-index);\n</code></pre>\n\n<p>means</p>\n\n<pre><code>index = lB + lB - (uB - 1 - index + uB);\n</code></pre>\n\n<p>means</p>\n\n<pre><code>index = 2*lB - 2*uB + 1 + index;\n</code></pre>\n\n<p>means</p>\n\n<pre><code>index = index - (2*(uB - lB) - 1);\n</code></pre>\n\n<p>Hmm... I see you have an extra <code>-1</code> in there. Was that intentional? Let's see if we can reproduce it in a test case.</p>\n\n<pre><code>assert(mirror(0, 0, 3) == 0);\nassert(mirror(1, 0, 3) == 1);\nassert(mirror(2, 0, 3) == 2);\nassert(mirror(3, 0, 3) == 2);\nassert(mirror(4, 0, 3) == 1);\nassert(mirror(5, 0, 3) == 0);\nassert(mirror(6, 0, 3) == 1);\nassert(mirror(7, 0, 3) == 2);\nassert(mirror(8, 0, 3) == 2);\n</code></pre>\n\n<p>Yep, the two boundaries behave differently! The moral of the story is: <em>Always test your code.</em></p>\n\n<p>Now that we know how the code behaves (which, honestly, probably <em>isn't</em> how you <em>intended</em> it to behave) — we can modify it safe in the knowledge that we won't introduce bugs. We just have to keep all our test cases passing. (Of course we should write some test cases with negative inputs, too.)</p>\n\n<p>Any time you have code with repeated addition, you should think about whether it can be replaced with multiplication; and any time you have repeated subtraction, you should think about whether it can be replaced with division (which is to say, modulus).</p>\n\n<pre><code>int mirror(int index, int lB, int uB) {\n int n = uB - lB;\n int period = 2*n - 1; // the pattern repeats with this period\n int mod_p = (index - lB) % period;\n if (mod_p < n) {\n return lB + mod_p;\n } else {\n return uB - 1 - (mod_p - n);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T09:29:05.017",
"Id": "417904",
"Score": "0",
"body": "thanks for the good advice. Dividing is not cheap on gpu, therefor I added an check, that the index is not in the interval to avoid it when possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T16:34:03.050",
"Id": "417958",
"Score": "0",
"body": "You might also consider special-casing when `period` is a power of 2, which means that `x % period` is `x & mask` for some integer `mask`. (Except that of course `period` is never a power of 2 with your current code! I still suspect that that `-1` is a bug.) For the quite real benefits of branching around an expensive division, see also [Chandler Carruth's keynote from CppCon 2015, \"Tuning C++.\"](https://www.youtube.com/watch?v=nXaxk27zwlk&t=55m30s)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T04:01:35.533",
"Id": "215970",
"ParentId": "215915",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "215970",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T08:37:19.730",
"Id": "215915",
"Score": "1",
"Tags": [
"c++",
"cuda"
],
"Title": "Mirrors number at borders of interval, untill it lays in the interval"
} | 215915 |
<p>For the past months I have been learning plain javascript without jquery or libraries/frameworks. So now, when I develop a website, I want to write all of the JS code by myself to fully understand what is going on and to learn the language.</p>
<p>So far so good. I tried to implement a slideshow with a fading background image. I had to learn, that although it sounds really simple and straightforward, there are so many things that you have to keep in mind.</p>
<p>For example: how do you stop the slideshow when it is out of view. Otherwise your content below the slideshow might jump up and down because the slides have different heights.</p>
<p>I have realized that I didn't now what I was doing, and that I don't know how to "design" such functionalites. I get "something somehow" to work.</p>
<p>What I am asking for is advice on structuring code for a slideshow like this. Any advice would be gratefully received. Here is a link to the current version of the page. <a href="http://jugelt-kk.de/2019/#eins" rel="nofollow noreferrer">http://jugelt-kk.de/2019/#eins</a></p>
<p>And some example code:</p>
<pre><code>function topicsSlider(){
numberTopics();
dotOnClick();
iconOnClick();
}
function showNextTopic(){
// Get index of current active topic
let currentActive = document.querySelector(".topic.is-active");
let currentIndex = parseInt(currentActive.dataset.number);
let nextIndex = currentIndex + 1;
setHeightOfTopicsContainer(getHeightOfActiveTopic(currentActive) + "px")
let refreshInterval = setInterval(function(){
currentActive.classList.remove("is-active");
topics.forEach( (topic, i) => {
if(topic.dataset.number == nextIndex){
// Add active class to icon
topic.classList.add("is-active");
setHeightOfTopicsContainer(getHeightOfActiveTopic(topic) + "px")
} else{
// Remove active class from icon
topic.classList.remove("is-active");
}
});
dots.forEach( (dot, i) => {
if(dot.dataset.number == nextIndex){
// Add active class to icon
dot.classList.add("is-active");
} else{
// Remove active class from icon
dot.classList.remove("is-active");
}
});
icons.forEach( (icon, i) => {
if(icon.dataset.number == nextIndex){
// Add active class to icon
icon.classList.add("is-active");
} else{
// Remove active class from icon
icon.classList.remove("is-active");
}
});
setBackgroundImage(nextIndex)
nextIndex++;
if(nextIndex > getTopicsCount() ){
nextIndex = 1;
}
}, 3000)
icons.forEach( icon => {
icon.addEventListener("click", () => {
clearInterval(refreshInterval)
});
});
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T18:16:22.960",
"Id": "418596",
"Score": "2",
"body": "Welcome to Code Review! Can you add all the code to be reviewed, more than just the sample code? Otherwise we would be guessing at what some of those functions do... and if you can include the HTML that would be good. Refer to [this meta answer](https://codereview.meta.stackexchange.com/a/217/120114) as well as the others below it..."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T10:12:06.123",
"Id": "215919",
"Score": "4",
"Tags": [
"javascript",
"beginner",
"html",
"animation",
"dom"
],
"Title": "Fullscreen slideshow with fading background"
} | 215919 |
<h2>Problem description:</h2>
<blockquote>
<p>Molly wants to purchase laptops for her school. Find out how many laptops she can purchase by comparing the vendors available.<br>
Each vendor sells the laptops in batches, with a quantity identifying how many laptops on each batch, and a cost for the whole batch.
Sample input: <code>50 [20,19] [24,20]</code>
That means Molly has 50 dollars to spend. The first vendor has 20 laptops per batch and each batch costs 24 dollars. The second vendor has 19 laptops per batch and each batch costs 20 dollars.<br>
The possible answers are 40 and 38. If she buys from the first vendor, she will spend 48 dollars (24 * 2) and since she's buying 2 batches the total quantity is 40 (20 * 2).<br>
If however she would buy from the second vendor, the maximum quantity would be 38, since each batch has 19 laptops and she'd run out of money after the second batch.<br>
The final answer is then 40, since 40 is higher than 38.<br>
This seems similar to the Knapsack problem. </p>
</blockquote>
<p>My solution is listed below. The permute method is there to generate the possible permutations between the indices. For instance if we have 3 items in the input array the permutations are:<br>
012 021 102 120 201 210 </p>
<pre><code>import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.stream.IntStream;
public class ShoppingBudget {
public static void main(String[] args) {
ShoppingBudget sb = new ShoppingBudget();
assertEquals(40, sb.budgetShopping(50, List.of(20, 19), List.of(24, 20)));
assertEquals(20, sb.budgetShopping(4, List.of(10), List.of(2)));
assertEquals(0, sb.budgetShopping(1, List.of(10), List.of(2)));
assertEquals(41, sb.budgetShopping(50, List.of(20, 1), List.of(24, 2)));
}
private void permute(int start, int moneyAvailable, int[] inputIndices,
List<Integer> budgetQuantities, List<Integer> budgetCosts, MaxQuantity maxQuantity) {
if (start == inputIndices.length) { // base case
int possibleMax = findSolution(inputIndices, moneyAvailable, budgetQuantities, budgetCosts);
maxQuantity.value = Math.max(maxQuantity.value, possibleMax);
return;
}
for (int i = start; i < inputIndices.length; i++) {
// swapping
int temp = inputIndices[i];
inputIndices[i] = inputIndices[start];
inputIndices[start] = temp;
// swap(input[i], input[start]);
permute(start + 1, moneyAvailable, inputIndices, budgetQuantities, budgetCosts, maxQuantity);
// swap(input[i],input[start]);
int temp2 = inputIndices[i];
inputIndices[i] = inputIndices[start];
inputIndices[start] = temp2;
}
}
private int findSolution(int[] inputIndices, int moneyAvailable,
List<Integer> budgetQuantities, List<Integer> budgetCosts) {
int remaining = moneyAvailable;
int counter = 0;
for (int index : inputIndices) {
if (remaining == 0) {
break;
}
int quantity = budgetQuantities.get(index);
int cost = budgetCosts.get(index);
if (cost <= remaining) {
int howManyToBuy = remaining / cost;
counter += howManyToBuy * quantity;
remaining -= (howManyToBuy * cost);
}
}
return counter;
}
private int budgetShopping(int n, List<Integer> budgetQuantities,
List<Integer> budgetCosts) {
int[] inputIndices = IntStream.rangeClosed(0, budgetQuantities.size() - 1).toArray();
MaxQuantity maxQuantity = new MaxQuantity();
maxQuantity.value = Integer.MIN_VALUE;
permute(0, n, inputIndices, budgetQuantities, budgetCosts, maxQuantity);
return maxQuantity.value;
}
}
class MaxQuantity {
int value;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T17:14:05.303",
"Id": "419364",
"Score": "0",
"body": "Request for Clarification: what is the point of `permute()` ? I see what is DOES (i.e. compute the permutations of an ordered sequence) but what I don't understand is the reason behind its use. **Is it required by the problem** because it isn't in the description...? **Do you believe It is required to solve completely?** I don't believe that is the case"
}
] | [
{
"body": "<p>My understanding of the problem:</p>\n\n<p>You are provided three values:</p>\n\n<ol>\n<li><p>A budget(the amount of funds you can spend)</p></li>\n<li><p>A List of Vendor Batch Sizes</p></li>\n<li><p>A List of Vendor Batch Prices</p></li>\n</ol>\n\n<p><strong>Promises/Assumptions</strong>: the items 2 & 3(the lists) correspond such that for Vendor i, the vendors batch size and price can be found at List.get(i)</p>\n\n<p>NOTE: Your code has a hard-coded assumption that the two lists (budgetQuantities and budgetCosts) are the same size, or at least you never check that this is true or otherwise enforce this requirement.</p>\n\n<p><strong>Goal:</strong> determine the maximum affordable quantity based on Vendor and budget information.</p>\n\n<hr>\n\n<p>There seems to be <em>some</em> superfluous code going on here, so I will try to address that first\n<hr>\n<strong>Inner Class <code>MaxQuantity</code></strong></p>\n\n<p>There really isn't any reason to use this. It has only one use: to interact with the internal <code>int value</code>. As both the class and value are public, I can access all the way through: <code>shoppingBudget.MaxQuantity.value</code>. This is generally considered bad. As the class is in all cases just an int, it can be replaced with an internal variable, <code>private int maxQuantity</code></p>\n\n<p>suggesting removal</p>\n\n<p><hr>\n<strong>The permute function</strong></p>\n\n<p><s>As mentioned in my comment, this function seems entirely pointless as the problem does not involve permutations; The information is linear in nature, as there is no \"mix and match\" (i.e. permutation) of Vendor Information (budgetQuantities and budgetCosts) </p>\n\n<p>suggesting removal</s></p>\n\n<p><strong>Update</strong>\nI appreciate your use of recursion in your permute function, but its a tad confusing. The second set of swapping seems pointless, as by the time you reach it you are simply propagating back up the recursion tree, swapping indeces that we no longer use.</p>\n\n<p>I looked for similar permutation implementations and found <a href=\"https://codereview.stackexchange.com/questions/11598/permutations-of-a-list-of-numbers+\">this well designed permutation util</a>, which I used for comparison testing of your permutation method. </p>\n\n<p><hr>\n<strong>IntStream</strong>\n<s>There really isn't a need to create an int[] for indices like this. I see it is mostly used in the permute() function, which I have suggested removing, so I will likewise suggest removing this. With a linear solution, it is much easier to create a single int index and increment it as we iterate through the lists, rather than creating an int for every position from 0 to budgetQuantities,size()-1 (the increment approach is also less computationally expensive, especially where memory is concerned)</s></p>\n\n<p><strong>Update</strong> I had to use this in my rework, definitely shouldn't remove</p>\n\n<p><hr>\n<code>maxQuantity.value = Integer.MIN_VALUE;</code></p>\n\n<p>Integer.MIN_VALUE is usually a good initial value for a maximum. However, this is not the true minimum of the problem. The absolute minimum items you can purchase is 0, so it makes more sense to initialize your globalMaximum to 0: <code>private int globalMaximum=0;</code>\n<hr>\n<strong>UPDATED</strong></p>\n\n<p><strong>findSolution is NOT broken</strong></p>\n\n<p><s>There is a hole in the logic of your findSolution method. You seem to have written your code with the intent that this method will be called many times, and each result will be compared with the global max (based on your use of <code>maxQuantity.value = Math.max(maxQuantity.value, possibleMax);</code> in permute)</p>\n\n<p>However, this method runs across all vendors. Because of this, your int remaining and counter should be inside your for loop, with an <code>int localMaximumToReturn</code> where counter is currently.</p>\n\n<p>To explain further: your current findSolution forEach loop represents each Possible Interaction between Molly and one Vendor, so both the money available and the total number of computers she can buy per transaction are independent. However, in the above code, <strong>each loop is interacting with the same funds</strong>, which will introduce severe error.</p>\n\n<p>Example: I ran in debug with breakpoints inside the findSolution method, outside the forEach loop, with the following information:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>moneyAvailable: 50\nbudgetQuantities: {20,19}\nbudgetCosts: {24,20}\n</code></pre>\n\n<p>Stepping through, the first loop correctly computes that howManyToBut is 2, meaning she can buy 40 computers for 48 dollars. <strong>Then you set remaining to 2 with remaining -= 48</strong></p>\n\n<p>This means for the next loop, we get a cost of 20, <strong>which is now greater than our remaining 2 so the second cost/quantity maximum is never checked</strong></p>\n\n<p>We have technically hit each index, so we leave the loop and return the counter 40. While this IS the correct answer, we got here by false means. If you switch the order of items in your lists for the first assert, you should see a return of 38, which will break your assertEqual\n<hr>\n<strong>It is at this point I see the point of permute</strong> in that it was scrambling your orders. Since your findSolution would only ever succeed at checking the first index, permute scrambles your orders so that each item gets a shot at being first, so each possible results is compared with the globalMax. <strong>While this works, it is incredibly backward, and buggy</strong> I highly recommend fixing this bug in findSolution, and remove the no longer needed permute()</s></p>\n\n<hr>\n\n<p>With superfluous code removed you should end up with something similar to:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class ShoppingBudget {\n int globalMax;\n\n public int budgetShopping(int budget, List<Integer> batchSizes, List<Integer> batchCosts) {\n List<Integer> indeces = new ArrayList<>();\n IntStream.range(0, batchSizes.size()).forEach((num) -> indeces.add(num));\n Collection<List<Integer>> permutations = new Permutations<Integer>().permute(indeces);\n permutations.forEach(\n (permutation) -> checkPermutationMaximum(permutation, budget, batchSizes, batchCosts)\n );\n return globalMax;\n }\n\n private void checkPermutationMaximum(List<Integer> indeces, int budget, List<Integer> batchSizes, List<Integer> batchCosts) {\n int localMax = 0;\n int remainingCash = budget;\n\n int i = 0;\n int sz = indeces.size();\n while (i < sz && remainingCash > 0) {\n int currentVendor = indeces.get(i);\n int currentCost = batchCosts.get(currentVendor);\n if (remainingCash >= currentCost) {\n int cashToCostRatio = remainingCash / currentCost;\n remainingCash -= currentCost * cashToCostRatio;\n localMax += cashToCostRatio * batchSizes.get(currentVendor);\n }\n i++;\n }\n\n if (localMax > globalMax) globalMax = localMax;\n\n }\n}\n</code></pre>\n\n<p>The above passes all of your assertEqual tests as well as debug scrutiny</p>\n\n<p><hr>\n<strong>Comments on Update</strong></p>\n\n<p>Rather than trying to create the next unvisited permutation at run time (which is your above approach) I adapted a utility to return a Collection of Lists, where each List is a possible permutation of the input. Then I compute and check the maximum for each permutation</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T19:34:11.523",
"Id": "419497",
"Score": "0",
"body": "Thanks for the feedback. I've taken your solution to my IDE and it seems the code you posted is perhaps slightly different than the one you used on your IDE. I've added the increment to currentVendor as a last line in the while loop to avoid infinite loop. It still fails the last assertion though: \nassertEquals(41, sb.budgetShopping(50, List.of(20, 1), List.of(24, 2))); \nWith the initial 50 dollars we can buy 2 batches of 20 at the cost of $24. Our current total is 40 and the balance is $2. Since we still have $2, we can still buy one package from the other vendor, totalling 41."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T19:46:52.267",
"Id": "419501",
"Score": "1",
"body": "Response edited to include the accumulator, thank you for noticing.\n\nI was working under the assumption that you could not purchase from more than one vendor. This explains **a lot** such as your use of permute and perhaps thus your use of IntStream. Expect a complete edit of my answer soon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T16:56:43.423",
"Id": "419589",
"Score": "0",
"body": "Answer Updated, but for postarity I just <s>struckthrough</s> the old review text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T20:08:33.950",
"Id": "419614",
"Score": "0",
"body": "Thanks for your feedback, it's always interesting to see different approaches to a given problem. By the way, I have since found out a much simpler way to generate the permutations, based on an article from baeldung -> https://www.baeldung.com/java-array-permutations"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T18:24:26.267",
"Id": "216807",
"ParentId": "215929",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T12:53:35.033",
"Id": "215929",
"Score": "4",
"Tags": [
"java",
"programming-challenge",
"knapsack-problem"
],
"Title": "Find out how many laptops Molly can buy based on available money, array of quantities and array of costs"
} | 215929 |
<p>I need you help with my php session class. I can not understand, the class implements adequate work with sessions. By adequate work, I understand the security and correctness of the methods.</p>
<pre><code><?php
namespace Core;
class Session
{
/**
* @var string Название сесии
*/
private $name;
/**
* @var array Cookie сессии
*/
private $cookie;
/**
* @var int Время жизни сессии
*/
private $timeToLive;
/**
* Session constructor
* @see http://php.net/manual/ru/session.configuration.php Настройка во время выполнения
* @see http://php.net/manual/ru/function.session-set-cookie-params.php PHP session_set_cookie_params
* @param int $time_to_live Время жизни сессии (в минутах)
* @param string $name
* @param array $cookie
*/
public function __construct($time_to_live = 30, $name = "application.session", $cookie = [])
{
$this->timeToLive = $time_to_live;
// Изменяется имя сеанса (по умолчанию) на указанное (если есть) имя для конкретного приложения
$this->name = $name;
$this->cookie = $cookie;
// session.cookie_path определяет устанавливаемый путь в сессионной cookie
// session.cookie_domain определяет устанавливаемый домен в сессионной cookie
$this->cookie += [
'lifetime' => 0,
'path' => ini_get('session.cookie_path'),
'domain' => ini_get('session.cookie_domain'),
'secure' => isset($_SERVER['HTTPS']),
'httponly' => true
];
/*
* Указывается, что сеансы должны передаваться только с помощью файлов cookie,
* исключая возможность отправки идентификатора сеанса в качестве параметра «GET».
* Установка параметров cookie идентификатора сеанса. Эти параметры могут быть переопределены при инициализации
* обработчика сеанса, однако рекомендуется использовать значения по умолчанию, разрешающие отправку
* только по HTTPS (если имеется) и ограниченный доступ HTTP (без доступа к сценарию на стороне клиента).
*/
// Определяет, будет ли модуль использовать cookies для хранения идентификатора сессии на стороне клиента
ini_set('session.use_cookies', 1);
// Определяет, будет ли модуль использовать только cookies для хранения идентификатора сессии на стороне клиента
ini_set('session.use_only_cookies', 1);
session_set_cookie_params(
$this->cookie['lifetime'],
$this->cookie['path'],
$this->cookie['domain'],
$this->cookie['secure'],
$this->cookie['httponly']
);
}
public function __get($name)
{
switch ($name) {
case 'isActive':
return $this->getActive();
case 'id':
return $this->getId();
case 'name':
return isset($this->name) ? $this->name : $this->getName();
case 'isValid':
return $this->isValid();
}
}
public function __set($name, $value)
{
switch ($name) {
case 'id':
$this->setId($value);
break;
case 'name':
$this->setName($value);
break;
case 'timeToLive':
$this->timeToLive = $value * 60;
break;
}
}
/**
* Получение статуса активности сессии
* @see https://secure.php.net/manual/en/function.session-status.php PHP session_status
* @return bool Статус активности сессии
*/
private function getActive()
{
return session_status() === PHP_SESSION_ACTIVE;
}
/**
* Получение идентификатора текущей сессии.
* Метод является оберткой для реализации стандартного метода.
* @see https://secure.php.net/manual/ru/function.session-id.php PHP session_id
* @return string
*/
private function getId()
{
return session_id();
}
/**
* Получение имени сессии
* Метод является оберткой для реализации стандартного метода
* @see http://php.net/manual/ru/function.session-name.php PHP session_name
* @return string|null
*/
private function getName()
{
return $this->isActive ? session_name() : null;
}
private function isValid()
{
return !$this->isExpired() && $this->isFingerprint();
}
/**
* Проверка срока действия сессии
* @return bool
*/
private function isExpired()
{
$activity = isset($_SESSION['_last_activity']) ? $_SESSION['_last_activity'] : false;
if ($activity && ((time() - $activity) > $this->timeToLive)) {
return true;
}
$_SESSION['_last_activity'] = time();
return false;
}
/**
* Проверка клиента
* @return bool
*/
private function isFingerprint()
{
$hash = sha1($_SERVER['HTTP_USER_AGENT'] .
(ip2long($_SERVER['REMOTE_ADDR']) & ip2long('255.255.0.0')));
if (isset($_SESSION['_fingerprint'])) {
return $_SESSION['_fingerprint'] === $hash;
}
$_SESSION['_fingerprint'] = $hash;
return true;
}
/**
* Назначение идентификатора текущей сессии.
* Метод является оберткой для реализации стандартного метода.
* @see https://secure.php.net/manual/ru/function.session-id.php PHP session_id
* @param string $id Идентификатор сессии для текущей сессии
*/
private function setId($id)
{
session_id($id);
}
/**
* Установка имени сессии
* Метод является оберткой для реализации стандартного метода
* @see http://php.net/manual/ru/function.session-name.php PHP session_name
* @param $name
*/
public function setName($name)
{
if ($this->isActive) {
session_name($name);
}
}
/**
* Инициализация сессии
*/
public function open()
{
// Бездействие, если сессия была инициализирована ранее
if ($this->isActive) {
return;
}
session_start();
// Проверка на корректность инициализированнйо сессии
if (!$this->isActive) {
// TODO: Вывод исключения
}
}
/**
* Уничтожение сессии, включая все атрибуты. Метод имеет эффект только при наличии активной сессии.
* @see http://php.net/manual/ru/function.setcookie.php PHP setcookie
*/
public function destroy()
{
if ($this->isActive) {
$this->deleteAll();
setcookie(
$this->name,
time() - 42000,
$this->cookie['path'],
$this->cookie['domain'],
$this->cookie['secure'],
$this->cookie['httponly']
);
session_destroy();
}
}
/**
* Удаление всех значений сессии
* Метод является оберткой для реализации стандартного метода
* @see http://php.net/manual/ru/function.session-unset.php PHP session_unset
*/
public function deleteAll()
{
if ($this->isActive) {
session_unset();
}
}
/**
* Обновление текущего ID на новый. Метод имеет эффект только при наличии активной сессии.
* @see https://secure.php.net/session_regenerate_id PHP session_regenerate_id
* @param bool $delete_old_session
*/
public function refresh($delete_old_session = true)
{
if ($this->isActive) {
session_regenerate_id($delete_old_session);
}
}
/**
* Получение значение сессии по ключу.
* @param string $key Ключ, по которому необходимо получить значения
* @return null|mixed Значение сессии по ключу
*/
public function get($key)
{
if ($this->isActive) {
return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
}
return null;
}
/**
* Добавление или установка значений в сессию по ключу
* @param string $key Ключ, в который необходимо добавить значения
* @param string $value Значение добавления
*/
public function set($key, $value)
{
if ($this->isActive) {
$_SESSION[$key] = $value;
}
}
/**
* Удаление значения сессии по ключу
* @param string $key Ключ, по которому необходимо удалить значения
*/
public function delete($key)
{
if ($this->isActive && isset($_SESSION[$key])) {
unset($_SESSION[$key]);
}
}
/**
* Проверка наличия ключа у сессии
* @param string $key Ключ, в который необходимо найти
* @return bool
*/
public function hasKey($key)
{
return ($this->isActive && isset($_SESSION[$key]));
}
}
</code></pre>
<p><strong>Usage</strong></p>
<pre><code>$session = new Session();
$session->open();
// If AFK more than access - logout
if (!$session->isValid) {
$session->destroy();
}
...
</code></pre>
<p>What are your thoughts and comments on this decision? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T16:03:30.557",
"Id": "417829",
"Score": "0",
"body": "Welcome to Code Review! The (doc) comments would be of little value for me but for web translators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T17:10:32.637",
"Id": "417840",
"Score": "0",
"body": "@greybeard ok, I will translate it"
}
] | [
{
"body": "<p>Securing PHP sessions is like art and the defualt session handler is not safe far from it and alot can go wrong with it.. </p>\n\n<p>For example on shared webhosting when the sessions are configured to run in one directory. <br />\nA attacker could run the PHP code on his hosting account </p>\n\n<pre><code><?php \n\nsession_start();\n$session_id = session_id(); \n\n$path = session_save_path() . '/sess_' . session_id();\nchmod($path, 777); # read and writeable by everybody\n\nvar_dump($session_id);\n\n?>\n</code></pre>\n\n<p>The attacker can now use the session id and change the <code>HTTP_REFERER</code> in a HTTP header tool, to use his session_id on your website. </p>\n\n<p>That makes it also possible read and modify session data on his web hosting account to gain more privilies or do SQL injections on your web hosting account. <br /> </p>\n\n<p>This works because the session source code in <code>session_start()</code> does not check which sessions belongs to which website, the only check is <code>HTTP_REFERER</code> header which can be spoofed. </p>\n\n<pre><code>/* Check whether the current request was referred to by\n * an external site which invalidates the previously found id. */\n\nif (PS(id) &&\n PS(extern_referer_chk)[0] != '\\0' &&\n PG(http_globals)[TRACK_VARS_SERVER] &&\n zend_hash_find(Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]), \"HTTP_REFERER\", sizeof(\"HTTP_REFERER\"), (void **) &data) == SUCCESS &&\n Z_TYPE_PP(data) == IS_STRING &&\n Z_STRLEN_PP(data) != 0 &&\n strstr(Z_STRVAL_PP(data), PS(extern_referer_chk)) == NULL\n) {\n efree(PS(id));\n PS(id) = NULL;\n PS(send_cookie) = 1;\n if (PS(use_trans_sid) && !PS(use_only_cookies)) {\n PS(apply_trans_sid) = 1;\n }\n}\n</code></pre>\n\n<p>How to make it safe? <br />\nYou have two good options</p>\n\n<p>1) Use <a href=\"http://php.net/manual/en/function.session-save-path.php\" rel=\"nofollow noreferrer\">session_save_path</a> <br />\n2) Write you own <a href=\"http://php.net/manual/en/class.sessionhandler.php\" rel=\"nofollow noreferrer\">SessionHandler class</a> and write your own layer to work on file system and or database. </p>\n\n<p><strong>Note</strong> <br />\nThis will not solve all session related security issues when using PHP sessions, but it is a good starting point. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T10:03:58.567",
"Id": "215987",
"ParentId": "215931",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T13:50:32.840",
"Id": "215931",
"Score": "3",
"Tags": [
"php",
"security",
"session"
],
"Title": "Is it enough for PHP secure session class?"
} | 215931 |
<p>This is a homework question, and I have written the code but wasn't sure if I had picked the right data structure for this job and minimised time complexity. Can anyone give me some feedback, anything about space complexity or potential bugs that can occur is appreciated as well.</p>
<p><strong>Problem Description</strong></p>
<blockquote>
<p>MagicTheGathering</p>
<p>Aim: deal with a series of command (SUMMON, KILL, HEAL). Each SUMMON
command will create a monster and each monster has a initial HP value.</p>
<p>Each KILL command will kill the monster with the lowest HP. And each
HEAL command applies to every monster in your list.</p>
<p>Input: N, the number of commands. Followed by N lines of commands.</p>
<p>Output: Each KILL command requires you to print the HP of the monster
that was killed. At the end of the series of commands, print the HP of
the remaining. monsters.</p>
<p><strong>Input example</strong>:</p>
<pre><code>8
SUMMON 30
SUMMON 20
SUMMON 50
HEAL 5
KILL
SUMMON 7
KILL
HEAL 10
</code></pre>
<p><strong>Output example:</strong></p>
<pre><code>25
7
45 65
</code></pre>
</blockquote>
<p><strong>Attempt</strong></p>
<pre><code>import java.util.*;
import java.util.stream.*;
class Yugioh {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
PriorityQueue<Integer> queue = new PriorityQueue(Comparator.naturalOrder());
for (int i =0;i<count;i++) {
String cmd = sc.next();
if (cmd.equals("SUMMON")) {
int health = sc.nextInt();
queue.add(health);
} else if (cmd.equals("HEAL")) {
int health = sc.nextInt();
PriorityQueue<Integer> newQueue = new PriorityQueue<>(Comparator.naturalOrder());
List<Integer> data = queue.stream().map(x -> x + health).collect(Collectors.toList());
newQueue.addAll(data);
queue = newQueue;
} else if (cmd.equals("KILL")) {
System.out.println(queue.poll());
}
}
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
</code></pre>
| [] | [
{
"body": "<p>HEAL doesn't change the relative order. So there is no point in rebuilding queue. Keep a sum of total HEAL so far, and remember it for each monster. Then, when HEAL happens you just do <code>totalHealSoFar++</code> and to display proper score on KILL return <code>health+(totalHealSoFar-totalHealWhenThisMonsterWasCreated)</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T13:06:24.067",
"Id": "215995",
"ParentId": "215939",
"Score": "0"
}
},
{
"body": "<p>You should use an ENUM or a class for the list of commands.</p>\n\n<p>E.G:</p>\n\n<pre><code>public ENUM Command\n{\n private String value;\n\n SUMMON(\"Summon\"),\n ATTACK(\"Attack\"),\n HEAL(\"Heal\")\n\n public Command(String value) { this.value = value; };\n}\n\n// String cmd = Commands.valueOf(sc.next());\n// if (cmd == Command.HEAL) ...\n// ( Or better yet, use a switch statement)\n</code></pre>\n\n<p>You should also be dealing with invalid input. (E.g in the default of the switch).</p>\n\n<p>You've mentioned Magic the gathering, but your class name is Yugioh. As we all know, those are two very different games.</p>\n\n<p>The variable 'health' is declared twice, I don't think the name makes sense for 'Summon'. </p>\n\n<p>The case for 'Heal' looks overly complicated. You shouldn't need to create a 'newQueue'. Try to take away X amount of health for each item (either using a for-loop or lambdas). No need to re-order the queue.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T20:29:05.453",
"Id": "216747",
"ParentId": "215939",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T14:58:56.693",
"Id": "215939",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"programming-challenge",
"priority-queue"
],
"Title": "A simple card game simulator"
} | 215939 |
<p>I was asked to create a Java program that will navigate through a series of mazes. I would like to know if this is the optimal way of using a DFS or is there a better way and I am doing something wrong?</p>
<p>Example of a Maze File:</p>
<pre><code>10 10
1 1
8 8
1 1 1 1 1 1 1 1 1 1
0 0 1 0 0 0 0 0 0 0
0 0 1 0 1 1 1 1 1 1
1 0 1 0 0 0 0 0 0 1
1 0 1 1 0 1 0 1 1 1
1 0 1 0 0 1 0 1 0 1
1 0 1 0 0 0 0 0 0 1
1 0 1 1 1 0 1 1 1 1
1 0 1 0 0 0 0 0 0 1
1 1 1 1 1 1 1 1 1 1
</code></pre>
<p>This file is then converted into a 2DInt array where 0 are empty spaces and 1 is a wall. The maze can wrap around itself too so you can go from one side to another if the space is 0 on either side. 10 10 is the maze size, 1 1 is starting location and 8 8 is ending location.</p>
<p>I have used the Depth-First-Search to solve this maze, here is the code:</p>
<p>MAIN CLASS</p>
<pre><code> import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
public class Main {
static Stack<Node> q = new Stack<Node>(); // Stack is used for Depth First Search Algorithm, Queue can be used to
// convert DFS into a Breadth-first search algorithm.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter exact maze file location: ");
String fileLocation = reader.nextLine();
reader.close();
ArrayList<String> mazeRaw = new ArrayList<String>();
File file = new File(fileLocation);
try {
String st;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((st = br.readLine()) != null)
mazeRaw.add(st);
br.close();
} catch (IOException e) {
System.out.println("Error: " + e);
}
Maze testMaze = new Maze(mazeRaw); //2D Int array maze constructor
String[][] results = new String[testMaze.maze2D.length][testMaze.maze2D[0].length];
Node p = solveMaze(testMaze, testMaze.returnStart()); //Node p contains p.parent that hold the path through the maze.
testMaze.printMazeResult(results, p, testMaze.returnStart());
}
public static Node solveMaze(Maze maze, Node start) {
q.push(new Node(start.x, start.y, null)); // Adds the starting coordinates to the stack.
while (!q.isEmpty()) // Until the stack is empty continue loop.
{
Node p = q.pop(); // Get the top element from the Stack and assign it to p
// Valid States //-------------------------------------------------------------------------------//
//If Exit found at coordinates p.x,p.y in 2Dint Array return the p Node.
if (maze.getMaze2D()[p.x][p.y] == 9) {
return p;
}
//If x,y location cannot be wrapped on either ends then check if its sparse for formatting purposes.
if (!isWrappable(maze, p) && isSparse(maze, p)) {
maze.getMaze2D()[p.x][p.y] = -1;
Node nextP = new Node(p.x + 1, p.y, p);
q.push(nextP);
continue;
}
//Check if p node is at the border and if the border wraps around the array in a valid way and make sure that the node parent is not at border to avoid loops
if (isWrappingBorder(maze, p.x, p.y, p) != null && isWrappingBorder(maze, p.parent.x, p.parent.y, p.parent) == null) {
q.push(isWrappingBorder(maze, p.x, p.y, p));
}
// 4 Directional Movements //-------------------------------------------------------------------------------//
// South
if (isFree(maze, p.x + 1, p.y)) {
maze.getMaze2D()[p.x][p.y] = -1;
Node nextP = new Node(p.x + 1, p.y, p);
q.push(nextP);
}
// North
if (isFree(maze, p.x - 1, p.y)) {
maze.getMaze2D()[p.x][p.y] = -1;
Node nextP = new Node(p.x - 1, p.y, p);
q.push(nextP);
}
// West
if (isFree(maze, p.x, p.y + 1)) {
maze.getMaze2D()[p.x][p.y] = -1;
Node nextP = new Node(p.x, p.y + 1, p);
q.push(nextP);
}
// East
if (isFree(maze, p.x, p.y - 1)) {
maze.getMaze2D()[p.x][p.y] = -1;
Node nextP = new Node(p.x, p.y - 1, p);
q.push(nextP);
}
}
return null; // If Maze cannot be solved value null is returned;
}
//This method checks if the coordinates adjacent to the Node p are empty to detect sparse input for formatting purposes
public static boolean isSparse(Maze maze, Node p) {
if (maze.getMaze2D()[p.x][p.y - 1] == 0 && maze.getMaze2D()[p.x + 1][p.y] == 0
&& maze.getMaze2D()[p.x + 1][p.y - 1] == 0 || maze.getMaze2D()[p.x + 1][p.y] == 9)
return true;
else
return false;
}
//Checks if the array can be wrapped around at either ends and direction from the current Node p.
public static boolean isWrappable(Maze maze, Node p) {
if (maze.getMaze2D()[0][p.y] == 0 || maze.getMaze2D()[p.x][0] == 0
|| maze.getMaze2D()[maze.getMaze2D().length - 1][p.y] == 0
|| maze.getMaze2D()[p.x][maze.getMaze2D()[0].length - 1] == 0)
return true;
else
return false;
}
//Detect the point where Array wraps around itself and return a Node that comes out on the other side of the wrapped array
public static Node isWrappingBorder(Maze maze, int x, int y, Node parent) {
Node nextNode;
if (x == 0 && maze.getMaze2D()[x][y] != 1) {
if (maze.getMaze2D()[maze.getMaze2D().length - 1][y] != 1)
return nextNode = new Node(maze.getMaze2D().length - 1, y, parent);
}
if (x == maze.getMaze2D().length - 1 && maze.getMaze2D()[x][y] != 1) {
if (maze.getMaze2D()[0][y] != 1)
return nextNode = new Node(0, y, parent);
}
if (y == 0 && maze.getMaze2D()[x][y] != 1) {
if (maze.getMaze2D()[x][maze.getMaze2D().length - 1] != 1)
return nextNode = new Node(x, maze.getMaze2D().length - 1, parent);
}
if (y == maze.getMaze2D()[0].length - 1 && maze.getMaze2D()[x][y] != 1) {
if (maze.getMaze2D()[x][0] != 1)
return nextNode = new Node(x, 0, parent);
}
return null;
}
//Checks if int x, and int y which are passed from Node.x and Node.y values are valid coordinates
public static boolean isFree(Maze maze, int x, int y) {
if ((x >= 0 && x < maze.getMaze2D().length) && (y >= 0 && y < maze.getMaze2D()[x].length)
&& (maze.getMaze2D()[x][y] == 0 || maze.getMaze2D()[x][y] == 9))
return true;
else
return false;
}
}
</code></pre>
<p>MAZE CLASS</p>
<pre><code> import java.util.ArrayList;
import java.util.Arrays;
public class Maze {
int[][] maze2D; //
private Node start;
private Node end;
public Maze(ArrayList<String> mazeString) {
this.maze2D = new int[(Integer.valueOf(mazeString.get(0).split(" ")[1]))][(Integer
.valueOf(mazeString.get(0).split(" ")[0]))]; // Assign maze size from the file.
start = new Node(Integer.valueOf(mazeString.get(1).split(" ")[1]), Integer.valueOf(mazeString.get(1).split(" ")[0]), null);
end = new Node(Integer.valueOf(mazeString.get(2).split(" ")[1]), Integer.valueOf(mazeString.get(2).split(" ")[0]), null);
for (int i = 0; i < this.maze2D.length; i++) {
for (int n = 0; n < this.maze2D[i].length; n++) {
this.maze2D[i][n] = Integer.valueOf(mazeString.get(i + 3).split(" ")[n]); // i + 3 to offset first 3 lines of text file.
}
}
this.maze2D[start.x][start.y] = 8; // Assign maze start from the file.
this.maze2D[end.x][end.y] = 9; // Assign maze end from the file.
}
@Override
public String toString() {
System.out.println(Arrays.deepToString(this.maze2D));
return (this.maze2D.toString());
}
public Node returnStart()
{
return start;
}
public Node returnEnd() {
return end;
}
public int[][] getMaze2D() {
return maze2D;
}
public void setMaze2D(int[][] maze2d) {
maze2D = maze2d;
}
public void printMazeResult(String[][] results, Node p, Node start) {
Boolean mazeState = false;
for (int i = 0; i < getMaze2D().length; i++) {
for (int j = 0; j < getMaze2D()[i].length; j++) {
switch (maze2D[i][j]) {
case 0:
results[i][j] = " ";
break;
case 1:
results[i][j] = "#";
break;
case -1:
results[i][j] = " ";
break;
case 9:
results[i][j] = "E";
break;
}
}
}
try {
while (p.getParent() != null) {
p = p.getParent();
if (maze2D[p.x][p.y] == 9)
continue;
results[p.x][p.y] = "X";
}
results[start.y][start.x] = "S";
mazeState = true;
} catch (java.lang.NullPointerException e) {
mazeState = false;
}
for (int i = 0; i < results.length; i++) {
for (int j = 0; j < results[i].length; j++) {
System.out.print(results[i][j]);
}
System.out.println();
}
if (mazeState == true)
System.out.println("- Maze has been solved :) -");
else
System.out.println("- Maze is unsolvable -");
}
}
</code></pre>
<p>NODE CLASS</p>
<pre><code>import java.util.ArrayList;
public class Node
{
int x;
int y;
Node parent;
public Node(int x, int y, Node parent) {
this.x = x;
this.y = y;
this.parent = parent;
}
public Node() {
this.x = 0;
this.y = 0;
this.parent = null;
}
public Node getParent() {
return this.parent;
}
public String toString() {
return "x = " + x + " y = " + y;
}
}
</code></pre>
<p>OUTPUT:</p>
<pre><code>##########
XS#XXXXXXX
#X######
# #XXXX #
# ## #X###
# # #X# #
# # XX #
# ###X####
# # XXXE#
##########
</code></pre>
| [] | [
{
"body": "<h2>API and Reusability</h2>\n\n<p><code>solveMaze</code> takes both a <code>Maze maze</code> and <code>Node start</code>, even though <code>Maze</code> defines a <code>start</code> position already.</p>\n\n<p>The use of the static <code>q</code> Stack means it is not reusable: if a solution is found, then it will remain populated, and interfere with the next run. You can also not reuse <code>Maze</code>s, because <code>solveMaze</code> replaces the empty spaces with <code>-1</code>: it would be much nicer if it did not modify the <code>Maze</code> it is given or, at the very least, reset the <code>Maze</code> once it has finished.</p>\n\n<p>Given you don't use <code>q</code> outside of <code>solveMaze</code>, there is no sense in making it a member of the class, when it could be a local variable, created on demand. It would be nice to see the maze-solving logic in its own class, rather than mixed up with the calling code.</p>\n\n<h2>Magic numbers</h2>\n\n<p><code>0</code>, <code>9</code>, <code>8</code>, <code>-1</code>... these are all meaningless to anyone who might be trying to use your classes and methods without having first inspected your code. They are a maintainability concern, because changing a <code>9</code> in one place has no effect in any of the others, and a find-and-replace for <code>9</code> is a nightmare waiting to happen. Much better to use meaningful constant values:</p>\n\n<pre><code>public static final int EmptyCell = 0;\npublic static final int StartCell = 8;\npublic static final int EndCell = 9;\npublic static final int VisitedCell = -1;\n</code></pre>\n\n<p>You could also hide the implementation details as best as possible. <code>isFree</code>, for example, could be a member of <code>maze</code>. <code>setVisited</code> could be added as a member, so that you can do away with <code>maze.getMaze2D()[p.x][p.y] = -1;</code>.</p>\n\n<h2><code>try ... catch</code></h2>\n\n<p>The <code>try ... catch</code> in <code>main</code> pretty much swallows any exception that might occur while reading the file, and then proceeds to allow the rest of the code to run, as though nothing has gone wrong. I'd prefer that this code printed the exception and stack-trace and then exited cleanly; otherwise, the code that follows after it is likely to fail on the invalid input it will receive, and the original source of the problem will be less apparent.</p>\n\n<p>You should also close the <code>BufferedReader</code> in a <code>finally</code> block, to ensure this unmanaged resource is freed as soon as possible; or, better, use a try-with-resources statement, which make it difficult to misuse the <code>BufferedReader</code> (e.g. by forgetting to close it, or by using it when it has already been closed)</p>\n\n<p>The <code>try ... catch</code> in <code>printMazeResult</code> is rather concerning: it seems that it's purpose is to deal with the case where <code>p</code> is <code>null</code> because <code>solveMaze</code> returned <code>null</code>. This, however, is wholly unclear from the code itself, and the <code>try ... catch</code> is liable to obscure bugs inside the code which are unrelated to whether the maze was or was note solved. You should use an explicit check to determine whether the maze was solved:</p>\n\n<pre><code>Boolean mazeIsSolved = p != null\n</code></pre>\n\n<p>(this is a better name than <code>mazeState</code>, which sounds like a transient concern)</p>\n\n<h2>Wrapping</h2>\n\n<p>The 'wrapping' code looks needlessly complicated. I'd be strongly inclined to remove it completely, and instead perform 'wrapping' in the NESW checks (see below).</p>\n\n<p>The wrapping code itself would be much nicer if <code>maze</code> exposed the width and height of the <code>maze</code>, as the code is currently dotted with <code>maze.getMaze2D()[maze.getMaze2D().length - 1]</code>, which is just a distraction from its real purpose. Many other places in the code would benefit from such methods also.</p>\n\n<p>I don't think <code>isWrappingBorder</code> is a very good name, since it does a lot more than determine whether it is a wrapping border. It's comment (which would ideally be <a href=\"https://en.wikipedia.org/wiki/Javadoc\" rel=\"nofollow noreferrer\">JavaDoc</a>) also fails to mention that it will return <code>null</code> if it is not a wrapping Border. More importantly, I think it is deficient in the cases where you are against both borders, as it can only return a single value.</p>\n\n<p>The <code>return nextNode = ...</code> theme is confusing: you assign a local variable only to return it immediately. There is no value in the local variable, and you can safely remove it.</p>\n\n<h2>NESW movement</h2>\n\n<p>Your have basically the same piece of code here four times, just with a different <code>+/- 1</code>: put this in a method, so that there is one reusable version to maintain, and it is easier to follow the logic in <code>solveMaze</code> without worrying about the details. Something like this would work:</p>\n\n<pre><code>static void tryMove(Maze maze, Node p, Stack<Node> q, int dx, int dy) {\n // offset and wrap\n int x = (p.x + dx + maze.getWidth()) % maze.getWidth();\n int y = (p.x + dy + maze.getHeight()) % maze.getHeight();\n\n if (isFree(maze, x, y)) {\n maze.getMaze2D()[p.x][p.y] = -1;\n Node nextP = new Node(x, y, p);\n q.push(nextP);\n }\n}\n</code></pre>\n\n<p>Using it is then just a case of:</p>\n\n<pre><code>tryMove(maze, p, q, -1, 0);\ntryMove(maze, p, q, +1, 0);\ntryMove(maze, p, q, 0, -1);\ntryMove(maze, p, q, 0, +1);\n</code></pre>\n\n<p>The following line appears once for each direction; it should presumably be run even if no move can be made, and doesn't need to be run for each in turn.</p>\n\n<pre><code>maze.getMaze2D()[p.x][p.y] = -1;\n</code></pre>\n\n<h2>Naming</h2>\n\n<p>Your naming could be better. <code>q</code>, for example, is pretty meaningless. I guess that <code>Node p</code> stands for 'point'. It's also odd to see <code>x</code> and <code>y</code> as the <code>row</code> and <code>column</code> indices, rather than the other way round (e.g. normally the x-axis is east-west, not north-south).</p>\n\n<p>In some places you use <code>i</code> and <code>j</code> as loop variables, in other <code>i</code> and <code>n</code>: <code>n</code> <em>usually</em> means a count, <code>j</code> is a better choice; however, <code>i</code> and <code>j</code> do not convey all that much; <code>(r)ow</code> and <code>(c)ol</code> would be more meaningful.</p>\n\n<h2><code>Maze</code> constructor</h2>\n\n<p>The parameter <code>ArrayList<String> mazeString</code> is not a <code>String</code>, but rather a collection of lines. You might also consider taking the abstract <code>List<String></code>, rather than requiring the particular derived typed, so that your interface is easier to use.</p>\n\n<p>The following is pretty unreadable, and the line-break is not in a very nice place:</p>\n\n<pre><code>this.maze2D = new int[(Integer.valueOf(mazeString.get(0).split(\" \")[1]))][(Integer\n .valueOf(mazeString.get(0).split(\" \")[0]))];\n</code></pre>\n\n<p>Instead of trying to squeeze all of that onto one line, break it up:</p>\n\n<pre><code>string[] dimensionData = mazeString.get(0).split(\" \");\nint width = Integer.valueOf(dimensionData[0]);\nint height = Integer.valueOf(dimensionData[1]);\n\nthis.maze2D = new int[width][height];\n</code></pre>\n\n<p>Now it is instantly recognisable what the code is meant to do, and the details are laid out plainly, and without repetition (repeated code is a maintainability concern, as all instances have to kept consistent).</p>\n\n<p>Performance shouldn't be an issue here, but little things like re-splitting whole lines of input for each entry should be avoided, as they can (as in this instance) turn a simple quadratic-complexity operation into a cubic cost, potentially creating problems in seemingly unlikely places:</p>\n\n<pre><code>for (int i = 0; i < this.maze2D.length; i++) {\n String[] lineData = mazeString.get(i + 3).split(\" \"); // i + 3 to offset first 3 lines of text file.\n\n for (int j = 0; j < this.maze2D[i].length; j++) {\n this.maze2D[i][j] = Integer.valueOf(lineData[j]);\n }\n}\n</code></pre>\n\n<h2>More <code>Maze</code></h2>\n\n<p><code>toString</code> should <em>not</em> be writing out to standard output!</p>\n\n<pre><code>@Override\npublic String toString() {\n System.out.println(Arrays.deepToString(this.maze2D)); // no!\n return (this.maze2D.toString());\n}\n</code></pre>\n\n<p>Your <code>setMaze</code> method doesn't make much sense, as it could well disagree with the <code>start</code> and <code>end</code> fields, <em>hopefully</em> leading to a crash down-the-line, but just as likely leading to incorrect operation of the class and a meaningless result.</p>\n\n<p>I also don't like <code>maze2D = maze2d</code>: it's far too easy get wrong. You are also inconsistent with your use of <code>this.maze2D</code>, which would be a better solution here.</p>\n\n<h2>Accessibility</h2>\n\n<p>You specify <code>private</code> accessors in some places and not in others; generally it's nice to see them everywhere, because it is then unambiguous to the reader that this was the intention (as opposed to 'forgetting' the access modifier, and leaving it as the default), and is nice for people who may not use the language every-day, or may use many languages with different defaults (I, for example - coming from C# - had forgotten the default field accessibility was <code>package</code> (or whatever it is) and not <code>private</code>, which is a very important difference, e.g. in <code>Node</code>...).</p>\n\n<h2><code>Node</code></h2>\n\n<p><code>x</code>, <code>y</code>, and <code>parent</code> are not <code>private</code>: indeed, you depend on being able to access <code>x</code> and <code>y</code> from outside the class, while you provide a public getter for <code>parent</code>. I would be strongly inclined to make <code>Node</code> immutable, by making all of these fields <code>final</code>. Then you can choose whether to keep <code>x</code> and <code>y</code> as (genuinely) <code>public</code> fields, or make them <code>private</code> (like <code>parent</code> should be) and provide an appropriate getter.</p>\n\n<p>I don't like the repurposing of <code>Node</code> as a <code>Point</code> or <code>Coordinates</code> structure; it's carrying around a <code>null</code> Parent everywhere, which is completely meaningless.</p>\n\n<p>Why does <code>Node()</code> have a default constructor? It is never used, and doesn't look like it produces a meaningful node: I would remove it.</p>\n\n<h2>Misc</h2>\n\n<ul>\n<li><p>Why all the empty-lines in <code>Node</code>?</p></li>\n<li><p>Why are <code>returnStart</code> and <code>returnEnd</code> not called <code>getStart</code> and <code>getEnd</code>?</p></li>\n<li><p>Why is <code>results</code> a parameter to <code>printMazeResult</code> instead of creating it itself?</p></li>\n<li><p>I have no idea what <code>isSparse</code> is meant to achieve.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T00:48:37.477",
"Id": "417880",
"Score": "0",
"body": "Thanks a lot for the advice I will dissect it in full soon I did fix a couple of the stuff you mentioned earlier today."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T00:52:19.230",
"Id": "417881",
"Score": "0",
"body": "I have a problem I don't really know how to go around solving which is what isSparse is suppose to achieve because in an event I get a maze that has a section of it which is empty my code runs through the entire maze instead of taking just 1 path as a result when I print out the result every single node is printed which is useless because its not a path at all it just visits every node possible. isSparse checks if elements around a point are empty and then forces it to run down."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T11:30:21.840",
"Id": "417924",
"Score": "0",
"body": "@MasterChiff that sounds like classic DFS; BFS won't have that problem (it will always find the optimal path), and it won't cost anything more since you are using graph search (e.g. use `Queue` instead of a `Stack` as per your comment to that effect)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T12:59:50.857",
"Id": "417935",
"Score": "0",
"body": "I tried but when I used BFS on large mazes It would just go on for hours and I need it to resolve in seconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T13:24:31.073",
"Id": "417936",
"Score": "1",
"body": "@MasterChiff if you have implemented it correctly, then the maximum run-time of a graph-search BFS and DFS should be the same (i.e. they only look at each empty cell once; you are setting the visited cell to `-1` only after expanding it, which might be creating a situation where you expand outer nodes and exponential number of times, but I've not looked at it too hard)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T13:47:20.623",
"Id": "417939",
"Score": "0",
"body": "I see, thanks I will look into it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T16:25:36.987",
"Id": "417956",
"Score": "0",
"body": "thank you for your pointers I have ended up scrapping the whole thing as it was vastly over-complicated and replaced it with a greedy BFS ProrityQueue approach that works fine (still have to code the wrapping functions)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T00:39:28.153",
"Id": "215964",
"ParentId": "215940",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "215964",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T14:59:29.390",
"Id": "215940",
"Score": "3",
"Tags": [
"java",
"algorithm",
"depth-first-search"
],
"Title": "Java Maze Solver (DFS)"
} | 215940 |
<p>The following source code is working Quad Tree Implementation in C++11.
How can I simplify the source code but also allow the user to bring his own Point Class Implementation?</p>
<pre><code>#pragma once
#include <algorithm>
#include <array>
#include <cstddef>
#include <functional>
#include <vector>
namespace forest {
template <typename T, std::size_t Capacity>
class QuadTree {
public:
using Point = std::array<T, 2>;
using Points = std::vector<Point>;
using PointsIt = typename std::vector<Point>::iterator;
using Callback = std::function<void(const Point &)>;
public:
class Range {
template <typename U, std::size_t K>
friend class QuadTree;
private:
Point mOrigin;
Point mTransform;
public:
Range() = default;
Range(const Point &origin, const Point &transform)
: mOrigin(origin), mTransform(transform) {}
~Range() = default;
public:
void setOrigin(const Point &origin) { mOrigin = origin; }
void setTransform(const Point &transform) { mTransform = transform; }
public:
Point getOrigin() const { return mOrigin; }
Point getTransform() const { return mTransform; }
public:
bool Contains(const Point &point) const {
return point[0] >= mOrigin[0] - mTransform[0] &&
point[0] <= mOrigin[0] + mTransform[0] &&
point[1] >= mOrigin[1] - mTransform[1] &&
point[1] <= mOrigin[1] + mTransform[1];
}
bool Intersects(const Range &other) const {
return mOrigin[0] - mTransform[0] <=
other.mOrigin[0] + other.mTransform[0] &&
mOrigin[0] + mTransform[0] >=
other.mOrigin[0] - other.mTransform[0] &&
mOrigin[1] - mTransform[1] <=
other.mOrigin[1] + other.mTransform[1] &&
mOrigin[1] + mTransform[1] >=
other.mOrigin[1] - other.mTransform[1];
}
};
private:
Points mBucket;
private:
Range mBoundary;
private:
bool mDivided{false};
private:
QuadTree *NW{nullptr};
QuadTree *NE{nullptr};
QuadTree *SW{nullptr};
QuadTree *SE{nullptr};
private:
void Divide() {
NW = new QuadTree<T, Capacity>(
{{mBoundary.mOrigin[0] - mBoundary.mTransform[0] / 2,
mBoundary.mOrigin[1] + mBoundary.mTransform[1] / 2},
{mBoundary.mTransform[0] / 2, mBoundary.mTransform[1] / 2}});
NE = new QuadTree<T, Capacity>(
{{mBoundary.mOrigin[0] + mBoundary.mTransform[0] / 2,
mBoundary.mOrigin[1] + mBoundary.mTransform[1] / 2},
{mBoundary.mTransform[0] / 2, mBoundary.mTransform[1] / 2}});
SW = new QuadTree<T, Capacity>(
{{mBoundary.mOrigin[0] - mBoundary.mTransform[0] / 2,
mBoundary.mOrigin[1] - mBoundary.mTransform[1] / 2},
{mBoundary.mTransform[0] / 2, mBoundary.mTransform[1] / 2}});
SE = new QuadTree<T, Capacity>(
{{mBoundary.mOrigin[0] + mBoundary.mTransform[0] / 2,
mBoundary.mOrigin[1] - mBoundary.mTransform[1] / 2},
{mBoundary.mTransform[0] / 2, mBoundary.mTransform[1] / 2}});
mDivided = true;
}
void Merge() {
delete NW;
delete NE;
delete SW;
delete SE;
NW = nullptr;
NE = nullptr;
SW = nullptr;
SE = nullptr;
mDivided = false;
}
public:
QuadTree() = delete;
QuadTree(const Range &BOUNDARY) : mBoundary(BOUNDARY) {}
~QuadTree() { Clear(); }
public:
bool Insert(const Point &point) {
if (!mBoundary.Contains(point)) return false;
if (!mDivided) {
if (std::find(mBucket.begin(), mBucket.end(), point) != mBucket.end())
return false;
mBucket.push_back(point);
if (mBucket.size() > Capacity) {
Divide();
PointsIt it = mBucket.begin();
while (it != mBucket.end()) {
if (NW->mBoundary.Contains(*it))
NW->Insert(*it);
else if (NE->mBoundary.Contains(*it))
NE->Insert(*it);
else if (SW->mBoundary.Contains(*it))
SW->Insert(*it);
else if (SE->mBoundary.Contains(*it))
SE->Insert(*it);
it = mBucket.erase(it);
}
}
return true;
}
return NW->Insert(point) || NE->Insert(point) || SW->Insert(point) ||
SE->Insert(point);
}
bool Remove(const Point &point) {
if (!mBoundary.Contains(point)) return false;
if (!mDivided) {
PointsIt begin = mBucket.begin();
PointsIt end = mBucket.end();
mBucket.erase(std::remove(begin, end, point), end);
return true;
}
if (NW->Remove(point) || NE->Remove(point) || SW->Remove(point) ||
SE->Remove(point)) {
if (!NW->mDivided && !NE->mDivided && !SW->mDivided && !SE->mDivided) {
if (NW->mBucket.empty() && NE->mBucket.empty() && SW->mBucket.empty() &&
SE->mBucket.empty()) {
Merge();
}
}
return true;
}
return false;
}
bool Search(const Point &point) {
if (!mBoundary.Contains(point)) return false;
if (mDivided) {
return NW->Search(point) || NE->Search(point) || SW->Search(point) ||
SE->Search(point);
}
return std::find(mBucket.begin(), mBucket.end(), point) != mBucket.end();
}
void Query(const Range &range, const Callback callback) {
if (!range.Intersects(mBoundary)) return;
if (mDivided) {
NW->Query(range, callback);
NE->Query(range, callback);
SW->Query(range, callback);
SE->Query(range, callback);
} else {
for (auto child : mBucket) {
if (range.Contains(child)) {
callback(child);
}
}
}
}
public:
void Clear() {
if (mDivided) {
NW->Clear();
NE->Clear();
SW->Clear();
SE->Clear();
}
mBucket.clear();
Merge();
}
};
} // namespace forest
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T16:13:53.340",
"Id": "417833",
"Score": "2",
"body": "\"How can I ... allow the user to bring his own Point Class Implementation?\" — I recommend you watch [this CppCon talk by Vinnie Falco](https://www.youtube.com/watch?v=WsUnnYEKPnI) once or twice. I think it's applicable to your situation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T16:19:01.947",
"Id": "417835",
"Score": "0",
"body": "@Quuxplusone Thank you!!! :)"
}
] | [
{
"body": "<h2>General</h2>\n\n<p>You labeled this as C++11; I'll try and stick to that feature set. </p>\n\n<p>Everything after <code>public:</code> or <code>private:</code> gains that access qualifier, so you only have to use it once. </p>\n\n<p>You use <code>using</code>: that is a good practice, <code>using PointsIt = typename std::vector<Point>::iterator;</code> but in most cases where you would need to use an iterator, <code>auto</code> has the same effect and is less work if you change your containers. The other reason why you'll most likely never write access an iterator type directly is that a <em>ranged based <code>for</code> loop</em> should be used instead. </p>\n\n<blockquote>\n<pre><code>QuadTree(const Range &BOUNDARY) : mBoundary(BOUNDARY) {}`\n</code></pre>\n</blockquote>\n\n<p>Capitalization is usually preserved for constants or compile time definitions; <code>boundary</code> would do nicely. The members <code>NW</code>, <code>NE</code>, etc. are not marked as members by your own convention should be <code>mNW</code>, etc. at least. </p>\n\n<p>Your <code>Range</code> which you use with the variable name <code>mBoundary</code>, that is basically the extent or bounding box of the area of the node. There is nothing wrong with using the same name as the class name for a member variable, and it looks like you weren't quite happy with <code>Range</code> as you named the member variable differently. Boundary seems to be a better term than range anyway, 'Extent', 'BoundingBox' would also work. </p>\n\n<p>There doesn't seem to be any specific reason to make the range a class inside of the <code>QuadTree</code>; it's just as comfortable on the outside as on the inside.</p>\n\n<p>I personally prefer the public parts above the private section, but that is really a taste issue.</p>\n\n<h2><code>Range</code></h2>\n\n<p>The you declared the default constructor, but that lets you construct an invalid range. There is no need to make the quadtree a friend; if you just want to save the writing effort, <code>Range</code> could as well be a <code>struct</code> with member access. The defaulted constructor will leave the members in your range uninitialized, that is not a good thing. You could initialize things with <code>{0}</code> but depending on your application that might not be the correct thing to do.</p>\n\n<p>Have you noticed that all the operations you do on your <code>Range</code> structure need to calculate the actual bounds? You would be better off storing the left, right, top and bottom bounds and checking against those.</p>\n\n<h2>QuadTree</h2>\n\n<p>To help with some of the suggestions in the following paragraph, I'd probably split the node type and the tree type. </p>\n\n<p>In most operations you check for each quadrant if the point is in the quadrant, at the worst case (SE) that is 4 <code>Contains</code> calls, but you are trying to insert the point into a quad, besides being totally out of bounds of the tree, the test for the quadrant can be down with 2 checks. The point is either north or south of the horizontal midline, and east or west of the vertical midline. You can ascertain once at the root node if the point is within bounds and then you just need to check which quadrant you want to add the point to. Determining the quadrant for insertion before doing the insertion will reduce the complexity of your code as you will move from the pattern that you have </p>\n\n<pre><code>NW->DoOperation(point) || NE->DoOperation(point) || SW->DoOperation(point) || SE->DoOperation(point)\n</code></pre>\n\n<p>to</p>\n\n<pre><code>auto node = GetQuadrant(point);\nnode->DoOperation(point);\n</code></pre>\n\n<p>Even with 4 nodes replacing your member <code>NW</code>, <code>NE</code>, etc with an array of nodes will reduce complexity somewhat and increase readability.</p>\n\n<p>Depending on the actual use, it might be better to amortize merges, i.e. not immediately merge empty nodes as the tree grows. In a dynamic system with a somewhat constant number of points, you would eventually reach an equilibrium and stop have to allocate new nodes of your tree. As the grid that you are partitioning is regular, a new split would be along the same lines as the old split. If you want, you could give the user a function to collapse the tree back to its minimal form.</p>\n\n<h3>Floating point comparisons</h3>\n\n<p>I don't know how you use this, but unless the values passed into this function for the point are <em>exactly the same</em> as the ones that you added this will fail. In graphical applications and games, floating point values would be compared by looking at an interval; if the values are within the interval they would be considered the same. So unless you pass exactly the same floating point value to functions like <code>Search()</code> or <code>Remove()</code> they will fail.</p>\n\n<h3><code>Insert()</code></h3>\n\n<p>Your insert function already checks if the node is in the bounds, so there is no need to check again; the array with the points can be cleared at the end of the iteration, as all points are moved to their respective quadrants. Using a range-based <code>for</code> loop will also be more idiomatic. I'd also change some of the checks to positive to reduce complexity. As you are iterating over all points you can clear the bucket in one step once you are done.</p>\n\n<h3><code>Remove()</code></h3>\n\n<p>There is no need to introduce the temporary <code>begin</code> and <code>end</code>:</p>\n\n<pre><code> m_bucket.erase(m_bucket.begin(), m_bucket.end(), point), m_bucket.end());\n</code></pre>\n\n<p>works as well</p>\n\n<p>But the return value <code>true</code> only indicates that the point was within the boundary, <em>not</em> that it was actually deleted. </p>\n\n<h3><code>Search()</code></h3>\n\n<p>What is the use for this? Within the domain of a program the user of your API usually knows that whether they added a point to the tree or not. Being able to look it up might not really be helpful.</p>\n\n<h3><code>Query()</code></h3>\n\n<p>Executing a callback for each found point might not yield the best performance. Depending on use, I'd probably prefer an interface that just returns the points that are part of the query. What this is doing here is more <code>ProcessPointsInRange()</code>. If you allow the user to pass in the results array then you can even amortize allocations over time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T14:41:23.957",
"Id": "418884",
"Score": "0",
"body": "So basically I made something meaningless xD."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T14:42:17.637",
"Id": "418885",
"Score": "0",
"body": "Thanks for the constructive criticism and the thorough feedback. I will try to follow your recommendations and hopefully improve! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T14:57:45.143",
"Id": "418886",
"Score": "0",
"body": "One question. Do you recommend that I make an array of nodes or an array of node pointers? Also, I am thinking of using std::array<QuadTree, 4> for that instead of the C way to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T13:29:43.177",
"Id": "418967",
"Score": "1",
"body": "It's not meaningless, I don't know if you implemented this out of a need or as an exercise, it's hard to come up with APIs for things that you don't directly use. A lot of these things need iterations, this is a good first attempt. Making an `array` of pointers would make things easier to do and read in some places, post c++11 an `array` in c++ always means `std::array`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T14:12:57.087",
"Id": "418970",
"Score": "0",
"body": "Yes I was assigned to write this for an exercise but I decided to try and make it more generic. Thank you so much Harald!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T19:45:50.100",
"Id": "216496",
"ParentId": "215943",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216496",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T16:04:34.963",
"Id": "215943",
"Score": "5",
"Tags": [
"c++",
"beginner",
"c++11"
],
"Title": "Quad Tree Implementation in C++11"
} | 215943 |
<p>Mainly looking for feedback on my use of smart pointers to implement a standard stack. For interview level production code I have also include a namespace and asserts to test my class, let me know if that would be appropriate for an interview. I'd like feedback on my pointer management to avoid memory leaks, like how I have the option to use the classic <code>SomeObjectNameHere*</code> pointer to swap data in my <code>swap</code> function or the <code>unique_ptr</code> swap method. </p>
<p>Other than that I have taken feedback from all my previous posts to properly. Let me know what you think</p>
<pre><code>#include <cassert>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
namespace sonsprl
{
class Stack
{
private:
class Node
{ private:
int m_data;
std::unique_ptr<Node> m_previous;
public:
Node(int data, std::unique_ptr<Node>& previous) {
m_data = data;
m_previous = std::move(previous);
}
~Node() { m_previous.reset(); }
const int data() { return m_data; }
std::unique_ptr<Node>& previous() { return m_previous; }
};
int m_size{0};
std::unique_ptr<Node> m_top;
public:
~Stack() { m_top.reset(); }
void push_back(int data) {
m_top = std::unique_ptr<Node>(new Node(data, m_top));
++m_size;
}
void pop_back() {
if(!m_top) {
throw std::out_of_range("ERROR: Can not pop. Stack empty.");
}
else {
m_top = std::move(m_top->previous());
--m_size;
}
}
int top() {
return m_top.get()->data();
}
int size() {
return m_size;
}
bool empty() {
return (m_size == 0) ? true : false;
}
void swap(Stack& other_stack) {
m_top.swap(other_stack.m_top);
// Node* other_top = other_stack.m_top.release();
// other_stack.m_top = std::move(m_top);
// m_top = std::unique_ptr<Node>(new Node(other_top->data(), other_top->previous()));
}
friend std::ostream& operator<<(std::ostream& os, Stack& stack) {
std::string stack_string = "";
Node* current = stack.m_top.get();
for(; current; current = current->previous().get()) {
stack_string = stack_string + '|' + std::to_string(current->data()) + '|' + '\n';
}
os << stack_string;
os << "---\n";
return os;
}
};
}
int main()
{
sonsprl::Stack stack;
try {
stack.pop_back();
} catch(const std::out_of_range& e) {
std::cout << e.what() << '\n';
}
assert(stack.empty());
stack.push_back(1);
stack.push_back(2);
stack.push_back(3);
assert(stack.size() == 3);
assert(stack.top() == 3);
stack.pop_back();
stack.pop_back();
assert(stack.size() == 1);
std::cout << stack << '\n';
stack.push_back(4);
stack.push_back(4);
assert(stack.empty() == false);
sonsprl::Stack swap_stack;
swap_stack.push_back(5);
swap_stack.push_back(6);
swap_stack.push_back(7);
swap_stack.push_back(8);
assert(swap_stack.top() == 8);
std::cout << "pre swap\n";
std::cout << stack << '\n';
std::cout << swap_stack << '\n';
swap_stack.swap(stack);
std::cout << "post swap\n";
std::cout << stack << '\n';
std::cout << swap_stack << '\n';
assert(stack.top() == 8);
assert(swap_stack.top() == 4);
std::cout << "passed all stack tests :) \n";
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T18:30:45.127",
"Id": "417846",
"Score": "3",
"body": "As a quick comment: one thing you should try to pay more attention to is const correctness. Again, there are many member functions that should be const. If the function does not modify the object contents, make it const."
}
] | [
{
"body": "<ul>\n<li><p><code>swap</code> does not swap sizes.</p></li>\n<li><p>If <code>pop_back</code> throws on empty stack, <code>top</code> shall also throw.</p></li>\n<li><p>I see no reason for an <code>operator<<</code> to build a string.</p>\n\n<pre><code> os << '|' << std::to_string(current->data()) << '|\\n';\n</code></pre>\n\n<p>in a loop achieves the same result.</p>\n\n<p>I would also consider letting <code>Node</code> to output itself with <code>Node::operator<<</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T18:32:06.417",
"Id": "215952",
"ParentId": "215944",
"Score": "6"
}
},
{
"body": "<h2>Overall</h2>\n\n<p>Not sure I agree with the use of <code>std::unique_ptr</code> inside of <code>Node</code>. <strong>BUT</strong> I can't really argue against it. So I am not going to push the point.</p>\n\n<p>You need to concentrate on your const correctness.</p>\n\n<h2>Design</h2>\n\n<p>Using a linked list for a stack seems very inefficient way of doing this. Each object that you save required an additional pointer. In this case were your data is a <code>int</code> you are basically doubling the space requirements (that's not including any overhead for memory management imposed by the system libraries).</p>\n\n<p>The standard provides a <code>std::stack</code> class. This uses the <code>std::deque</code> underneath the hood (default) to store the data.</p>\n\n<p>You should think about what it would take to templatize your <code>Stack</code> class. Storing <code>int</code> is good as a test; but there is no reason you could not store any object. Once you have done that there are a couple of extra functions that would be nice:</p>\n\n<pre><code> void push_back(T const& data); // insert by copy.\n void push_back(T&& data); // insert by move\n template<typename... Args>\n void emplace_back(Args&& p...); // construct in place at the back\n</code></pre>\n\n<h2>Code Review</h2>\n\n<p>I assume this has some meaning to you?</p>\n\n<pre><code>namespace sonsprl\n</code></pre>\n\n<hr>\n\n<p>Passing a <code>std::unqiue_ptr</code> by non-cost referece is a bit strange. I would normally expect that to be passed by r-value reference. When I was reading the <code>Stack</code> class below it confused me that you were passing a <code>std::unique_ptr</code> as a parameter without the <code>std::move</code>.</p>\n\n<pre><code> Node(int data, std::unique_ptr<Node>& previous) {\n</code></pre>\n\n<p>You are affectively hiding the transfer of ownership that the C++ community has tried very hard to make explicit and visible.</p>\n\n<hr>\n\n<p>Both your destructors are us-less:</p>\n\n<pre><code> ~Node() { m_previous.reset(); }\n ~Stack() { m_top.reset(); }\n</code></pre>\n\n<p>I would remove both.</p>\n\n<hr>\n\n<p>You could mark this function as <code>const</code>. I would not bother marking the <code>int</code> const (but it does not hurt). When you convert this into a template you should return by <code>const</code> reference. <code>T const&</code>.</p>\n\n<pre><code> const int data() { return m_data; }\n\n // I would have written like this:\n T const& data() const { return m_data; }\n //^^^^^^ ^^^^^\n</code></pre>\n\n<hr>\n\n<p>As mentioned above. I don't like the passing of <code>m_top</code> as a parameter (and it being changed inside the <code>Node</code> constructor).</p>\n\n<pre><code> void push_back(int data) {\n m_top = std::unique_ptr<Node>(new Node(data, m_top));\n ++m_size;\n }\n</code></pre>\n\n<p>I would have written it like this:</p>\n\n<pre><code> void push_back(int data) {\n m_top = std::unique_ptr<Node>(new Node(data, std::move(m_top)));\n ++m_size;\n }\n</code></pre>\n\n<p>This way I can explicitly show that I am transferring ownership of <code>m_top</code> into the <code>Node</code> and that the newly created object is taking the place as the new value of <code>m_top</code>.</p>\n\n<hr>\n\n<p>There is an <code>empty()</code> function that allows users to check if the stack is empty before calling <code>pop_back()</code>. So also checking inside is a waste of time. If you really want to check then you should provide a checked and an unchecked version of <code>pop</code>.</p>\n\n<pre><code> void pop_back() {\n if(!m_top) {\n throw std::out_of_range(\"ERROR: Can not pop. Stack empty.\");\n }\n else {\n m_top = std::move(m_top->previous());\n --m_size;\n }\n }\n</code></pre>\n\n<p>Note: the main use case is going to be something like this:</p>\n\n<pre><code> while(!stack.empty()) {\n stack.pop_back(); // I just checked its empty\n } // are you going to check again?\n</code></pre>\n\n<p>If you look at functions in the standard library they tend not to throw (even if this would cause the object to be invalid). Instead the writters provide mechanisms to validate the pre-conditions of method so the user can do the check manually. Sometimes they also provide checked alternatives. That way a user of the functionality does not need to pay an extra cost (for the check) if they have already validate the pre-conditions.</p>\n\n<p>An example of this is:</p>\n\n<pre><code>std::vector::operator[]std::size_t index) // unchecked access into the container.\nstd::vector::afstd::size_t index) // un-unchecked access into the container.\n</code></pre>\n\n<hr>\n\n<p>The <code>top()</code> function should be <code>const</code>. Your return value is <strong>inconsistent</strong> with the return type from <code>data()</code> (which returns a const). Consistency is king in programming.</p>\n\n<p>Talking about consistency. The <code>pop_back()</code> function checks the state of the container (and throws if it is not valid). To be consistent the <code>top()</code> method should perform a similar check (or both of them should not perform a check).</p>\n\n<pre><code> int top() {\n return m_top.get()->data();\n }\n</code></pre>\n\n<p>Do you need to call <code>get()</code> above?</p>\n\n<hr>\n\n<p>Another couple of function that should be marked <code>const</code></p>\n\n<pre><code> int size() {\n bool empty() {\n</code></pre>\n\n<hr>\n\n<p>Swap should be marked <code>noexcept</code>:</p>\n\n<pre><code> void swap(Stack& other_stack) {\n m_top.swap(other_stack.m_top);\n // Node* other_top = other_stack.m_top.release();\n // other_stack.m_top = std::move(m_top);\n // m_top = std::unique_ptr<Node>(new Node(other_top->data(), other_top->previous()));\n }\n</code></pre>\n\n<p>I don't see you swapping the size!!!!!!<br>\nEvery part of the swapped object should be exchanged.</p>\n\n<p>The normal pattern for this is to use <code>swap()</code> on each member.</p>\n\n<pre><code> void swap(Stack& other) noexcept {\n using std::swap;\n swap(m_top, other.m_top);\n swap(m_size, other.m_size);\n }\n</code></pre>\n\n<p>It's also nice to add a friend function so others can do the swap naturally as well.</p>\n\n<pre><code> friend void swap(Stack& lhs, Stack& rhs) {\n lhs.swap(rhs);\n }\n</code></pre>\n\n<hr>\n\n<p>When printing. The value being printed is normally marked <code>const</code> (because printing it should not change it).</p>\n\n<pre><code> friend std::ostream& operator<<(std::ostream& os, Stack const& stack) { \n ^^^^\n</code></pre>\n\n<p>Why are you building a string to output?</p>\n\n<pre><code> std::string stack_string = \"\";\n // STUFF\n os << stack_string;\n</code></pre>\n\n<p>Just print each value directly to the stream.</p>\n\n<pre><code> Node* current = stack.m_top.get();\n for(; current; current = current->previous().get()) {\n os << '|' << current->data() << \"|\\n\";\n }\n</code></pre>\n\n<hr>\n\n<p>One late entry:</p>\n\n<pre><code> return (m_size == 0) ? true : false;\n</code></pre>\n\n<p>You are using a bool test to decide which bool to return. Simpler to simply return the result of the test.</p>\n\n<pre><code> return m_size == 0;\n</code></pre>\n\n<hr>\n\n<p>How I would have written it (apart from keeping the std::unique_ptr in Node).</p>\n\n<pre><code>namespace ThorsAnvil\n{\n namespace Container\n {\n template<typename T>\n class Stack\n {\n struct Node;\n using Chain = std::unique_ptr<Node>;\n struct Node\n {\n T data;\n Chain prev;\n Node(Chain&& prev, T const& data)\n : data(data)\n , prev(std::move(prev))\n {}\n Node(Chain&& prev, T&& data)\n : data(std::move(data))\n , prev(std::move(prev))\n {}\n template<typename... Args>\n Node(Chain&& prev, Args&&... p)\n : data(std::forward<Args>(p)...)\n , prev(std::move(prev))\n {}\n };\n int m_size{0};\n std::unique_ptr<Node> m_top;\n public:\n void push_back(T const& data) {\n m_top = std::make_unique<Node>(std::move(m_top), data);\n ++m_size;\n }\n void push_back(T&& data) {\n m_top = std::make_unique<Node>(std::move(m_top), std::move(data));\n ++m_size;\n }\n template<typename... Args>\n void push_back(Args&&... p) {\n m_top = std::make_unique<Node>(std::move(m_top), std::forward<Args>(p)...);\n ++m_size;\n }\n void pop_back() {\n m_top = std::move(m_top->prev);\n --m_size;\n }\n T const& top() const {return m_top->data;}\n int size() const {return m_size;}\n bool empty() const {return m_size == 0;}\n void swap(Stack& other) noexcept {\n using std::swap;\n swap(m_top, other.m_top);\n swap(m_size, other.m_size);\n }\n friend void swap(Stack& lhs, Stack& rhs) {\n lhs.swap(rhs);\n }\n friend std::ostream& operator<<(std::ostream& os, Stack const& stack) {\n Node* current = stack.m_top.get();\n for(; current; current = current->prev.get()) {\n os << \"|\" << current->data << \"|\\n\";\n }\n return os << \"---\\n\";\n }\n };\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T19:16:29.350",
"Id": "417852",
"Score": "1",
"body": "Just curious, independent of whether a redoing a list here is a good solution or not. These days I would promote using `std::unique_ptr` in favor over raw pointers. Is there a case to be made against the use of one over the other ? \nThis is not meant as flame bait, we all make technical decisions and this one still seems to have people a little bit puzzled."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T19:34:21.473",
"Id": "417856",
"Score": "0",
"body": "Thanks I've modified my code! In your swap is there a reason you're using `swap(m_top, other.m_top);` over the `unique_ptr<...>::swap`? In my Node constructor I am calling move internally, do I need to still need to have this call `new Node(data, std::move(m_top)` in my `push_back` function? I can not seem to get this new implementation to work with move used as a function parameter. Why do I not need my destructors?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T19:38:14.137",
"Id": "417858",
"Score": "0",
"body": "How can I create a smart pointer without passing it as a parameter? Docs here note passing it as a param as you mentioned is bad practice https://docs.microsoft.com/en-us/cpp/cpp/smart-pointers-modern-cpp"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T19:42:57.000",
"Id": "417860",
"Score": "0",
"body": "`BUT I can really argue against it. So I am not going to push the point.` Did you mean *can't argue against it*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T19:56:54.250",
"Id": "417862",
"Score": "0",
"body": "@yuri fixed to can't"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T20:01:07.670",
"Id": "417863",
"Score": "0",
"body": "@HaraldScheirich I would argue that there are two places that we manage memory. Single item objects are managed via smart pointers. While multi item objects are managed via containers. Both of these constructs are designed to manage memory but we don't use smart pointers to implement containers as the containers are the method for managing the memory. Here we are building a container and it (the container) should manage the memory. Now as a beginner I can see the usefulness of using smart pointers in this context to learn other features. Hence I don't argue against it,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T20:04:16.470",
"Id": "417864",
"Score": "1",
"body": "@greg In the constructor. I would use std::move to pass the m_top into the constructor. But this is because I would also make the underlying node take an r-value reference. Yes you still need to use `std::move` inside the constructor because even though the parameter is bound as an r-value reference a named value itself is not an r-value reference and must be made one by using `std::move`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T20:05:15.253",
"Id": "417865",
"Score": "1",
"body": "@greg The rule of zero is why you don't need destructors. The `std::unique_ptr` destructor will automatically be called and release its resources. You doing it manually is not required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T20:11:11.440",
"Id": "417866",
"Score": "0",
"body": "@greg Not sure what you are referring to on the MS page you linked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T20:38:33.363",
"Id": "417868",
"Score": "1",
"body": "@greg Update to show how I would do it (so you can see everything in context)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T00:07:42.580",
"Id": "417878",
"Score": "0",
"body": "The second push_back is moving from a non-const reference to the data rather than a rvalue reference is that intentional ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T17:40:58.273",
"Id": "417967",
"Score": "0",
"body": "@HaraldScheirich No that was a bug. Fixed."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T18:53:49.360",
"Id": "215954",
"ParentId": "215944",
"Score": "8"
}
},
{
"body": "<pre><code>class Node {\n private:\n int m_data;\n std::unique_ptr<Node> m_previous;\n public:\n Node(int data, std::unique_ptr<Node>& previous) {\n m_data = data;\n m_previous = std::move(previous);\n }\n</code></pre>\n\n<p>Since <code>Node</code> is an implementation detail of <code>Stack</code>, you don't need to hide <code>Node</code>s members <code>data</code> and <code>previous</code> from <code>Stack</code>. Consider using aggregate initialization so that members can be directly manipulated.</p>\n\n<pre><code> ~Node() { m_previous.reset(); }\n</code></pre>\n\n<p>Since the destructor isn't doing anything after <code>std::unique_ptr<T>::reset()</code>, it's equivalent to letting the class call the destructor of your <code>std::unique_ptr<Node></code> member.</p>\n\n<pre><code> ~Node() { }\n</code></pre>\n\n<p>Now, you have chained your pointers such that the current node is the owner of the previous node which owns the previous node and so on. When we call the destructor, this is essentially what is happening</p>\n\n<pre><code>m_previous.reset() calls \n m_previous->~Node()\n m_previous->m_previous->~Node()\n m_previous->m_previous->m_previous->~Node()\n m_previous->m_previous->m_previous->m_previous->~Node()\n m_previous->m_previous->m_previous->m_previous->m_previous->~Node()\n and so on\n</code></pre>\n\n<p>And it's correct in that each node gets cleaned up and all the cleanup happens automatically. Unfortunately, it's also recursive which means its bounded by the stack (memory) depth. To fix this, you'll need to iteratively remove elements.</p>\n\n<p>Whenever you define any of the special member functions (destructor, copy/move constructor, copy/move assignment), you should consider whether your class needs the others. This is commonly known as the rule of five. By providing the destructor, the move operations are not declared. Normally, the copy operations are defaulted, but <code>std::unique_ptr</code> as a data member results in those being implicitly deleted. You'll need to implement the copy and move operations if your stack is to have those value semantics. The general guideline is that if you explicitly declare any of the special member functions, then explicitly declare all of the special member functions and explicitly <code>=default</code> (opt into the implicit behavior), <code>=delete</code> (opt out of the implicit behavior), or user-define each of them.</p>\n\n<pre><code> const int data() { return m_data; }\n</code></pre>\n\n<p><code>const</code> as a qualifier on the return type is ignored here.</p>\n\n<hr>\n\n<pre><code>class Stack {\n ...\n public:\n ~Stack() { m_top.reset(); }\n</code></pre>\n\n<p>Same issues as node, from recursive destruction to missing copy/move operations.</p>\n\n<pre><code> void push_back(int data) {\n m_top = std::unique_ptr<Node>(new Node(data, m_top));\n ++m_size;\n }\n</code></pre>\n\n<p>Avoid <code>new</code> and prefer <code>std::make_unique</code> to make <code>std::unique_ptr</code>s. It cuts down on the duplication and enforces consistency when you need safety in more complex initialization sequences.</p>\n\n<pre><code> void pop_back() {\n if(!m_top) {\n throw std::out_of_range(\"ERROR: Can not pop. Stack empty.\");\n }\n else {\n m_top = std::move(m_top->previous());\n --m_size;\n }\n }\n</code></pre>\n\n<p>Don't use <code>else</code> after language constructs that interrupts control flow (<code>return</code>, <code>break</code>, <code>continue</code>, <code>goto</code>).</p>\n\n<pre><code> int top() {\n return m_top.get()->data();\n }\n</code></pre>\n\n<p>Be consistent with the naming. If directionality matters to you, then <code>back()</code> would be consistent with <code>push_back()</code> and <code>pop_back()</code>. <code>top()</code> would go better with functions like <code>push()</code>, and <code>pop()</code>.</p>\n\n<p>Be consistent with your exception handling. If you throw on an empty stack <code>pop_back()</code>, then you should throw on an empty stack <code>top()</code>.</p>\n\n<p>In order to modify the top value, the user has to pop (deallocate) and push (allocate). Consider allowing the user to access the top element by reference and modify the element in place.</p>\n\n<pre><code> bool empty() {\n return (m_size == 0) ? true : false;\n }\n</code></pre>\n\n<p><code>m_size == 0</code> will return a boolean that maps to the same exact values in your ternary. The compiler knows that and optimizes it for you, but you could help readers and just do it yourself.</p>\n\n<pre><code> void swap(Stack& other_stack) {\n m_top.swap(other_stack.m_top);\n // Node* other_top = other_stack.m_top.release();\n // other_stack.m_top = std::move(m_top);\n // m_top = std::unique_ptr<Node>(new Node(other_top->data(), other_top->previous()));\n }\n</code></pre>\n\n<p>You forgot to swap the size.</p>\n\n<pre><code> friend std::ostream& operator<<(std::ostream& os, Stack& stack) {\n std::string stack_string = \"\";\n Node* current = stack.m_top.get();\n for(; current; current = current->previous().get()) {\n stack_string = stack_string + '|' + std::to_string(current->data()) + '|' + '\\n';\n }\n os << stack_string;\n os << \"---\\n\";\n return os;\n }\n</code></pre>\n\n<p><code>stack</code> is passed in as a reference. <code>operator<<</code> doesn't modify the contents of <code>stack</code> and can be qualified with <code>const</code>.</p>\n\n<p>You don't have to convert <code>data</code> (<code>int</code>) to a <code>std::string</code> to stream into a <code>std::ostream</code>. There is already an <a href=\"https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt\" rel=\"nofollow noreferrer\">overload</a> that does this for you.</p>\n\n<p>Do you even need <code>operator<<()</code>? A stack is a last in-first out container. Inspection only exists on the latest element pushed on the stack that hasn't been popped. This function also requires the inclusion of <code><iostream></code>. A static constructor is transparently injected into every translation unit that includes this header, whether IOStreams are used or not in the user application.</p>\n\n<hr>\n\n<p>Overall, you should read up on <code>const</code>-correctness and <code>noexcept</code> specification. As for the design of your stack, I would consider splitting the management of the nodes (<code>forward_list</code>?) from the interface of <code>stack</code>, which could be adapted over an existing sequence interface.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T04:30:53.517",
"Id": "215972",
"ParentId": "215944",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "215954",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T16:32:34.720",
"Id": "215944",
"Score": "5",
"Tags": [
"c++",
"c++11",
"stack",
"pointers",
"namespaces"
],
"Title": "Stack Interview Code methods made from class Node and Smart Pointers"
} | 215944 |
<p>I've added a timer to my code and the bottleneck comes when I'm looping through 47 rows and inputting data from a dictionary that I previously loaded with values.</p>
<p>Since i use these files for a lot of different things I've set up public variables in order to avoid setting them up for every new code.</p>
<p>So my question is, is there a quicker way to pull data from the dictionary based on criteria in specific cells? The line directly below is repeated 8 times for the 8 different columns being populated with dictionary data, each column takes .20 seconds to complete, so 1.6 seconds per each iteration in the w loop (orderStart to orderEnd). </p>
<pre><code>Cells(w, OF_clearanceColumn1) = stationclearanceData(Cells(w, OF_stationColumn).Value & Cells(orderStart - 1, OF_clearanceColumn1).Value)
</code></pre>
<p>Timer stats:</p>
<pre><code>3.4453125 Open client database, determine which account we're on
3.484375 Find last 4 weks and order range
7.31640625 Adding columns and formating
7.61328125 loop through last 4 weeks, add station clearance and P&L data to dictionary
7.6484375 find range of cumulative, add clearance and P&L for 2019
100.90234375 adding data from dictionary to order file
</code></pre>
<p><strong>NEW TIMER STATS, THANKS TO AJD AND MOVING DATA FROM DICTIONARY TO ARRAY TO RANGE.</strong></p>
<pre><code>1.71875 Open client database, determine which account we're on
1.75 Find last 4 weeks and order range
5.3203125 Adding columns and formating
5.6171875 loop through last 4 weeks, add station clearance and P&L data to dictionary
5.6640625 find range of cumulative, add clearance and P&L for 2019
7.6171875 adding data from dictionary to order file
</code></pre>
<p>Anyway, below is the code...</p>
<pre><code>Sub Orders_Historicals_autofilterdict()
Dim start As Double
start = Timer
''--------------------------------------
''Static Variables
''--------------------------------------
Call DefinedVariables
Dim orderFile As Variant
Dim orderStart As Long
Dim orderEnd As Long
Dim clientdataFile As Variant
Dim internalFile As Variant
Dim dateStart As Long
Dim stationStart As Long
Dim stationEnd As Long
Dim currentStation As String
Dim currentWeek As String
Dim dictData As New Scripting.Dictionary
Dim stationclearanceData As New Scripting.Dictionary
Dim stationplData As New Scripting.Dictionary
Dim key As Variant
Dim fileOnly As String
Dim networkOnly As String
Dim i As Long
Dim w As Long
Dim t As Long
Dim plTotal As Long
Dim clearTotal As Long
Dim stationHash As String
''--------------------------------------
''Dictionary the Order Abbreviations
''--------------------------------------
Application.ScreenUpdating = False
Set orderFile = ActiveWorkbook.ActiveSheet
Workbooks.Open clientdataLocation
Set clientdataFile = ActiveWorkbook.Sheets(dan_location) '/ Change sheet when using on different computer
clientdataFile.Activate
For i = 1 To Cells(Rows.count, 1).End(xlUp).row
If dictData.Exists(Cells(i, clientOrder).Value) Then
Else: dictData.Add Cells(i, clientOrder).Value, i
End If
Next
''--------------------------------------
''Determine Account/Network & Open Internal Associated with Order
''--------------------------------------
orderFile.Activate
fileOnly = ActiveWorkbook.Name
fileOnly = Left(fileOnly, InStr(fileOnly, ".") - 1)
If InStr(fileOnly, 2) > 0 Or InStr(fileOnly, 3) > 0 Then
fileOnly = Left(fileOnly, Len(fileOnly) - 1)
End If
networkOnly = ActiveWorkbook.Name
networkOnly = Mid(networkOnly, InStr(networkOnly, "IO.") + 3)
networkOnly = Left(networkOnly, InStr(networkOnly, ".") - 1)
Workbooks.Open Filename:=clientdataFile.Cells(dictData(fileOnly), clientInternal).Value
Set internalFile = ActiveWorkbook
internalFile.Sheets(WT_newWeek).Activate
Debug.Print Timer - start & " Open client database, determine which account we're on"
''--------------------------------------
''Find Last 4 Dates & Column Header for Orders
''--------------------------------------
For i = 1 To 700
If Cells(i, 1) = WT_newWeek Then
dateStart = i
ElseIf Cells(i, 1) = "Station" Then
stationStart = i + 1
Exit For
End If
Next
For i = stationStart To 700
If Cells(i, 1).Value = Cells(stationStart - 2, 1).Value & " Total" Then
stationEnd = i - 1
Exit For
End If
Next
orderFile.Activate
For i = 1 To 700
If Cells(i, 1) = "Station" Then
orderStart = i + 1
Exit For
End If
Next
For i = orderStart To 700
If Len(Cells(i, 1)) = 0 And Len(Cells(i - 1, 1)) = 0 And Len(Cells(i - 2, 1)) = 0 Then
orderEnd = i - 3
Exit For
End If
Next
Debug.Print Timer - start & " Find last 4 weeks and order range"
''--------------------------------------
''Add Dates to Order Header and Formatting
''--------------------------------------
Cells(orderStart - 1, OF_buyAlgoColumn) = "Algorithm Recommendation"
Cells(orderStart - 1, OF_totalplColumn) = "Total P&L"
Cells(orderStart - 1, OF_totalclearanceColumn) = "Total Clearance %"
Cells(orderStart - 1, OF_clearanceColumn1) = internalFile.Sheets(WT_newWeek).Cells(dateStart, 1)
Cells(orderStart - 1, OF_clearanceColumn2) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 1, 1)
Cells(orderStart - 1, OF_clearanceColumn3) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 2, 1)
Cells(orderStart - 1, OF_clearanceColumn4) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 3, 1)
Cells(orderStart - 1, OF_plColumn1) = internalFile.Sheets(WT_newWeek).Cells(dateStart, 1)
Cells(orderStart - 1, OF_plColumn2) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 1, 1)
Cells(orderStart - 1, OF_plColumn3) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 2, 1)
Cells(orderStart - 1, OF_plColumn4) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 3, 1)
Range(Cells(orderStart - 2, OF_clearanceColumn1), Cells(orderStart - 2, OF_clearanceColumn4)) = "Clearance"
Range(Cells(orderStart - 2, OF_plColumn1), Cells(orderStart - 2, OF_plColumn4)) = "P&L"
Cells(orderStart - 1, OF_stationColumn).Copy
Range(Cells(orderStart - 1, OF_buyAlgoColumn), Cells(orderStart - 1, OF_plColumn4)).PasteSpecial xlPasteFormats
Cells(orderStart, OF_stationColumn).Copy
Range(Cells(orderStart - 2, OF_clearanceColumn1), Cells(orderStart - 2, OF_plColumn4)).PasteSpecial xlPasteFormats
Range(Cells(orderStart - 2, OF_buyAlgoColumn), Cells(orderEnd, OF_plColumn4)).HorizontalAlignment = xlCenter
Cells(orderStart, OF_stationColumn).Copy
Range(Cells(orderStart, OF_buyAlgoColumn), Cells(orderEnd, OF_plColumn4)).PasteSpecial xlPasteFormats
Cells(orderStart, OF_totalColumn).Copy
Range(Cells(orderStart, OF_plColumn1), Cells(orderEnd, OF_plColumn4)).PasteSpecial xlPasteFormats
Range(Cells(orderStart, OF_totalplColumn), Cells(orderEnd, OF_totalplColumn)).PasteSpecial xlPasteFormats
Range(Cells(orderStart, OF_totalclearanceColumn), Cells(orderEnd, OF_clearanceColumn4)).NumberFormat = "0%"
Range(Cells(orderStart - 2, OF_buyAlgoColumn), Cells(orderEnd, OF_plColumn4)).FormatConditions.Delete
Range(Columns(OF_buyAlgoColumn), Columns(OF_plColumn4)).AutoFit
Debug.Print Timer - start & " Adding columns and formating"
''--------------------------------------
''Add Clearance and P&L by Date to Dictionary
''--------------------------------------
For i = OF_clearanceColumn1 To OF_clearanceColumn4
currentWeek = Cells(orderStart - 1, i).Value
internalFile.Sheets(currentWeek).Activate
For t = 1 To 700
If Cells(t, 1) = "Station" Then
stationStart = t + 1
Exit For
End If
Next
For t = stationStart To 700
If Cells(t, 1).Value = Cells(stationStart - 2, 1).Value & " Total" Then
stationEnd = i - 1
Exit For
End If
If stationclearanceData.Exists(Cells(t, WT_stationColumn).Value & currentWeek) Then
Else:
On Error Resume Next
stationclearanceData.Add Cells(t, WT_stationColumn).Value & currentWeek, Cells(t, WT_mediaactColumn).Value / Cells(t, WT_mediaestColumn).Value
stationplData.Add Cells(t, WT_stationColumn).Value & currentWeek, Cells(t, WT_profitColumn).Value
End If
Next
orderFile.Activate
Next
Debug.Print Timer - start & " loop through last 4 weeks, add station clearance and P&L data to dictionary"
''--------------------------------------
''Add Cumulative Clearance and P&L to Dictionary
''--------------------------------------
internalFile.Sheets("Cumulative").Activate
For t = 5 To 70000
If Cells(t, 1) = "" And Cells(t + 1, 1) = "" And Cells(t + 2, 1) = "" Then
stationEnd = t + 1
Exit For
End If
Next
For t = 5 To stationEnd
If Cells(t, CT_yearColumn) = 2019 Then
If stationclearanceData.Exists(Cells(t, CT_hashColumn).Value) Then
Else:
On Error Resume Next
stationclearanceData.Add Cells(t, CT_hashColumn).Value, Cells(t, CT_clearanceColumn).Value
stationplData.Add Cells(t, CT_hashColumn).Value, Cells(t, CT_invoiceColumn).Value - Cells(t, CT_actcostColumn).Value
End If
End If
Next
Debug.Print Timer - start & " find range of cumulative, add clearance and P&L for 2019"
orderFile.Activate
''--------------------------------------
''Loop Through Stations on Order File and Update Based on Dictionary Values
''--------------------------------------
For w = orderStart To orderEnd
If Cells(w, OF_stationColumn) <> "" Then
If Cells(w, OF_stationColumn) <> Cells(w - 1, OF_stationColumn) Then
stationHash = Cells(w, OF_stationColumn).Value & " " & Cells(w, OF_trafficColumn).Value & " Total"
On Error Resume Next
Cells(w, OF_clearanceColumn1) = stationclearanceData(Cells(w, OF_stationColumn).Value & Cells(orderStart - 1, OF_clearanceColumn1).Value)
Cells(w, OF_clearanceColumn2) = stationclearanceData(Cells(w, OF_stationColumn).Value & Cells(orderStart - 1, OF_clearanceColumn2).Value)
Cells(w, OF_clearanceColumn3) = stationclearanceData(Cells(w, OF_stationColumn).Value & Cells(orderStart - 1, OF_clearanceColumn3).Value)
Cells(w, OF_clearanceColumn4) = stationclearanceData(Cells(w, OF_stationColumn).Value & Cells(orderStart - 1, OF_clearanceColumn4).Value)
Cells(w, OF_plColumn1) = stationplData(Cells(w, OF_stationColumn).Value & Cells(orderStart - 1, OF_plColumn1).Value)
Cells(w, OF_plColumn2) = stationplData(Cells(w, OF_stationColumn).Value & Cells(orderStart - 1, OF_plColumn2).Value)
Cells(w, OF_plColumn3) = stationplData(Cells(w, OF_stationColumn).Value & Cells(orderStart - 1, OF_plColumn3).Value)
Cells(w, OF_plColumn4) = stationplData(Cells(w, OF_stationColumn).Value & Cells(orderStart - 1, OF_plColumn4).Value)
Cells(w, OF_totalplColumn) = stationplData(stationHash)
Cells(w, OF_totalclearanceColumn) = stationclearanceData(stationHash)
End If
End If
Next
Debug.Print Timer - start & " adding data from dictionary to order file"
clientdataFile.Activate
ActiveWorkbook.Close saveChanges:=False
Application.ScreenUpdating = True
Range(Cells(orderStart - 2, OF_buyAlgoColumn), Cells(orderEnd, OF_plColumn4)).HorizontalAlignment = xlCenter
MsgBox ("Buy Algorithm Complete")
End Sub
</code></pre>
| [] | [
{
"body": "<p>Obligatory message: Please ensure you use <code>Option Explicit</code> at the start of every module.</p>\n\n<h2>Code readability</h2>\n\n<p>The first thing that hits me is a wall of declarations. That and the double spacing makes it hard to review this code. Are all the variables used? I know that there are some variables in there that are not in that wall of declarations.</p>\n\n<p>You are also happy to spread the lines out, but then use \"scrunching\" techniques such as <code>Else: dictData.Add Cells(i, clientOrder).Value, i</code></p>\n\n<p>Some of the code here can be broken into logic chunks - either as subroutines or functions. Remember, you can pass parameters to these routines!</p>\n\n<h2>DefinedVariables?</h2>\n\n<p>I don't know what <code>DefinedVariables</code> does.</p>\n\n<p><code>Call</code> is deprecated. You just use</p>\n\n<pre><code>DefinedVariables\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>Call DefinedVariables\n</code></pre>\n\n<h2>Active<em>thingies</em></h2>\n\n<p>You use the active workbook (explicitly and implicitly), active sheet (explicitly and implicitly) and active cell/range (implicitly) a lot. In reality, you can never be sure what is the active book, sheet or cell, you just don't know if something has changed the focus outside of your macro.</p>\n\n<p>There are some occasions within Excel VBA where immediately grabbing the active object is necessary (e.g. when copying a sheet), but for pretty much all cases you can explicitly qualify the object you are using to prevent the code being hijacked by something that is on screen.</p>\n\n<p>Having said that, activating something while screen updating is off is a null activity.</p>\n\n<h2>Object typing</h2>\n\n<p>You declare variables as <code>Variant</code>, but then use them for objects</p>\n\n<pre><code>Dim clientdataFile As Variant\nSet clientdataFile = ActiveWorkbook.Sheets(dan_location) '/ Change sheet when using on different computer\n</code></pre>\n\n<p>If you are going to use it for worksheets, then declare it as such!</p>\n\n<pre><code>Dim clientdataFile As Worksheet\n</code></pre>\n\n<h2>Strange use of inbuilt functions</h2>\n\n<p><code>InStr(fileOnly, 2)</code> is not how InStr is supposed to be used. I suspect that this code does not work as intended - have you checked this?</p>\n\n<h2>Use Arrays instead of looping through cells</h2>\n\n<p>There have been numerous discussions in these hallowed halls about the performance hit of switching between the Excel Model and the VBA model. And every loop that calls a range or a cell performs that switch.\nThe best option is to out the range into an array instead of looping.</p>\n\n<p>The use of a <code>do while</code> loop is neater than an arbitrary <code>For I =</code> loop, the exit conditions are more explicitly stated than a hidden <code>Exit For</code>. Technically correct, but harder to maintain.</p>\n\n<h2>Use Excel functionality</h2>\n\n<p>Excel has named ranges. This can be exploited to simplify code. You don't have to declare static variables which hold column numbers if you can use the named ranges.</p>\n\n<h2>Magic numbers</h2>\n\n<p>You have some magic numbers in the code. What is the significance of <code>700</code> or <code>70000</code> ? How are you going to manage the code if these change - how will you ensure you have got every copy of them?</p>\n\n<p>Also, what happens to <code>stationStart</code> or <code>stationEnd</code> if you go through the loops and do not find the relevant cell? Currently they stay at 0.</p>\n\n<p>what does this look like?\nPutting most of what I said above into practice gives the following code. This is not tested and I have not moved all the declarations to where they are supposed to be. I have also found a couple left over!</p>\n\n<pre><code>Sub Orders_Historicals_autofilterdict2()\n\nDim start As Double\nstart = Timer\n\n''--------------------------------------\n''Static Variables\n''--------------------------------------\nDefinedVariables\n\n\n\nDim currentStation As String\nDim currentWeek As String\n\nDim stationclearanceData As New Scripting.Dictionary\nDim stationplData As New Scripting.Dictionary\n\nDim key As Variant\n\nDim i As Long\nDim w As Long\n\nDim plTotal As Long\nDim clearTotal As Long\nDim stationHash As String\n\n''--------------------------------------\n''Dictionary the Order Abbreviations\n''--------------------------------------\n Application.ScreenUpdating = False\n\nDim orderFile As Worksheet ' notVariant\nDim clientdataFile As Worksheet 'Variant\nDim clientdataBook As Workbook ' I added this\nDim dictData As New Scripting.Dictionary\n\n Set orderFile = ActiveWorkbook.ActiveSheet ' consider putting that orderBook variable in, because this gets used a few times later.\n Set clientdataBook = Workbooks.Open(clientdataLocation) 'clientdataLocation is undeclared? What happens if this is null?\n Set clientdataFile = clientdataBook.Sheets(dan_location) '/ Change sheet when using on different computer\n With clientdataFile ' not activate! Now the following code is fully qualified.\n For i = 1 To .Cells(.Rows.Count, 1).End(xlUp).Row\n If dictData.Exists(.Cells(i, clientOrder).Value) Then ' This could be \"If Not dictData etc.\"\n Else\n dictData.Add .Cells(i, clientOrder).Value, i\n End If\n Next\n End With\n\n''--------------------------------------\n''Determine Account/Network & Open Internal Associated with Order\n''--------------------------------------\nDim fileOnly As String\nDim networkOnly As String\nDim internalBook As Workbook ' I added this\n fileOnly = orderFile.Parent.Name ' no need to activate\n fileOnly = Left(fileOnly, InStr(fileOnly, \".\") - 1)\n\n If InStr(fileOnly, 2) > 0 Or InStr(fileOnly, 3) > 0 Then '' Does this actually work?\n fileOnly = Left(fileOnly, Len(fileOnly) - 1)\n End If\n\n networkOnly = orderFile.Parent.Name ' at this point, you have already lost track of what is supposed to be active.\n networkOnly = Mid(networkOnly, InStr(networkOnly, \"IO.\") + 3)\n networkOnly = Left(networkOnly, InStr(networkOnly, \".\") - 1)\n\nDim internalFile As Workbook\n Set internalFile = Workbooks.Open(Filename:=clientdataFile.Cells(dictData(fileOnly), clientInternal).Value)\n\nDebug.Print Timer - start & \" Open client database, determine which account we're on\"\n''--------------------------------------\n''Find Last 4 Dates & Column Header for Orders\n''--------------------------------------\nDim dateStart As Long\nDim stationStart As Long\nDim stationEnd As Long\nDim orderStart As Long\nDim orderEnd As Long\nDim findStationArray As Variant ' I added the next 4\nDim startFound As Boolean\nDim endFound As Boolean\nDim stationStartValue As String ' assumption here\n With internalFile.Sheets(WT_newWeek) ' no need to Activate!\n findStationArray = .Range(\"A1:A700\").Value\n i = LBound(findStationArray, 1)\n While i <= UBound(findStationArray, 1) Or Not startFound\n Select Case .Cells(i, 1).Value\n Case WT_newWeek\n dateStart = i\n Case \"Station\"\n If Not startFound Then\n stationStart = i + 1\n startFound = True\n End If\n End Select\n i = i + 1\n Wend\n stationStartValue = .Cells(stationStart - 2, 1).Value & \" Total\" ' do this only once, not 700 times\n While i <= UBound(findStationArray, 1) Or Not endFound\n endFound = (.Cells(i, 1).Value = stationStartValue)\n If endFound Then stationEnd = i - 1\n i = i + 1\n Wend\n End With\n\n With orderFile ' again - do not .Activate\n findStationArray = .Range(\"A1:A700\").Value\n i = LBound(findStationArray, 1)\n While i <= UBound(findStationArray, 1) Or Not startFound\n startFound = (.Cells(i, 1).Value = \"Station\")\n If startFound Then orderStart = i + 1\n i = i + 1\n Wend\n While i <= UBound(findStationArray, 1) Or Not endFound\n endFound = (Len(.Cells(i, 1)) = 0 And Len(.Cells(i - 1, 1)) = 0 And Len(.Cells(i - 2, 1)) = 0)\n If endFound Then orderEnd = i - 3\n i = i + 1\n Wend\n End With\n\nDebug.Print Timer - start & \" Find last 4 weeks and order range\"\n\n''--------------------------------------\n''Add Dates to Order Header and Formatting\n''--------------------------------------\n With orderFile ' assumption here - have we lost track of what is active yet?\n .Cells(orderStart - 1, OF_buyAlgoColumn) = \"Algorithm Recommendation\"\n .Cells(orderStart - 1, OF_totalplColumn) = \"Total P&L\"\n .Cells(orderStart - 1, OF_totalclearanceColumn) = \"Total Clearance %\"\n .Cells(orderStart - 1, OF_clearanceColumn1) = internalFile.Sheets(WT_newWeek).Cells(dateStart, 1)\n .Cells(orderStart - 1, OF_clearanceColumn2) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 1, 1)\n .Cells(orderStart - 1, OF_clearanceColumn3) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 2, 1)\n .Cells(orderStart - 1, OF_clearanceColumn4) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 3, 1)\n .Cells(orderStart - 1, OF_plColumn1) = internalFile.Sheets(WT_newWeek).Cells(dateStart, 1)\n .Cells(orderStart - 1, OF_plColumn2) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 1, 1)\n .Cells(orderStart - 1, OF_plColumn3) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 2, 1)\n .Cells(orderStart - 1, OF_plColumn4) = internalFile.Sheets(WT_newWeek).Cells(dateStart - 3, 1)\n .Range(.Cells(orderStart - 2, OF_clearanceColumn1), .Cells(orderStart - 2, OF_clearanceColumn4)) = \"Clearance\"\n .Range(.Cells(orderStart - 2, OF_plColumn1), .Cells(orderStart - 2, OF_plColumn4)) = \"P&L\"\n .Cells(orderStart - 1, OF_stationColumn).Copy\n .Range(.Cells(orderStart - 1, OF_buyAlgoColumn), .Cells(orderStart - 1, OF_plColumn4)).PasteSpecial xlPasteFormats\n .Cells(orderStart, OF_stationColumn).Copy\n .Range(.Cells(orderStart - 2, OF_clearanceColumn1), .Cells(orderStart - 2, OF_plColumn4)).PasteSpecial xlPasteFormats\n .Range(.Cells(orderStart - 2, OF_buyAlgoColumn), .Cells(orderEnd, OF_plColumn4)).HorizontalAlignment = xlCenter\n .Cells(orderStart, OF_stationColumn).Copy\n .Range(.Cells(orderStart, OF_buyAlgoColumn), .Cells(orderEnd, OF_plColumn4)).PasteSpecial xlPasteFormats\n .Cells(orderStart, OF_totalColumn).Copy\n .Range(.Cells(orderStart, OF_plColumn1), .Cells(orderEnd, OF_plColumn4)).PasteSpecial xlPasteFormats\n .Range(.Cells(orderStart, OF_totalplColumn), .Cells(orderEnd, OF_totalplColumn)).PasteSpecial xlPasteFormats\n .Range(.Cells(orderStart, OF_totalclearanceColumn), .Cells(orderEnd, OF_clearanceColumn4)).NumberFormat = \"0%\"\n .Range(.Cells(orderStart - 2, OF_buyAlgoColumn), .Cells(orderEnd, OF_plColumn4)).FormatConditions.Delete\n .Range(.Columns(OF_buyAlgoColumn), .Columns(OF_plColumn4)).AutoFit\n End With\nDebug.Print Timer - start & \" Adding columns and formating\"\n\n''--------------------------------------\n''Add Clearance and P&L by Date to Dictionary\n''--------------------------------------\n\nDim t As Long\n For i = OF_clearanceColumn1 To OF_clearanceColumn4\n currentWeek = orderFile.Cells(orderStart - 1, i).Value\n With internalFile.Sheets(currentWeek)\n findStationArray = .Range(\"A1:A700\").Value\n t = LBound(findStationArray, 1)\n While t <= UBound(findStationArray, 1) Or Not startFound\n startFound = (.Cells(t, 1).Value = \"Station\")\n If startFound Then stationStart = t + 1\n t = t + 1\n Wend\n stationStartValue = .Cells(stationStart - 2, 1).Value & \" Total\" ' do this only once, not 700 times\n While t <= UBound(findStationArray, 1) Or Not endFound\n endFound = (.Cells(t, 1).Value = stationStartValue)\n If endFound Then\n stationEnd = i - 1 ' is this meant to be \"i\" or \"t\" ?\n Else\n If stationclearanceData.Exists(Cells(t, WT_stationColumn).Value & currentWeek) Then\n Else\n On Error Resume Next ' I assume you want to fail silently. Otherwise this is dangerous\n stationclearanceData.Add Cells(t, WT_stationColumn).Value & currentWeek, Cells(t, WT_mediaactColumn).Value / Cells(t, WT_mediaestColumn).Value\n stationplData.Add Cells(t, WT_stationColumn).Value & currentWeek, Cells(t, WT_profitColumn).Value\n On Error GoTo 0 ' stop the error hiding - otherwise you will not pick up any errors later in the code\n End If\n End If\n i = i + 1\n Wend\n End With\n Next i\n\nDebug.Print Timer - start & \" loop through last 4 weeks, add station clearance and P&L data to dictionary\"\n\n''--------------------------------------\n''Add Cumulative Clearance and P&L to Dictionary\n''--------------------------------------\nDim cumulativeSheet As Worksheet\n With internalFile.Sheets(\"Cumulative\") ' again, no need to .Activate\n findStationArray = .Range(\"A5:A70000\").Value\n t = LBound(findStationArray, 1)\n While t <= UBound(findStationArray, 1) Or Not endFound\n endFound = (.Cells(t, 1) = \"\" And .Cells(t + 1, 1) = \"\" And .Cells(t + 2, 1) = \"\")\n ' If endFound Then stationEnd = t + 1 ' this is superfluous, because the loop will exit with t+1 anyway. But good to have here for future readability and maintenance.\n t = t + 1\n Wend\n\n For t = 5 To stationEnd\n If Cells(t, CT_yearColumn) = 2019 Then\n If stationclearanceData.Exists(Cells(t, CT_hashColumn).Value) Then\n Else\n On Error Resume Next\n stationclearanceData.Add Cells(t, CT_hashColumn).Value, Cells(t, CT_clearanceColumn).Value\n stationplData.Add Cells(t, CT_hashColumn).Value, Cells(t, CT_invoiceColumn).Value - Cells(t, CT_actcostColumn).Value\n On Error GoTo 0 ' stop the error hiding - otherwise you will not pick up any errors later in the code\n End If\n End If\n Next\n\nDebug.Print Timer - start & \" find range of cumulative, add clearance and P&L for 2019\"\n\n''--------------------------------------\n''Loop Through Stations on Order File and Update Based on Dictionary Values\n''--------------------------------------\n' **** The changes here are for better performance.\nDim stationValues As Variant\nDim trafficValues As Variant\nDim totalPLValues As Variant\nDim totalClearanceValues As Variant\nDim clearance1Values As Variant ' if these are contiguous columns then this could be handled as a two dimensional array.\nDim clearance2Values As Variant\nDim clearance3Values As Variant\nDim clearance4Values As Variant\nDim pl1Values As Variant ' Ditto\nDim pl2Values As Variant\nDim pl3Values As Variant\nDim pl4Values As Variant\nDim clearanceValue1 As String\nDim clearanceValue2 As String\nDim clearanceValue3 As String\nDim clearanceValue4 As String\nDim plValue1 As String\nDim plValue2 As String\nDim plValue3 As String\nDim plValue4 As String\n\n With orderFile '.Activate\n stationValues = .Range(.Cells(orderStart - 1, OF_stationColumn), .Cells(orderEnd, OF_stationColumn)).Value ' use arrays instead of calling excel ranges\n trafficValues = .Range(.Cells(orderStart - 1, OF_trafficColumn), .Cells(orderEnd, OF_trafficColumn)).Value ' use arrays instead of calling excel ranges\n totalPLValues = .Range(.Cells(orderStart - 1, OF_totalplColumn), .Cells(orderEnd, OF_totalplColumn)).Value\n totalClearanceValues = .Range(.Cells(orderStart - 1, OF_totalclearanceColumn), .Cells(orderEnd, OF_totalclearanceColumn)).Value\n clearance1Values = .Range(.Cells(orderStart - 1, OF_clearanceColumn1), .Cells(orderEnd, OF_clearanceColumn1)).Value\n clearance2Values = .Range(.Cells(orderStart - 1, OF_clearanceColumn2), .Cells(orderEnd, OF_clearanceColumn2)).Value\n clearance3Values = .Range(.Cells(orderStart - 1, OF_clearanceColumn3), .Cells(orderEnd, OF_clearanceColumn3)).Value\n clearance4Values = .Range(.Cells(orderStart - 1, OF_clearanceColumn4), .Cells(orderEnd, OF_clearanceColumn4)).Value\n pl1Values = .Range(.Cells(orderStart - 1, OF_plColumn1), .Cells(orderEnd, OF_plColumn1)).Value\n pl2Values = .Range(.Cells(orderStart - 1, OF_plColumn2), .Cells(orderEnd, OF_plColumn2)).Value\n pl3Values = .Range(.Cells(orderStart - 1, OF_plColumn3), .Cells(orderEnd, OF_plColumn3)).Value\n pl4Values = .Range(.Cells(orderStart - 1, OF_plColumn4), .Cells(orderEnd, OF_plColumn4)).Value\n clearanceValue1 = .Cells(orderStart - 1, OF_clearanceColumn1).Value ' evaluate these only once, instead of every time in the loop\n clearanceValue2 = .Cells(orderStart - 1, OF_clearanceColumn2).Value\n clearanceValue3 = .Cells(orderStart - 1, OF_clearanceColumn3).Value\n clearanceValue4 = .Cells(orderStart - 1, OF_clearanceColumn4).Value\n plValue1 = .Cells(orderStart - 1, OF_plColumn1).Value\n plValue2 = .Cells(orderStart - 1, OF_plColumn2).Value\n plValue3 = .Cells(orderStart - 1, OF_plColumn3).Value\n plValue4 = .Cells(orderStart - 1, OF_plColumn4).Value\n For w = LBound(stationValues) + 1 To UBound(stationValues) 'orderStart To orderEnd\n If stationValues(w, 1) <> \"\" Then\n If stationValues(w, 1) <> stationValues(w - 1, 1) Then\n stationHash = stationValues(w, 1) & \" \" & stationValues(w, 1) & \" Total\"\n ' On Error Resume Next ' don't hide errors - what is the issue here?\n clearance1Values(w, 1) = stationclearanceData(stationValues(w, 1) & clearanceValue1)\n clearance2Values(w, 1) = stationclearanceData(stationValues(w, 1) & clearanceValue2)\n clearance3Values(w, 1) = stationclearanceData(stationValues(w, 1) & clearanceValue3)\n clearance4Values(w, 1) = stationclearanceData(stationValues(w, 1) & clearanceValue4)\n\n pl1Values(w, 1) = stationclearanceData(stationValues(w, 1) & plValue1)\n pl1Values(w, 2) = stationclearanceData(stationValues(w, 1) & plValue2)\n pl1Values(w, 3) = stationclearanceData(stationValues(w, 1) & plValue3)\n pl1Values(w, 4) = stationclearanceData(stationValues(w, 1) & plValue4)\n\n totalPLValues(w, 1) = stationplData(stationHash)\n totalClearanceValues(w, 1) = stationclearanceData(stationHash)\n End If\n End If\n Next\n ' return the changed arrays to the ranges.\n .Range(.Cells(orderStart - 1, OF_totalplColumn), .Cells(orderEnd, OF_totalplColumn)).Value = totalPLValues\n .Range(.Cells(orderStart - 1, OF_totalclearanceColumn), .Cells(orderEnd, OF_totalclearanceColumn)).Value = totalClearanceValues\n .Range(.Cells(orderStart - 1, OF_clearanceColumn1), .Cells(orderEnd, OF_clearanceColumn1)).Value = clearance1Values\n .Range(.Cells(orderStart - 1, OF_clearanceColumn2), .Cells(orderEnd, OF_clearanceColumn2)).Value = clearance2Values\n .Range(.Cells(orderStart - 1, OF_clearanceColumn3), .Cells(orderEnd, OF_clearanceColumn3)).Value = clearance3Values\n .Range(.Cells(orderStart - 1, OF_clearanceColumn4), .Cells(orderEnd, OF_clearanceColumn4)).Value = clearance4Values\n .Range(.Cells(orderStart - 1, OF_plColumn1), .Cells(orderEnd, OF_plColumn1)).Value = pl1Values\n .Range(.Cells(orderStart - 1, OF_plColumn2), .Cells(orderEnd, OF_plColumn2)).Value = pl2Values\n .Range(.Cells(orderStart - 1, OF_plColumn3), .Cells(orderEnd, OF_plColumn3)).Value = pl3Values\n .Range(.Cells(orderStart - 1, OF_plColumn4), .Cells(orderEnd, OF_plColumn4)).Value = pl4Values\n End With\n\nDebug.Print Timer - start & \" adding data from dictionary to order file\"\n\n clientdataBook.Close saveChanges:=False\n Application.ScreenUpdating = True\n\n ' lost track of what is supposed to be active yet?\n orderFile.Range(Cells(orderStart - 2, OF_buyAlgoColumn), Cells(orderEnd, OF_plColumn4)).HorizontalAlignment = xlCenter\n\n MsgBox (\"Buy Algorithm Complete\")\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T16:03:47.553",
"Id": "418055",
"Score": "0",
"body": "Very good information and I appreciate the response. Doesn't look like I can answer all your questions in this little comment box. But a few comments you made helped me like declaring as worksheet instead of variant. I didn't know what to do with it which is why I did variant. InStr I think it supposed to be \"2\" not just 2 and it will rarely pop but it would mess with opening the correct data. The magic numbers are just max numbers, nothing special to them. Stationstart/end will find what they are looking for because it's the same template used for each file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T16:05:25.170",
"Id": "418056",
"Score": "0",
"body": "I put your code in and I get an error. Method or data member not found and it stops on `fileOnly = orderFile.Workbook.Name ' no need to activate`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T21:44:27.623",
"Id": "418097",
"Score": "0",
"body": "@Dan: Yes, my error and did not pick it up due to not testing. The change required is `fileOnly = orderFile.Parent.Name`, and also a few lines down `networkOnly = orderFile.Workbook.Name`. Because `Parent` is a generic object, the `Name` property will not come up in Intellisense. In this case, `Parent` is implicitly converted to a `Workbook` object (because `orderFile` is a `WorkSheet`) which does have the `Name` property/data member."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T21:45:50.280",
"Id": "418098",
"Score": "0",
"body": "I didn't pick it up in my review, but you don't use the variable `networkOnly` in your logic, so those few lines of code aren't required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T21:53:50.350",
"Id": "418099",
"Score": "0",
"body": "Correct, I had a plan for networkOnly but then didn't use it so I can probably delete it. Let me go through your change and see how it runs. Give me a few minutes, thank you for your help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T21:57:05.710",
"Id": "418100",
"Score": "0",
"body": "Missing an \"end with\" right above Debug.Print Timer - start & \" find range of cumulative, add clearance and P&L for 2019\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T21:58:49.127",
"Id": "418101",
"Score": "0",
"body": "Application defined or object defined error on `endFound = (.Cells(i, 1).Value = stationStartValue)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T22:27:06.727",
"Id": "418106",
"Score": "0",
"body": "I didn't take your code 1:1, but the last part of your coding where you move the data into an array, then array to range makes this soooooo much quicker. I appreciate your assistance here. I will definitely be using this going forward!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T23:32:06.967",
"Id": "418109",
"Score": "0",
"body": "np - glad it is was helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T05:01:38.287",
"Id": "418646",
"Score": "0",
"body": "AJD, Is the `While i <= UBound(findStationArray, 1) Or Not startFound` correct? I think it should be AND not OR otherwise it continues looping until the end of the range. Either I could change to AND, or I could add an \"exit while\" right under the `startFound = True`. Thoughts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T18:38:50.893",
"Id": "418723",
"Score": "0",
"body": "@Dan: Good pick up, yes, these should be `And` - while we are within a legal number of elements **and** we haven't found the one we want. As you have found out, the `Or` option would loop until the end of the array, and then, if found, would continue to loop past the end!"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T06:07:24.560",
"Id": "216033",
"ParentId": "215946",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216033",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T17:36:30.853",
"Id": "215946",
"Score": "2",
"Tags": [
"performance",
"vba",
"excel",
"hash-map"
],
"Title": "Sluggish Loop Transferring Dictionary Data to Spreadsheet"
} | 215946 |
<p>I started coding in August 2018, and I was wondering on how I can improve as a programmer. I'm more concerned about coding conventions. Particularly, how can I improve the structure of my code, organization, comments, variables, formatting, etc. Any other feedback is welcome and appreciated as well.</p>
<p>I completed a Snake game with the following classes. The code can also be viewed <a href="https://github.com/kanedu828/Snake-Game/tree/master/src/kane/game" rel="noreferrer">here</a>.</p>
<p>Body</p>
<pre><code>package kane.game.snake;
import kane.game.map.Block;
/**
* This class is a linked list of the bodies of a snake. The body index should be right before the previous node,
* depending on the direction.
*/
public class Body extends Block {
private Direction dir;
/**
* Initializes the body at the following index.
* @param row Row index of the body.
* @param col Col index of the body.
*/
public Body(int row, int col){
super(row, col);
}
/**
* Returns the direction the snake is heading.
* @return the direction the snake is heading.
*/
public Direction getDir(){
return dir;
}
/**
* Sets the direction the snake is heading.
* @param dir the direction the snake is heading.
*/
public void setDir(Direction dir){
this.dir = dir;
}
}
</code></pre>
<p>Direction</p>
<pre><code>package kane.game.snake;
/**
* This enum represents the direction of a snake block.
*/
public enum Direction{
UP, DOWN, RIGHT, LEFT;
}
</code></pre>
<p>Snake</p>
<pre><code>package kane.game.snake;
import java.util.ArrayList;
/**
* This class represents the snake. Snake contains the head of the snake that the user controls.
*/
public class Snake {
private ArrayList<Body> snake;
/**
* Initializes the snake with a head, which the starting index is at the center of the map.
* @param width
* @param height
*/
public Snake(int width, int height){
snake = new ArrayList<>();
snake.add(new Body(height/2, width/2));
}
/**
* Returns the first index of {@code snake}.
* @return the {@code head} of {@code snake}.
*/
public Body getHead(){
return snake.get(0);
}
/**
* Returns the {@code snake}
* @return the {@code snake}
*/
public ArrayList<Body> getSnake(){
return snake;
}
/**
* Returns the size of the snake.
* @return size of the snake.
*/
public int size(){
return snake.size();
}
/**
* Returns the tail of the snake.
* @return The last index of {@code snake}.
*/
public Body getTail(){
return snake.get(snake.size()-1);
}
/**
* Adds a body to the snake.
*/
public void appendBody(){
Body tail = getTail();
//The bodies are added depending on which direction the tail is heading.
if(tail.getDir()==Direction.UP){
snake.add(new Body(tail.getRow(), tail.getCol()-1));
getTail().setDir(tail.getDir());
}
if(tail.getDir()==Direction.DOWN){
snake.add(new Body(tail.getRow(), tail.getCol()+1));
getTail().setDir(tail.getDir());
}
if(tail.getDir()==Direction.RIGHT){
snake.add(new Body(tail.getRow()+1, tail.getCol()));
getTail().setDir(tail.getDir());
}
if(tail.getDir()==Direction.LEFT){
snake.add(new Body(tail.getRow()-1, tail.getCol()));
getTail().setDir(tail.getDir());
}
}
/**
* Returns whether or not the snake collided with itself.
* @return True if it collided with itself, false otherwise.
*
*/
public boolean isCollision(){
for(Body b: snake){
if(getHead().getRow()==b.getRow()&&getHead().getCol()==b.getCol()&&b!=getHead()){
return true;
}
}
return false;
}
/**
* Moves the snake along.
*/
public void passIndex(){
for(int i = size()-1; i>0; i--){
snake.get(i).setRow(snake.get(i-1).getRow());
snake.get(i).setCol(snake.get(i-1).getCol());
}
}
}
</code></pre>
<p>Map</p>
<pre><code>package kane.game.map;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import kane.game.snake.Body;
import kane.game.snake.Snake;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Random;
/**
* The class represents the game map of snake. The map includes properties such as {@code width}, {@code height},
* {@code user}, and {@code apple}. It also holds the visual aspects of the game.
*/
public class Map {
private ImageView[][] map;
private int width;
private int height;
private Snake user;
private Apple apple;
private static Image whiteblock;
private static Image snakeblock;
private static Image appleblock;
/**
* This constructor initializes the map with a certain width and height. It take's in a GridPane argument, and
* each index of this GridPane is set to be a background block ({@code whiteblock}). Additionally, the head of a
* snake block is placed at the center, and an {@code apple} block is randomly placed on the map.
* @param root
* @param width
* @param height
*/
public Map(GridPane root, int width, int height){
//Initializing whiteblock to a simple white square, snakeblock to be a simple red square,
//and appleblock to be a red square.
try {
whiteblock = new Image(new FileInputStream("resources/whitesquare.jpg"));
snakeblock = new Image(new FileInputStream("resources/blacksquare.png"));
appleblock = new Image(new FileInputStream("resources/redsquare.jpg"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
user = new Snake(width, height);
//Apple placed at a random index.
apple = new Apple(0,0);
apple.placeApple(width,height);
this.width = width;
this.height = height;
map = new ImageView[width][height];
//Sets each GirdPane block to the corresponding 2d ImageView Array, map.
for(int row = 0; row<width; row++){
for(int col = 0; col<height; col++){
//Initializes a new ImageView for each index.
map[row][col] = new ImageView(whiteblock);
//Sets the apple block on the GridPane. Overrides the background block.
if(row==apple.getRow()&&col==apple.getCol()){
map[row][col].setImage(appleblock);
}
//Sets the head of the snake on the GridPane. Overrides the background block.
if(row==user.getHead().getRow()&&col==user.getHead().getCol()){
map[row][col].setImage(snakeblock);
}
//Makes sure the dimensions of each index in GridPane is reasonable. 50x50 pixels
map[row][col].setFitHeight(50);
map[row][col].setFitWidth(50);
//Adds each ImageView to the GridPane
root.add(map[row][col], row, col);
}
}
}
/**
* Returns the user snake.
* @return {@code user}. The Snake object for this class.
*/
public Snake getUser(){
return user;
}
/**
* Returns {@code apple}
* @return The Apple object for this class.
*/
public Apple getApple(){
return apple;
}
/**
* Returns the {@code width} of the map.
* @return {@code width} of the map.
*/
public int getWidth(){
return width;
}
/**
* Returns the {@code height} of the map.
* @return {@code height} of the map.
*/
public int getHeight(){
return height;
}
/**
* Updates the map by resetting each ImageView index in the array {@code map}. Updates visuals. This method should
* be used after any change to a block.
*/
public void updateMap(){
for(int row = 0; row<width; row++){
for(int col = 0; col<height; col++){
//setImage instead of initializing is used for better memory usage.
map[row][col].setImage(whiteblock);
//Sets the apple block on the GridPane. Overrides the background block.
if(row==apple.getRow()&&col==apple.getCol()){
map[row][col].setImage(appleblock);
}
for(int i = 0; i<user.size(); i++){
if(user.getSnake().get(i).getRow()==row&&user.getSnake().get(i).getCol()==col){
map[row][col].setImage(snakeblock);
}
}
//Makes sure the dimensions of each index in GridPane is reasonable. 50x50 pixels
map[row][col].setFitHeight(50);
map[row][col].setFitWidth(50);
//Adds each ImageView to the GridPane
}
}
}
}
</code></pre>
<p>Block</p>
<pre><code>package kane.game.map;
/**
* This class represents any block that would be in a snake game.
*/
public class Block {
private int row;
private int col;
/**
* Initializes the {@code row} and {@code col} of the block.
* @param row row index of the block
* @param col column index of the block
*/
public Block(int row, int col){
this.row = row;
this.col = col;
}
/**
* Returns the {@code row} index of the block.
* @return Returns the {@code row} index of the block.
*/
public int getRow(){
return row;
}
/**
* Sets the {@code row} index of the block.
* @param row {@code row} index.
*/
public void setRow(int row){
this.row = row;
}
/**
* Returns the {@code col} index of the block.
* @return Returns the {@code col} index of the block.
*/
public int getCol(){
return col;
}
/**
* Sets the {@code col} index of the block.
* @param col {@code col} index.
*/
public void setCol(int col){
this.col = col;
}
}
</code></pre>
<p>Apple</p>
<pre><code>package kane.game.map;
import java.util.Random;
/**
* This class represents a block that represents an apple.
*/
public class Apple extends Block {
/**
* Initializes the apple at the specified location.
* @param row Row index of where apple will be placed.
* @param col Col index of where apple will be placed.
*/
public Apple(int row, int col) {
super(row, col);
}
/**
* Randomly places the apple at an index.
* @param height Height of the map.
* @param width Width of the map.
*/
public void placeApple(int height, int width){
Random rand = new Random();
int appleRow = rand.nextInt(height);
int appleCol = rand.nextInt(width);
setRow(appleRow);
setCol(appleCol);
}
}
</code></pre>
<p>Movement</p>
<pre><code>package kane.game.controls;
import javafx.scene.control.Label;
import kane.game.map.Map;
import kane.game.snake.Body;
import kane.game.snake.Direction;
import java.util.TimerTask;
/**
* This class represents how the snake visually moves.
*/
public class Movement extends TimerTask {
private Map map;
private Body head;
/**
* Passes in the map to be referenced.
* @param map map that is to be referenced.
*/
public Movement(Map map){
this.map = map;
this.head = map.getUser().getHead();
}
/**
* Snake moves based off of the direction it is facing. The direction is changed with {@code UserInput} controls.
*/
@Override
public void run() {
//Checks if the snake is out of bounds of the map. You lose if so.
if(head.getRow()<0||head.getRow()>=map.getWidth()||head.getCol()<0||head.getCol()>=map.getHeight()){
System.exit(0);
}
//Checks if the snake collides with itself. You lose if so.
if(map.getUser().isCollision()){
System.exit(0);
}
//When the snake eats an apple. Snake grows in size if so.
if(map.getApple().getRow()==head.getRow()&&map.getApple().getCol()==head.getCol()) {
map.getUser().appendBody();
map.getApple().placeApple(map.getWidth(), map.getHeight());
map.updateMap();
}
//Moves snake up.
if(head.getDir()== Direction.UP){
map.getUser().passIndex();
head.setCol(head.getCol()-1);
map.updateMap();
}
//Moves snake down.
if(head.getDir()== Direction.DOWN){
map.getUser().passIndex();
head.setCol(head.getCol()+1);
map.updateMap();
}
//Moves snake to the right.
if(head.getDir()== Direction.RIGHT){
map.getUser().passIndex();
head.setRow(head.getRow()+1);
map.updateMap();
}
//Moves snake to the left
if(head.getDir()== Direction.LEFT){
map.getUser().passIndex();
head.setRow(head.getRow()-1);
map.updateMap();
}
}
}
</code></pre>
<p>UserInput</p>
<pre><code>package kane.game.controls;
import javafx.event.EventHandler;
import javafx.scene.input.KeyEvent;
import kane.game.map.Map;
import kane.game.snake.Body;
import kane.game.snake.Direction;
import kane.game.snake.Snake;
import java.util.Timer;
import java.util.TimerTask;
import static javafx.scene.input.KeyCode.*;
/**
* This class represents the controls for a game of snake.
*/
public class UserInput implements EventHandler<KeyEvent> {
private Body head;
private Map map;
/**
* Passes in the head to reference for the direction.
* @param head Head object to use to get the direction.
*/
public UserInput(Map map, Body head){
this.head = head;
this.map = map;
}
/**
* Controls of the game. Up, down, right, and left arrow keys are used for movement.
* @param event the event that is being listened.
*/
@Override
public void handle(KeyEvent event) {
//Each input is checked if it inputs the direct opposite direction. For example, if going up, you can not
//switch direction to down. (Unless size of snake is 1).
if(event.getCode()==UP){
if(map.getUser().size()>1&&head.getDir()==Direction.DOWN){
}else {
head.setDir(Direction.UP);
}
}
if(event.getCode()==DOWN){
if(map.getUser().size()>1&&head.getDir()==Direction.UP){
}else {
head.setDir(Direction.DOWN);
}
}
if(event.getCode()==RIGHT){
if(map.getUser().size()>1&&head.getDir()==Direction.LEFT){
}else {
head.setDir(Direction.RIGHT);
}
}
if(event.getCode()==LEFT){
if(map.getUser().size()>1&&head.getDir()==Direction.RIGHT){
}else {
head.setDir(Direction.LEFT);
}
}
}
}
</code></pre>
<p>Driver</p>
<pre><code>package kane.game;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import kane.game.controls.Movement;
import kane.game.controls.UserInput;
import kane.game.map.Map;
import java.util.Timer;
/**
* This is the driver class for a game of snake.
*
* Author: Kane Du
* Last Edited: 3/17/19
*/
public class Driver extends Application {
private static final int SNAKE_SPEED = 100;
/**
* Launches a JavaFX application.
* @param args Command line arguments.
*/
public static void main(String[] args) {
launch(args);
}
/**
* Creates the snake game window.
* @param primaryStage the stage
*/
@Override
public void start(Stage primaryStage) {
Stage window = primaryStage;
window.setTitle("Snake");
VBox root = new VBox();
Label score = new Label("hello");
//The layout that will be compared to an ImageView array.
GridPane grid = new GridPane();
//Initializing map for snake.
Map map = new Map(grid, 21, 21);
root.getChildren().addAll(score,grid);
root.setVgrow(grid, Priority.ALWAYS);
UserInput userInput = new UserInput(map, map.getUser().getHead());
Scene scene = new Scene(root);
scene.setOnKeyPressed(userInput);
//Timer allows the snake to continue to move without a key press.
Timer timer = new Timer();
Movement movement = new Movement(map);
timer.schedule(movement, 0, SNAKE_SPEED);
window.setScene(scene);
window.show();
}
}
</code></pre>
| [] | [
{
"body": "<p>This is a very good for a few months of experience! You're on the right track with trying to separate concepts out into objects, but I think you made some strange decisions in your <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separating of concerns</a> that I'll call out in addition to some stylistic things. Also decent documentation; keep that up!</p>\n\n<ul>\n<li>Java is kind of verbose. This includes package names. Typically packages are named <code>(com|org|net).yourdomain.yourproject</code> (ex <code>org.apache.commons</code>). Now, since your package isn't meant to be used by anyone else, you can get away with this naming scheme. But, that doesn't mean you shouldn't follow the convention.</li>\n<li>Your inheritance is strange. The chain for <code>Snake</code> is: <code>Snake</code> is composed of <code>Body</code> (which has a <code>Direction</code>) which is a <code>Block</code>. The chain for <code>Apple</code> is: <code>Apple</code> is a <code>Block</code>. While I see what you were trying to do here, the separation is odd. The <code>Block</code> superclass (which should be <code>abstract</code>, instantiating a <code>Block</code> means nothing) just encapsulates position. If block also handled drawing (since in the original snake, the snake's body and apples were just single pixels on a screen), this would make more sense. But, in this case, I'd recommend composition over inheritance. Create an immutable <code>Point</code> and give an <code>Apple</code> a <code>Point</code> member variable (instead of extending it). Instead of having the <code>Body</code> class, just give the <code>Snake</code> a ordered collection of points that form its body (more on both of these later).</li>\n<li>You do not need to redefine a constructor if all it does is call <code>super</code> with the same args.</li>\n<li><code>Map</code> conflates two concerns: holding the game state and rendering the game state. Ideally you'd separate this or push drawing concerns into the objects themselves.</li>\n<li>Never <code>e.printStackTrace()</code> outside of development. You'd want to display a nice error message. You can achieve this by letting the exception bubble up and catching it at a layer that can show UI. An editor like IntelliJ will be able to help with this because it can show you the path that an exception will bubble up (by making you add <code>throws</code> clauses to function definitions in Java 8).</li>\n<li><code>placeApple</code> should not be a method on <code>Apple</code>. If you were going to do that, call it <code>randomizePosition</code>, because that's what it actually does. But I'd recommend against that. In general, immutability is much easier to reason about. We'll discuss this in detail later. (In the end, <code>placeApple</code> should be a method of <code>Map</code>)</li>\n<li><code>Movement</code> is a strange class. I understand it ties into your game loop. I'd call it <code>GameTickHandler</code>, because it handles what actions should be taken every game \"tick.\" I also wouldn't use <code>java.util.TimerTask</code>. I believe you have potential data races because <code>TimerTask</code> runs in a separate thread. In general, there's a more common pattern for games that I'll advocate for below.</li>\n<li><code>Movement</code> contains a lot of logic that should be in <code>Direction</code> (particularly the end of <code>run</code>). If you have an immutable <code>Point</code> then you could have a method <code>movedTowards(Direction d)</code> which returns a new <code>Point</code> moved in that direction. You can test this separately without having to deal with all of the complexities in <code>Movement</code> at all.</li>\n<li>Don't <code>System.exit(0)</code>! Display some useful message to your user. The pattern I'll advocate that you use (mentioned above, more detail later) will make this easy.</li>\n<li>How you check for collisions is strange. I'm imagining an API that is much clearer and separates concerns better. Give snake two methods <code>intersectSelf</code> and <code>intersect(Apple a)</code>. This way only a snake decides what these mean. And if you need to check these multiple times, you don't have to duplicate the \"head is touching a part of the body\" logic.</li>\n<li>I don't like how <code>UserInput</code> has a <code>head</code> and <code>map</code>. Ideally it should have some internal state indicating the last direction pushed and one getter (<code>getDirection</code>) that is used by the game loop (more on that below). It should definitely not have all of the logic of moving the snake! That should be the responsibility of <code>Snake</code>.</li>\n<li>Why <code>SNAKE_SPEED</code> in <code>Driver</code>? What units is it in?</li>\n<li><code>.getUser().getHead()</code> is everywhere in your code. That should be a sign that some refactoring is necessary.</li>\n</ul>\n\n<p>Now let's talk about the big idea. What you need is a game loop. No timers, no threads. You want the <a href=\"http://gameprogrammingpatterns.com/game-loop.html\" rel=\"nofollow noreferrer\">game loop pattern</a>. The high level idea is that your game is a object with two methods <code>update(double elapsedTime)</code> and <code>draw()</code>. The first is called frequently and handles keyboard input, updating game state, checking collisions, determining win/loss scenarios. The second is called less frequently (but ideally at 60fps) after the game state is updated and is responsible for drawing the current game state to the screen.</p>\n\n<p>More on that later. Let's start by simplifying your \"game objects.\" We'll start by making an immutable <code>Point</code>. Why immutable? Well, simply put when things change it's very hard to keep all of that in the back of your mind while you're coding. Say for example that we created a <code>Point</code> with members <code>public int x, y;</code> Then <code>Apple</code> has a <code>public Point position;</code>. Anyone who has that apple can change its position. An apple should never move once placed. We have no way of ensuring that other than to keep in the back of our mind that we should never modify <code>apple.position.x</code> or <code>y</code>. But if we make <code>Point</code> immutable we can expose a <code>Point getPosition()</code> on <code>Apple</code> without worrying that objects/methods who we give that apple to will be able to move it around. Hopefully this convinces you.</p>\n\n<p>Let's start with <code>Point</code> (<code>Direction</code> can remain the same):</p>\n\n<pre><code>class Point {\n protected int x;\n protected int y;\n\n public Point(int x, int y) {\n this.x = x;\n this.y = y;\n }\n\n public int getX() { return this.x; }\n public int getY() { return this.y; }\n\n public Point movedTowards(Direction d) {\n switch(d) {\n case Direction.UP: return new Point(this.x - 1, this.y );\n case Direction.DOWN: return new Point(this.x + 1, this.y );\n case Direction.LEFT: return new Point(this.x , this.y - 1);\n case Direction.RIGHT: return new Point(this.x , this.y + 1);\n }\n }\n\n public boolean inBounds(int width, int height) {\n return 0 <= this.x && this.x < width && 0 <= this.y && this.y < height;\n }\n\n @Override\n public boolean equals(Object other) {\n if (this == other) {\n return true;\n }\n\n if (!(other instanceof Point)) {\n return false;\n }\n\n Point otherPoint = (Point) other;\n return this.x == otherPoint.x && this.y == otherPoint.y;\n }\n\n @Override\n public int hashCode() {\n return 31 * this.x + y;\n }\n}\n</code></pre>\n\n<p>Good, now we have a nice encapsulated idea that can be used in the game objects that need it (<code>Snake</code> and <code>Apple</code>). We could also consider adding a static method to <code>Point</code> called <code>randomPoint(int width, int height)</code> that returns a random point between (0, 0) and (<code>width</code>, <code>height</code>). We'd have to be careful here, though (you make this mistake in your code as far as I can tell). We probably don't want to spawn an apple inside the snake's body/head. We'll tackle that later.</p>\n\n<p>With this building block, let's build the <code>Apple</code>.</p>\n\n<pre><code>import javafx.scene.image.Image;\n\nclass Apple {\n protected Point position;\n protected static final Image IMAGE;\n\n static {\n IMAGE = new Image(new FileInputStream(\"resources/redsquare.jpg\"));\n }\n\n public Apple(Point position) {\n this.position = position;\n }\n\n public Point getPosition() { return this.position; }\n\n public void draw(GridGraphicsContext ctx) {\n ctx.drawImage(IMAGE, position);\n }\n}\n</code></pre>\n\n<p>Note a few things here. First, the apple's location is immutable. We want this! Also note how the apple is responsible for drawing itself (and loading its resources--although it is perhaps a little sloppy to do this in a static initializer; a more principled approach would be creating an <code>AppleFactor</code> which loads the file and builds apples by adding a paramter to the constructor for the <code>Image</code>, but this is a lot of Java-y indirection and this approach is sufficient for your simple use case). Also note how I've gotten rid of your <code>GridView</code>. You should be using <a href=\"https://docs.oracle.com/javase/8/javafx/api/javafx/scene/canvas/Canvas.html\" rel=\"nofollow noreferrer\"><code>Canvas</code></a>. This is what real games do and the <code>GridView</code> was just an unnecessary level of indirection (and a lot of overhead of making arrays of <code>ImageView</code>s). I'd recommend making a <code>GridGraphicsContext</code> to wrap your <code>GraphicsContext</code> (from <code>Canvas.getGraphicsContext()</code>), to avoid duplicating the logic of computing the point for the image (converting integer grid coordinates to floating point canvas coordinates):</p>\n\n<pre><code>import javafx.scene.canvas.GraphicsContext;\nimport javafx.scene.image.Image;\n\nclass GridGraphicsContext {\n protected GraphicsContext ctx;\n\n public GridGraphicsContext(GraphicsContext ctx) {\n this.ctx = ctx;\n }\n\n public drawGridImage(Image image, Position p) {\n this.ctx.drawImage(image, p.getX() * image.getWidth(),\n p.getY() * image.getHeight());\n }\n}\n</code></pre>\n\n<p>Now let's look at <code>Snake</code>. Since we defined <code>equals</code> and <code>hashCode</code> on <code>Point</code>, it is hashable (we couldn't make it hashable if it was mutable!). This will let us represent the body of the snake a lot more succinctly.</p>\n\n<pre><code>import java.util.Deque;\nimport java.util.Set;\nimport java.util.ArrayDeque;\nimport java.util.HashSet;\n\nclass Snake {\n protected static final Image BODY_IMAGE;\n\n static {\n BODY_IMAGE = new Image(new FileInputStream(\"resources/blacksquare.png\"));\n }\n\n protected Point headPosition;\n protected Deque<Point> bodyPositions = new ArrayDeque<>();\n protected Set<Point> bodyPositionsSet = new HashSet<>();\n\n public Snake(Point headPosition) {\n this.headPosition = headPosition;\n }\n\n public void move(Direction direction) {\n try {\n Point lastPosition = this.bodyPositions.removeLast();\n this.bodyPositionSet.remove(lastPosition);\n } catch (NoSuchElementException e) {}\n\n this.bodyPositions.offerFirst(this.headPosition);\n this.bodyPositionsSet.add(this.headPosition);\n\n this.headPosition = this.headPosition.moveTowards(direction);\n }\n\n public boolean intersectsSelf() {\n return this.headPositionsSet.contains(this.headPosition);\n }\n\n public boolean headIntersects(Apple apple) {\n return this.headPosition.equals(apple.getPosition());\n }\n\n public void draw(GridGraphicsContext ctx) {\n ctx.drawImage(BODY_IMAGE, this.headPosition);\n\n for (Point p : this.bodyPositions) {\n ctx.drawImage(BODY_IMAGE, p);\n }\n }\n}\n</code></pre>\n\n<p>Notice how I use the interfaces for the types of the collections. This is a good habit to get into. Generally your types should be interfaces so that you can accept any kind of object that conforms to that interface. This allows you to swap out implementations by only changing one line of code. Also note how I changed how you represent the snake's head and body. For one, I kept the separate head member variable. There are multiple reasons for this. Although it could still be nulled, this conveys the idea that the snake <em>always</em> has a head, but may not have a body (<code>bodyPositions</code> and <code>bodyPositionsSet</code> may be empty). This is a good pattern because it's possible that <code>bodyPositions.peekFirst()</code> may throw if it is empty. Although we could get a <code>NullPointerException</code> if <code>headPosition</code> was <code>null</code> (there are static tools to prevent this), this conveys that idea and is a bit safer. Also note that with <code>bodyPositions</code> and <code>bodyPositionsSet</code> testing for collisions is now constant time and moving the snake is easier. Collision testing should be obvious. For moving the snake, note how that you don't need to keep track of the direction of each block. Instead, you can just remove the last body point, add the current head, and then move the head. This is a lot simpler to wrap your head around and ends up being much less work.</p>\n\n<p>Now let's fix the user input:</p>\n\n<pre><code>import javafx.event.EventHandler;\nimport javafx.scene.input.KeyEvent;\nimport static javafx.scene.input.KeyCode.*;\n\nclass InputManager implements EventHandler<KeyEvent> {\n protected Direction direction = Direction.UP;\n\n public Direction getDirection() { return this.direction; }\n\n @Override\n public void handle(KeyEvent event) {\n if (event.getCode() == UP) {\n this.direction = Direction.UP;\n } else if (event.getCode() == DOWN) {\n this.direction = Direction.DOWN;\n } else if (event.getCode() == LEFT) {\n this.direction = Direction.LEFT;\n } else if (event.getCode() == RIGHT) {\n this.direction = Direction.RIGHT;\n }\n }\n}\n</code></pre>\n\n<p>Note how much simpler this is! It has one concern: keeping track of which direction the user pressed. And a user of this object can ask what that direction was. And we can use that and bring everything together in the new <code>Game</code> object:</p>\n\n<pre><code>import javafx.application.Application;\nimport javafx.stage.Stage;\nimport javafx.scene.canvas.Canvas;\nimport javafx.scene.canvas.GraphicsContext;\nimport javafx.scene.Scene;\n\nclass Game extends Application {\n protected static final long TICK_TIME = 100; // miliseconds\n\n protected static final int COLS = 21;\n protected static final int ROWS = 21;\n\n protected static final int GRID_SIZE = 50; // size of tile image\n protected static final int WIDTH = COLS * GRID_SIZE;\n protected static final int HEIGHT = ROWS * GRID_SIZE;\n\n protected InputHandler inputHandler = new InputHandler();\n protected GraphicsContext graphicsContext;\n protected GridGraphicsContext gridGraphicsContext;\n\n protected Snake snake;\n protected Apple apple; \n\n public static void main(String[] args) {\n launch(args);\n }\n\n @Override\n public void start(Stage window) {\n window.setTitle(\"Snake\");\n\n // It's been a long time since I've used javafx, so this might\n // not be totally correct. I believe you need a Parent to insert the\n // Canvas into (that becomes the root of the Scene). You can sort this out.\n Canvas canvas = new Canvas(WIDTH, HEIGHT);\n this.graphicsContext = canvas.getGraphicsContext();\n this.gridGraphicsContext = new GridGraphicsContext(this.graphicsContext);\n\n Scene scene = new Scene(canvas);\n scene.setOnKeyPressed(this.inputHandler);\n\n window.setScene(scene);\n window.show();\n\n this.startGameLoop();\n }\n\n public void startGameLoop() {\n long lastFrameTime = System.currentTimeMillis();\n\n while (true) {\n long currentTime = System.currentTimeMillis();\n long elapsedTime = currentTime - lastFrameTime;\n lastFrameTime = currentTime;\n\n if (!this.update(elapsedTime)) {\n break;\n }\n\n this.draw();\n }\n }\n\n protected long totalTime = 0;\n\n public boolean update(long elapsedTime) {\n this.totalTime += elapsedTime;\n\n while (this.totalTime > TICK_TIME) {\n this.totalTime -= TICK_TIME;\n\n if (this.snake.intersectsSelf() || !this.snake.getHeadPosition().inBounds(COLS, ROWS)) {\n this.reportLoss();\n return false;\n }\n\n this.snake.move(this.inputHandler.getDirection());\n\n if (this.snake.intersects(this.apple.getPosition()) {\n // TODO: increment score\n\n // TODO: don't intersect snake head or body\n this.apple = Apple.randomlyPositioned(COLS, ROWS);\n }\n }\n\n return true;\n }\n\n public void draw() {\n // Clear previous drawing (in a real game, this would be double buffered)\n this.graphicsContext.setFill(Color.WHITE);\n this.graphicsContext.fillRect(0, 0, WIDTH, HEIGHT);\n\n this.snake.draw(this.gridGraphicsContext);\n\n if (this.apple != null) {\n this.apple.draw(this.gridGraphicsContext);\n }\n }\n}\n</code></pre>\n\n<p>This is a bit bulky, but you'll find that overall it's easier to follow. We still do the usual javafx setup (as I noted in the comment, I don't think I did it exactly correctly. You can sort of adding the <code>Canvas</code> to the stage). You may actually want to pull that out into your own <code>Application</code> class and then have <code>Application</code> own a <code>Game</code> object (which is only given the things it needs). But javafx aside, the only other thing we have is the game loop (<code>startGameLoop()</code>). This is a simple game loop (read the linked stuff for more complex ones that do fixed timestep increments and other fancy techniques used in real games--you don't need these though for such a simple game). We see it is just a <code>while</code> loop that only exits if <code>update</code> returns <code>false</code> (indicate the game is over). It alternates between calling <code>update()</code> and <code>draw()</code>. The idea here being we update state and then redraw the screen to show the player what changed. <code>update</code> receives the number of milliseconds that have elapsed since it was last called. This is usually more relevant for games with physics (where computing the next game state involves doing physics calculations--typically integrating some function given the elapsed time), but it works here too. We have a <code>TICK_TIME</code> which is the amount of milliseconds that elapses between each time the snake actually moves. We just keep track of how much time has elapsed and when more than a tick has elapsed, we actually preform the tick (do the game update). Note how we don't just do <code>if (this.totalTime > TICK_TIME)</code> and instead use a <code>while</code>. This is because it is possible that between updates more than 1 tick has happened (consider if the computer is under high load and the OS scheduler doesn't schedule our game for more than 200ms).</p>\n\n<p><code>update()</code> is otherwise fairly simple thanks to some of the separation of concerns that we undertook earlier. Checking for game end states is delegated to the proper objects. The same goes for eating apples.</p>\n\n<p><code>draw()</code> is even easier. It just defers to the appropriate drawing methods on the game objects. Now, since the game has tick based graphics, we could be a bit smarter about drawing and only redraw when something has changed. You could make this optimization, but if you wanted to, say, have a cool death animation you'd want to keep this structure.</p>\n\n<p>I didn't try running this code, so I suspect there may be some issues (and I've indicated places where you need to implement things). But, this is the overall idea. Hopefully this can help you improve your game!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T21:06:37.540",
"Id": "216125",
"ParentId": "215948",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216125",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T17:48:29.307",
"Id": "215948",
"Score": "6",
"Tags": [
"java",
"game",
"javafx",
"snake-game"
],
"Title": "Snake Game in Java feedback"
} | 215948 |
<p>Was told this code was 'weird' and didn't pass the coding test. I tried to split up to show the different levels of abstraction but maybe I went overboard? I told them this in the walk through of the code as things like console logging would be something more like save to database or something more complex so it's its own abstraction.</p>
<pre><code>const https = require('https');
/*
* Complete the function below.
* Use console.log to print the result, you should not return from the function.
* Base url: https://jsonmock.hackerrank.com/api/movies/search/?Title=
*/
async function getMovieTitles(substr) {
// get first page results
const results = await fetchMoviePage(substr, 1);
let matches = results.data.map(extractMovieTitle);
// base case - if we only have one page of results then we done here
if (results.total_pages === 1) {
return sortAndPrintResults(matches);
}
// fill an incremented integer array from page 2 to last page
const pages = fillRange(2, results.total_pages);
// for each page fetch data and add to results list
for await (const page of pages) {
const { data } = await fetchMoviePage(substr, page);
matches = matches.concat( data.map(extractMovieTitle) );
}
sortAndPrintResults(matches);
}
/**
* send sorted results to stdout
*/
function sortAndPrintResults(results){
console.log(results.sort().join('\n'));
}
/**
* fetches a page of movie results.
*/
async function fetchMoviePage(substr, page) {
try {
return await fetchMatchingMovies(substr, page);
} catch (error) {
console.log(`Error retrieving movies for ${substr} on page ${page}: ${error}`);
return {data:[]};
}
}
/**
* Fills an array of incremented integers from start to end
*/
function fillRange(start, end) {
return Array(end - start + 1).fill().map((item, index) => start + index);
};
/**
* returns the movie title from a movie object
*/
function extractMovieTitle(movie) {
return movie.Title;
}
/**
* fetch a list of movies matching a search string
*/
function fetchMatchingMovies(searchString, page) {
const queryString = `https://jsonmock.hackerrank.com/api/movies/search/?Title=${searchString}&page=${page}`;
return new Promise((resolve, reject) => {
https.get(queryString, res => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => resolve(JSON.parse(data)));
}).on('error', e => reject(e));
});
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T00:09:05.747",
"Id": "417879",
"Score": "0",
"body": "Is this the entirety of the code? It is neither a module nor does it actually execute anything like a standalone script. It's just a set of functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T17:15:38.703",
"Id": "417960",
"Score": "0",
"body": "Were you really asked to fetch _all_ results? What API endpoints were you provided? Fetching _all_ results from a _paginated_ API is weird. I would expect an endpoint to return me all results than to loop over and do multiple calls to a paginated API. This is probably part of the test, and just saying \"ok, I'll do it\" without question is probably the trick. But then this is just an assumption. We need more info."
}
] | [
{
"body": "<p>I think it's cool that you fetch the pages in parallel.</p>\n\n<h3>A minor miss of the spec</h3>\n\n<p>The description says to <em>not return</em> from <code>getMovieTitles</code>,\nbut the implementation does that.</p>\n\n<p>I agree the early return makes sense when there is a single page of results.\nI would have extracted to a function the code that fetches results.\nThen the caller could simply call <code>sortAndPrintResults</code> on the returned array.</p>\n\n<h3>Things I find weird</h3>\n\n<p><code>return sortAndPrintResults(matches)</code> is weird because <code>sortAndPrintResults</code> is void.</p>\n\n<p><code>sortAndPrintResults</code> joins the results before printing to console,\nwhich doubles the memory used by the results.\nIt would have been better to call <code>console.log</code> in a loop.</p>\n\n<p>I find the name <code>fillRange</code> misleading.\nBasically it creates a sequence of numbers.\nThat's not what I would guess from the name.</p>\n\n<p>It's a pity to construct an array of numbers just to loop over them.</p>\n\n<p>These two issues could be fixed by implementing a <code>range</code> function as an <em>async generator</em>.</p>\n\n<p>It's not 100% clear if the functions were given or only the first one.\nMany of them would be better inlined.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T17:26:36.580",
"Id": "216666",
"ParentId": "215956",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T19:58:10.563",
"Id": "215956",
"Score": "3",
"Tags": [
"javascript",
"interview-questions",
"node.js"
],
"Title": "Given a search string, fetch all movies results from the api"
} | 215956 |
<p>We know that P-values (within t-test context as an example..) is highly sensitive to sample size. A larger sample will yield a smaller p-value remaining everything else constant. On the other hand, Cohen´s d effect size remains the same.</p>
<p><a href="https://i.stack.imgur.com/3ZIhQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3ZIhQ.png" alt="Sample size and P values"></a></p>
<p>I'm inspired in <a href="https://stats.stackexchange.com/questions/73045/simulating-p-values-as-a-function-of-sample-size">this code here</a>, but I´ve changed some parts to make the difference between means constant, instead of creating a random variable based on a normal distribution.</p>
<p>Although everything is working, I do imagine that some of the experts in this community could improve my syntax.</p>
<pre><code>library(tidyverse)
ctrl_mean <- 8
ctrl_sd <- 1
treated_mean <- 7.9
treated_sd <- 1.2
sample <- numeric() #criar vetor para grupar resultados
nsim <- 1000 #criar variavel
t_result <- numeric()
for (i in 1:nsim) {
set.seed(123)
t_result[i] <- (mean(ctrl_mean)-mean(treated_mean))/sqrt((ctrl_sd^2/(i))+(treated_sd^2/(i))) #manual t test
sample[i] <- i # number of participants
}
ds <- data.frame(
sample = sample, #assign the sample size
t_result = round(t_result,3), #get the t test result
degrees = sample*2-2) #compute the degrees of freedom
ds %>%
filter(sample>1) %>%
mutate(P_Value = 2*pt(abs(t_result), df=degrees,lower.tail=FALSE)) %>%
left_join(ds,.) -> ds
#plot
ggplot(ds, aes(x=sample, y=P_Value)) +
geom_line() +
annotate("segment", x = 1, xend=sample, y = 0.05, yend = 0.05, colour = "purple", linetype = "dashed") +
annotate("segment", x = 1, xend=sample, y = 0.01, yend = 0.01, colour = "red", linetype = "dashed") +
annotate("text", x = c(1,1), y=c(.035,.001), label = c("p < 0.05", "p < 0.01"))
</code></pre>
| [] | [
{
"body": "<p>In this code you do not need the loop:</p>\n\n<pre><code>sample <- 1:nsim\nt_result <- (mean(ctrl_mean)-mean(treated_mean)) /\n sqrt((ctrl_sd^2/(sample))+(treated_sd^2/(sample)))\n# OR:\nt_result <- (mean(ctrl_mean) - mean(treated_mean)) /\n sqrt((ctrl_sd^2 + treated_sd^2) / sample)\n</code></pre>\n\n<p>why the set seed?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T05:27:17.377",
"Id": "418007",
"Score": "0",
"body": "Thank you. Easier than I was imagining. Set.seed, in this case, was an error, thanks for highlighting that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T07:29:02.407",
"Id": "215982",
"ParentId": "215958",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215982",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T21:15:58.523",
"Id": "215958",
"Score": "4",
"Tags": [
"beginner",
"statistics",
"r",
"data-visualization"
],
"Title": "Sample size, P-values (its relationship), and data visualization with plots. ggplot and T test"
} | 215958 |
<p>The code in its full glory, complete with unit tests is <a href="https://github.com/edemo/PDEngine/pull/277/files" rel="nofollow noreferrer">here</a> (and some discussion of the issue).</p>
<p>I am struggling with how the principle of separating data structures and behaviour applies here.</p>
<p>This would be the data structure, only with public fields:</p>
<pre><code>package org.rulez.demokracia.pdengine;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.ElementCollection;
public class BeatTableEntity {
@ElementCollection
public Map<Choice, HashMap<Choice, Integer>> table;
public BeatTableEntity() {
super();
}
}
</code></pre>
<p>And this would be the behaviour, no data fields:</p>
<pre><code>package org.rulez.demokracia.pdengine;
import java.util.HashMap;
import org.rulez.demokracia.pdengine.exception.IsNullException;
public class BeatTable extends BeatTableEntity {
public enum Direction {
DIRECTION_FORWARD, DIRECTION_BACKWARD
}
public BeatTable() {
table = new HashMap<>();
}
public int beatInformation(Choice choice1, Choice choice2, Direction direction) throws IsNullException {
if(direction == null)
throw new IllegalArgumentException("Null direction");
int result = 0;
if(direction.equals(Direction.DIRECTION_FORWARD))
result = getBeatValue(choice1, choice2);
else
result = getBeatValue(choice2, choice1);
return result;
}
private HashMap<Choice, Integer> getBeatRow(Choice choice) {
if (table.get(choice) == null)
throw new IllegalArgumentException("Not existing row key");
return table.get(choice);
}
private int getBeatValue(Choice choiceF, Choice choiceS) throws IsNullException {
if (choiceF == null || choiceS == null)
throw new IsNullException("Choice");
HashMap<Choice, Integer> row = getBeatRow(choiceF);
if (row.get(choiceS) == null)
throw new IllegalArgumentException("Not existing column key");
return row.get(choiceS);
}
}
</code></pre>
<p>This is obviously badly encapsulated; an example is the test which changes a whole row to an empty one, and calls <code>beatInformation()</code> to throw an exception. That test fiddles around with the internals of the data representation (which should have no internals in the first place), and results in an error which is not exactly making sense in the business logic level.</p>
<p>My question is: what would be the right data structure to back this behaviour.</p>
<p>We came up with two possible solutions, none of them could really convince me:</p>
<ol>
<li>have table as a simple map , where key is effectively the (Choice choice1, Choice choice2) tuple (e.g. choice1.id + choice2.id, as those are strings). This way the data structure have no internals to hide, but it is slow for a non-sparse matrix, and I do believe that good design is not slow.</li>
<li>come up with a Matrix class which we think of as a "primitive type". Matrix would itself use an internal data structure fully encapsulated, and implement its own serialization. The reasoning of this would be that this complexity of data cannot work without internals, and as the compiler can hide the internals of e.g. a <code>HashMap</code>, we just do the same, and thus we can use Matrix as a building block in properly separated code.</li>
</ol>
<p>What are the points to consider here, and what would be the right solution?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T03:32:10.080",
"Id": "417891",
"Score": "0",
"body": "Welcome to Code Review! Please tell us task what this code accomplishes, and also make that the title of the question. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T11:00:20.177",
"Id": "417919",
"Score": "0",
"body": "can we assume that you're storing all the information you're working with here in a database and that JPA is available?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T13:26:18.300",
"Id": "417937",
"Score": "0",
"body": "Well, if we assume a specific persistence layer in business logic, then we are fscked, aren't we?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T13:31:01.620",
"Id": "417938",
"Score": "0",
"body": "@200_success I am not sure whether this site is the correct one to ask, because I am interested in a specific design question. While getting feedback on the code is nice, it is pointless while the basic design is not settled.\nShould I ask it on stack owerflow instead? Or which site is best suited for design questions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T16:31:10.170",
"Id": "417957",
"Score": "1",
"body": "JPA is *not* a specific persistence layer, actually..."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T22:59:06.760",
"Id": "215960",
"Score": "1",
"Tags": [
"java",
"design-patterns"
],
"Title": "Proper separation of behaviour and data structure when the data structure is complex"
} | 215960 |
<p>The algorithm takes input for a string's length for <strong>L</strong>, and the number of strings altogether for <strong>X</strong>. The hamming distance is for input <strong>D</strong>. Input <strong>Z</strong> calculates the exact amount of all possible characters in the string besides the permutations for input <strong>D</strong>.</p>
<p>We get a set of <strong>Z</strong> amount of characters. We divide <strong>Z</strong> by <strong>D</strong> which is <strong>S</strong>. We get <strong>B</strong> possible permutations of characters that can be generated in a list of <strong>X</strong> strings. In other words, <strong>Z</strong> divided by <strong>Y</strong> groupings of the same <strong>X</strong> should uniquely have <strong>B</strong> possible permutations within the <strong>Z</strong> characters. (For the center numerical listed string based on hamming?)</p>
<p>If the algorithm is, correct (or I've misled). The center of <strong>Z</strong> is at the <strong>S</strong> string which should be the <strong>B</strong> permutation.</p>
<p>NOTE: The concept is to visualize our strings as a number line.</p>
<p>Here the algorithm is written in <em>Ancient Basic</em> from a TRS-80 computer.</p>
<pre><code>0 A=1
1 INPUT "LENGTH OF STRING";L
2 INPUT "X FOR HOW MANY";X
3 INPUT "D FOR HAMMING DISTANCE";D
4 Z = X * X * 1 * L + X * D * D * D + 1
5 S = Z / D
6 B = S / D
7 Y = S / B
8 CL = D * A ≤ X ≤ B * Y
10 P=B*Y
11 PRINT "CLOSEST STRING", CL, "P=", P
12 IF S = S * D / D THEN PRINT"S = S * D / D", S * D / D
13 IF D = Z / S THEN PRINT"D = Z / S", Z / S
15 PRINT"PROOF", P, S
</code></pre>
<p>I also continue with the algorithm to find where the 2nd closest string, 3rd closest, 4th and so on.</p>
<pre><code>16 PRINT"WOULD YOU LIKE TO FIND CUSTOM CLOSEST STRING?";R$
17 IF R$=YES$ THEN GOTO 19
18 IF R$=NO$ THEN GOTO 19
19 INPUT "ENTER # FOR CLSE STRING";RT
20 GOTO 21
21 PRINT"YOUR CLOSEST STRING"RT, S / RT
90 NQ = S / RT
91 P = RT * NQ
92 IF P = NQ THEN PRINT P, NQ, "LUCKY"
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-21T23:01:08.133",
"Id": "215961",
"Score": "2",
"Tags": [
"strings",
"basic-lang"
],
"Title": "Finding the numerically listed string to the center algorthim"
} | 215961 |
<p>I am trying to create a function for a larger script to determine the third octet of a site IP address based off a user entered site number. I have actually come up with the function, but was hoping that someone could help me come up with something that is simpler and more elegant, instead of the multitude of nested if statements that I came up with. Here are the rules:</p>
<ul>
<li>For sites numbered 0001 - 0255, the third octet is the last 3 digits of the site number, less any zeroes preceding a real number (e.g. Site 0007 = 10.10.7.xxx)</li>
<li>For sites numbered 0256 - 0399 and 0500 - 1999 (except 1202), the third octet is the last 2 digits of the site number less any zeroes preceding a real number (e.g. site 0315 = 10.22.15.xxx)</li>
<li>For sites numbered 401 - 499, the third octet is the last two digits of the site number +100 (e.g. 0401 = 10.20.101.xxx)</li>
<li>Site 1202 is an exception to the above rule, where the third octet is the last 3 digits (.202)</li>
<li>For sites 5000 and above (5000 - 9999), the first digit is dropped, and then the rules above are followed. (e.g. 8248 = 10.12.48.xxx)</li>
</ul>
<p>Here is what I have come up with. It is not very elegant, but it seems to work. Note that the first three lines will be in another function in the script, but are here for testing purposes.</p>
<pre><code>$global:site = Read-Host 'What is the 4 digit site number?' #must include leading zeros
[int]$global:sitecheck=$site #need for comparasion operators
[string]$global:sitestring=$site
if ($sitecheck -le 255)
{
if ($sitestring.substring(0,3) -eq '000') #(i.e. 0001 - 0009)
{
$global:thirdoct = $sitestring.substring(3,1) #(i.e. 1-9)
}
elseif ($sitestring.substring(0,2) -eq '00') #(i.e. 0010 - 0099)
{
$global:thirdoct = $sitestring.substring(2,2) #(i.e. 10 - 99)
}
elseif ($sitestring.substring(0,1) -eq '0') #(i.e. 0100 - 0255)
{
$global:thirdoct = $sitestring.substring(1,3) #(i.e. 100 - 255)
}
}
elseif ($sitecheck -ge 256 -and $sitecheck -le 399 )
{
if ($sitestring.substring(2,1) -eq '0')
{
$global:thirdoct = $sitestring.substring(3,1)
}
else
{
$global:thirdoct = $sitestring.substring(2,2)
}
}
elseif ($sitecheck -ge 401 -and $sitecheck -le 499)
{
$global:thirdoct = 100+$sitestring.substring(2,2)
}
elseif ($sitecheck -ge 501 -and $sitecheck -le 799)
{
if ($sitestring.substring(2,1) -eq '0')
{
$global:thirdoct = $sitestring.substring(3,1)
}
else
{
$global:thirdoct = $sitestring.substring(2,2)
}
}
elseif ($sitecheck -eq 1202)
{
$global:thirdoct = $sitestring.substring(1,3)
}
elseif ($sitecheck -ge 5000 -and $sitecheck -le 9999)
{
$site5000 = [int]$sitestring.substring(1,3)
if ($site5000 -le 255)
{
if ($sitestring.substring(1,2) -eq '00')
{
$global:thirdoct = $sitestring.substring(3,1)
}
elseif ($sitestring.substring(1,1) -eq '0')
{
$global:thirdoct = $sitestring.substring(2,2)
}
else
{
$global:thirdoct = $sitestring.substring(1,3)
}
}
elseif (($site5000 -ge 256 -and $site5000 -le 399) -or ($site5000 -ge 501 -and $site5000 -le 999))
{
$global:thirdoct = $sitestring.substring(2,2)
}
elseif ($site5000 -ge 401 -and $site5000 -le 499)
{
$global:thirdoct = 100+$sitestring.substring(2,2)
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T03:13:03.533",
"Id": "417888",
"Score": "0",
"body": "if you do a modulus division by 100 you don't need to distinguish between one or two places `$global:thirdoct = [int]$sitestring % 100` And I`d use a switch instead of the nested if/elseif to handle the exceptions and leave the rest to the default."
}
] | [
{
"body": "<p>See the following as an incomplete and untested template, ATM too tired to distinguish between parens and curly braces.</p>\n\n<pre><code>$global:site = Read-Host 'What is the 4 digit site number?' #must include leading zeros\n[int]$global:sitecheck=$site #need for comparasion operators\n[string]$global:sitestring=$site\n\nswitch ($sitecheck){\n {$_ -le 255} {$global:thirdoct = $_ % 1000;Break} \n\n {$_ -ge 256 -and \n $_ -le 399} { ;Break}\n\n {$_ -ge 401 -and \n $_ -le 499} {$global:thirdoct = 100 + $_ % 100;Break} \n\n {$_ -eq 1202} {$global:thirdoct = $_ % 1000;Break} \n\n {$_ -ge 501 -and \n $_ -le 799} {} \n\n {$_ -ge 5000 -and\n $_ -le 9999} { ;Break}\n\n default { }\n}\n\n\"Site:{0} thirdOct: {1}\" -f $Sitecheck,$thirdOct\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T04:04:52.113",
"Id": "215971",
"ParentId": "215966",
"Score": "0"
}
},
{
"body": "<p>Let's start with a table of inputs and outputs, because it may not be exactly the same as what you expect from your script. The first column is the input range, the other column is the transformation applied for those inputs.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>0000-0255 self\n0256-0399 last2\n0400 undefined\n0401-0499 -300\n0500 undefined\n0501-0799 last2\n0800-1201 undefined\n1202 last3\n1203-4999 undefined\n5000-5255 last3\n5256-5399 last2\n5400-5500 undefined\n5501-5999 last2\n6000+ same as 5000-5999\n</code></pre>\n\n<p>The best way to manage these cases is with a data structure. A <code>switch</code> statement can work too but there's going to be a lot of repetition, and you really want something that lets you focus on the data. </p>\n\n<p>In this version, the ranges are an array of arrays. Each inner array is a lower bound, an upper bound, and a script block that transforms input to output. As a special case, a negative result from the script block means \"restart the conversion with this new value (after making it positive)\"—this lets us reuse the low patterns for most of 5000-5999, and then reuse the 5000-5999 pattern for 6000-9999.</p>\n\n<p>We simply traverse the array looking matches, and apply the transforms from matching rows. (There's only ever one matching row per call to <code>convert</code>, in this example, but the code allows overlapping ranges; matching transforms will apply in order).</p>\n\n<pre><code>$ranges = @(\n @( 0, 255, { $_ } ),\n @( 256, 399, { $_ % 100 } ),\n @( 401, 499, { $_ - 300 } ),\n @( 501, 799, { $_ % 100 } ),\n @( 1202, 1202, { $_ % 1000 } ),\n @( 5000, 5399, { -($_ % 1000) } ), # redo using last 3 digits\n @( 5501, 5999, { -($_ % 1000) } ),\n @( 6000, 9999, { -($_ % 1000 + 5000) } ) # redo using 5000 + last 3\n)\n\n$convert = {\n $_ = [int]$args[0]\n $out = -1\n foreach ($range in $ranges) {\n if ($_ -ge $range[0] -and $_ -le $range[1]) { \n $out = & $range[2] \n # negative result means re-do the conversion with a new value\n if ($out -lt 0) { $out = & $convert ($out * -1) }\n }\n }\n return $out\n}\n\n$site = Read-Host 'enter the site code: '\n$octet = & $convert $site\nif ($octet -ge 0) {\n echo $octet\n} else {\n echo \"error - $site has no defined octet\"\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T10:14:11.167",
"Id": "417911",
"Score": "0",
"body": "Nice one +1, I do see a difference in repetitions to a switch as there you can break if a condition is met while the foreach will iterate inevitable through all (non matching) ranges."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T11:09:44.023",
"Id": "417920",
"Score": "0",
"body": "that's entirely optional: you could move `return $out` inside of the loop and return on the first match. I think this way is slightly better: makes it easy to have one-off exceptions, like if 400-499 does one thing but 411 and 455 do something different, have a 400-499 range, and below it specific overrides for the exceptions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T06:07:41.363",
"Id": "215978",
"ParentId": "215966",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "215978",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T01:43:04.793",
"Id": "215966",
"Score": "4",
"Tags": [
"powershell",
"ip-address"
],
"Title": "Determine the third octet of an IP address based on user entered site number"
} | 215966 |
<p>I have a function that changes the image on a webpage every three seconds. I would like feedback on efficiency, good code practices, and anything else that can improve the quality of this code. It works, I just want any insight if it can work any better. Any and all feedback is welcomed and considered.</p>
<p><strong>Slideshow Script</strong></p>
<pre><code><!-- Script for Slide Show: Change picture every three seconds -->
<script type="text/javascript">
var index = 0;
change();
function change() {
//Collect all images with class 'slides'
var x = document.getElementsByClassName('slides');
//Set all the images display to 'none' (invisible)
for(var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
//Increment index variable
index++;
//Set index to 1 if it's greater than the amount of images
if(index > x.length) {
index = 1;
}
//set image display to 'block' (visible)
x[index - 1].style.display = "block";
//set loop to change image every 3000 milliseconds (3 seconds)
setTimeout(change, 3000);
}
</script>
</code></pre>
<p><strong>HTML Images accessed</strong></p>
<pre><code><!-- Slide Show -->
<section>
<img class="slides" src="external/ph1.jpg" style="width:100%">
<img class="slides" src="external/ph2.jpg" style="width:100%">
<img class="slides" src="external/ph3.jpg" style="width:100%">
</section>
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>The script tag default type is <code>text/javascript</code> and thus is not needed.</p></li>\n<li><p>Keep your script out of the global scope. This can become a problem when more JS is added to the page and you get name conflicts. The easiest way to encapsulate your code is to wrap it in a function. In this case it would be best to wait for the page to load before starting image cycle. You can use either <code>DOMContentLoaded</code> or <code>load</code> events but if you use the first be sure that the CSS has loaded.</p></li>\n<li><p>Drop the comments they add nothing that is not self evident in the code itself, and are but noise. If you find that the code does not contain the information needed to understand it, first can you rename to make it clear, if not then comments are the last resort.</p></li>\n<li><p>Define a CSS class for hidden images rather than setting the style properties directly. (see example)</p></li>\n<li><p>Use the CSS class to define style properties. Do not set style properties in the HTML document. Its just easier to manage.</p></li>\n<li><p>Use <code>querySelectorAll</code> it is more flexible in the long run.</p></li>\n<li><p>Use <code>for of</code> loop rather than <code>for(;;)</code> loops as it cleaner and requires less code.</p></li>\n<li><p>You don't need to query for the images every 3 seconds. Do it once at the start.</p></li>\n<li><p>Use <code>const</code> for variables that do not change.</p></li>\n<li><p>The variable name <code>x</code> is a bad name. <code>slideImages</code> of <code>slides</code> would be more fitting. Note that I use the plural signifying that it is array, or array like.</p></li>\n<li><p>Start with the images hidden, then ever 3 seconds all you need to do is hide one and show one.</p></li>\n<li><p>Use the remainder operator <code>%</code> to cycle a value (see example)</p></li>\n</ul>\n\n<p>Example</p>\n\n<pre><code><style>\n .slides { width: 100%; }\n .slides-hidden { display : none; }\n</style>\n\n<script>\n addEventListener(\"load\",() => { // \"load\" is safe but \"DOMContentLoaded\" starts earlier\n var index = 0;\n const slides = document.querySelectorAll(\".slides\");\n const classHide = \"slides-hidden\", count = slides.length;\n nextSlide();\n function nextSlide() {\n slides[(index ++) % count].classList.add(classHide);\n slides[index % count].classList.remove(classHide);\n setTimeout(nextSlide, 3000);\n }\n });\n</script>\n\n<section>\n <img class=\"slides slides-hidden\" src=\"external/ph1.jpg\">\n <img class=\"slides slides-hidden\" src=\"external/ph2.jpg\">\n <img class=\"slides slides-hidden\" src=\"external/ph3.jpg\">\n</section>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T05:05:47.660",
"Id": "215974",
"ParentId": "215967",
"Score": "4"
}
},
{
"body": "<p>I made few improvements, the current code you have looks clean to me. But it's better to have control over something we created. So when I looked at the code, I got these questions:</p>\n\n<ol>\n<li>What if I want to go to specific slide based on some logic.</li>\n<li>Why can't we make it reusable</li>\n<li>Why can't we make it context bound so that it has it's specific context to store state.</li>\n<li>What if I want to destroy any point of time.</li>\n</ol>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var SlideShow = (function () {\n function SlideShow (config) {\n if (!config) {\n config = {};\n }\n this.slideSelector = config.slideSelector;\n this.refreshInterval = config.refreshInterval || 3000;\n this.currentVisibleSlide = null;\n this.initialize();\n }\n var prototype = {\n constructor: SlideShow\n };\n prototype.initialize = function () {\n this.refresh();\n this.nextSlide();\n this.slideShowTimer = window.setInterval(this.nextSlide.bind(this), this.refreshInterval);\n }\n prototype.destroy = function () {\n if (this.slideShowTimer) {\n window.clearInterval(this.slideShowTimer);\n }\n }\n prototype.displaySlide = function (slide, show) {\n slide && (slide.style.display = show ? 'block' : 'none');\n }\n prototype.gotoSlide = function (index) {\n var slideToShow = this.slideElements[index];\n if (slideToShow) {\n if (this.currentVisibleSlide) {\n this.displaySlide(this.currentVisibleSlide, false);\n }\n this.displaySlide(slideToShow, true);\n this.currentVisibleSlide = slideToShow;\n }\n }\n prototype.nextSlide = function () {\n var currentVisibleSlide = this.currentVisibleSlide\n var nextSlideIndex;\n if (!currentVisibleSlide) {\n nextSlideIndex = 0;\n } else {\n currentVisibleSlide = this.slideElements.indexOf(currentVisibleSlide);\n nextSlideIndex = currentVisibleSlide + 1;\n if (nextSlideIndex > this.slideElements.length - 1) {\n nextSlideIndex = 0;\n }\n }\n console.log('Showing index: ', nextSlideIndex);\n this.gotoSlide(nextSlideIndex);\n }\n prototype.refresh = function () {\n var slideElements = document.querySelectorAll(this.slideSelector);\n this.slideElements = Array.prototype.slice.call(slideElements, 0);\n }\n SlideShow.prototype = prototype;\n return SlideShow;\n})();\n\n\nvar slideShow = new SlideShow({\n slideSelector: '.slides'\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.slides {\n display: none\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><section>\n <div class=\"slides\" style=\"width:100%\">1</div>\n <div class=\"slides\" style=\"width:100%\">2</div>\n <div class=\"slides\" style=\"width:100%\">3</div>\n</section></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>My rationale behind converting it to a class is, In our application we had an exact same functionality written by a beginner JS programmer in a same way as OP has posted. Other developers made amendments to it. The code has grown complex and started giving unexpected bugs. It was harder to maintain and reuse in other parts of the application. So my intention behind rewriting it was to show an alternate way in a way that i thought will be easier to maintain. And it does not have comments because, comments lose meaning as code changes, but variable names do not. Thats why variables in above code has some meaning behind their names.</p>\n\n<p>And another intention behind making it class is, it is easy to extend. UX requirements changes very rapidly. Tomorrow OP might have to show all the slides and switch them using timer. UX team might ask to click and show the slide instead of showing in automated way.</p>\n\n<p>Thank you for the excellent inputs in comments section.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T08:22:54.097",
"Id": "417901",
"Score": "3",
"body": "Just posting an alternative implementation isn't the goal of this site. You should explain why you consider your solution better. To be honest I find your solution over-engineered for the given task."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T16:45:46.943",
"Id": "417959",
"Score": "0",
"body": "@RoToRa Thanks for clarifying. I thought my explanation was enough to showcase what problems it is solving but looks like not. Also can you tell me more about why do you think its over engineered? I am curious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T19:44:01.093",
"Id": "417984",
"Score": "0",
"body": "I agree that it is over cooked. Code complexity is source of bugs, and feature creep is a common reason for undue complexity, You have added features not required, to accommodate these features you have had to add a lot more code (5 times as much as is needed). In addition the expanded features have been added such to expose an unsafe interface that if not used correctly will throw or produce unexpected behavior. Keep it simple is an important part of good code design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T03:59:58.663",
"Id": "418001",
"Score": "0",
"body": "I really enjoy your code, which is why I wish I didn't have to say that the scope creep is obscuring key lessons for the OP. Not only the amount of extra code the OP must digest but also this ensuing commentary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T04:28:33.130",
"Id": "418004",
"Score": "0",
"body": "I winced when I saw `var prototype = {...}`. I can just see this happening `prototype.prototype.anotherFunction = ...`. Even this: `prototype = ...` would cause anyone to pause in uncertainty. The potential confusion is not worth it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T04:36:25.747",
"Id": "418005",
"Score": "0",
"body": "... cont. My lessons learned: Immediate Invoked Function Expression (IIFE) encapsulate all the code and so naturally makes it more portable (reusable). Said more concisely: **Stay out of global scope!!** Hear me now and believe me later. ... Nice Single Responsibility Principle illustration: functionally focused methods. I can \"see\" the functional parts of a rotational image display. Also notice how these well named methods and variables simply do not require comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T07:41:52.260",
"Id": "418129",
"Score": "0",
"body": "Thanks for the excellent inputs. I added some content to explain the rationale behind my solution."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T06:05:48.233",
"Id": "215977",
"ParentId": "215967",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "215974",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T02:02:49.047",
"Id": "215967",
"Score": "2",
"Tags": [
"javascript",
"html",
"animation"
],
"Title": "JavaScript change image every three seconds"
} | 215967 |
<p>I've done a little bit of programming in the past, mostly just dabbling.
After a long time of not touching an IDE, I am getting back into it, with Visual Studio. I just threw this quick project together to make sure I remember how to use classes and objects before I start playing with bigger projects.</p>
<p>I would love a quick critique to make sure there arent any glaring poor practices that could develop into bad habbits in the future.</p>
<p>I know the standard way to solve this problem is just time = distance/(velA+velB), but what would the point of using objects be if i didnt have the objects do something and change their status in someway?</p>
<p>What do you think, looks good?</p>
<pre><code>/*
The goal for this practice program is to solve the common math word problem below using classes and objects.
I feel that using iterations rather than the basic math formula to solve, although clearly less efficient, would be more true to thinking in terms of objects.
Train A, traveling X miles per hour (mph), leaves Westford heading toward Eastford, 260 miles away.
At the same time Train B, traveling Y mph, leaves Eastford heading toward Westford.
When do the two trains meet? How far from each city do they meet?
*/
#include "pch.h"
#include <iostream>
using namespace std;
class Train
{
public:
Train(int, int);
int getLocation();
void update();
private:
int location, velocity;
};
Train::Train(int loc, int vel) //to initialize the train object and set its location and velocity
{
location = loc;
velocity = vel;
}
int Train::getLocation() // returns the location of the train object
{
return location;
}
void Train::update() // updates the train object for one iteration
{
location += velocity;
}
int main()
{
int velA, velB, distance; //to take the values from the user input
int time; // to keep track of the number of iterations
// time is declared here so it can be used outside of the for loop
//input
cout << "Enter velocity of the train from Westford:\n";
cin >> velA;
cout << "\n\nEnter velocity of the train from Eastford:\n";
cin >> velB;
cout << "\n\nEnter the distance between Westford and Eastford:\n";
cin >> distance;
//initialize each train
Train trainA(0, velA);
Train trainB(distance, 0 - velB); //location of trainB is distance because the distance between an x coordinate at 0 and another x coordinate is equal to the second x coordinate
//the velocity of trainB is the negative of velB because it is traveling in the opposite direction of trainA
//run the sim
for (time = 0; trainA.getLocation() < trainB.getLocation(); time++)
{
trainA.update();
trainB.update();
}
//output
cout << "\n\nThe Trains pass eachother after " << time << " hours."
<< "\nAt that time, the Westford train is " << trainA.getLocation() << " miles from Westford\n"
<< "and the Eastford train is " << distance - trainB.getLocation() << " miles from Eastford.\n\n";
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T03:05:05.917",
"Id": "417887",
"Score": "0",
"body": "I guess a do while loop could make more sense here than a for loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T12:58:42.070",
"Id": "417934",
"Score": "0",
"body": "At this stage of your learning, an IDE like Visual Studio is likely overkill. This is my preference, of course, but I would personally never use Visual Studio for C++ unless I was specifically developing for Windows using the C++ Windows API. With simple applications like this one, a basic text editor like Atom would be all you really need, and you can compile and run from the command line. For more advanced projects, I would choose Clion over Visual Studio any day of the week for portable C++ applications. YMMV."
}
] | [
{
"body": "<ul>\n<li><p>Note that <code>pch.h</code> header is not standard, and probably should not be part of this review.</p></li>\n<li><p><a href=\"https://stackoverflow.com/q/1452721/551375\">Don't do <code>using namespace std;</code></a>.</p></li>\n<li><p>Use initializer lists. That is, the constructor should be written as <code>Train::Train(int loc, int vel) : location(loc), velocity(vel) { }</code>. For POD types this might not matter, but it is idiomatic.</p></li>\n<li><p>Because <code>int getLocation()</code> does not modify the state of the object, it should be made const, i.e., <code>int getLocation() const</code>.</p></li>\n<li><p>In your main program, don't strive to declare all variables as soon as possible as this is C++ and not C. Instead, introduce variables as late as possible and as close to their site of usage as possible. As a remark, you should also initialize e.g., <code>time</code> when you define it to improve readability.</p></li>\n<li><p>Yes, you could use a while-loop, but the for-loop has the advantage that you have to make an explicit decision as to what happens at the end of the loop in order for the program to compile. Because you need the <code>time</code> variable outside of the loop, you could do say <code>for(; trainA.getLocation() < trainB.getLocation(); ++time) { ... }</code>. A while-loop is also perfectly fine, and this boils down mostly to personal preference. </p></li>\n<li><p>Perhaps you should enforce the train speeds to be positive. Otherwise you can get stuck in an infinite loop as the trains will never meet.</p></li>\n<li><p>Your comments are too verbose. Good code is self-documenting via variables names and logical structure. Prefer comments that answer \"why\" to \"what\". For example, a comment like \"input\", \"initialize each train\", and \"run the sim\" are unnecessary, and only hurt readability. </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T17:33:50.400",
"Id": "417964",
"Score": "0",
"body": "Only in strictly standard-conforming pre-C99 C you would declare all the variables at the start of a block and later assign."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T17:38:48.040",
"Id": "417966",
"Score": "0",
"body": "@Deduplicator Exactly."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T10:23:03.553",
"Id": "215989",
"ParentId": "215968",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "215989",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T02:05:44.147",
"Id": "215968",
"Score": "5",
"Tags": [
"c++",
"beginner",
"c++17"
],
"Title": "Calculating when trains will meet, iteratively and using OOP"
} | 215968 |
<p>There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.</p>
<p>For example, if N is 4, then there are 5 unique ways:</p>
<blockquote>
<pre><code>1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
</code></pre>
</blockquote>
<p>What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.</p>
<pre class="lang-java prettyprint-override"><code>public class DailyCodingProblem12 {
public static void main(String args[]) {
int[] X = { 1, 2 };
int N = 4;
int result = solution(N, X);
System.out.println(result);
int[] X1 = { 1, 2, 3 };
N = 4;
result = solution(N, X1);
System.out.println(result);
int[] X2 = { 1, 2, 3 };
N = 3;
result = solution(N, X2);
System.out.println(result);
}
static int solution(int N, int[] X) {
int[] memory = new int[N + 1];
memory[0] = 1;
memory[1] = 1;
return noOfWays(N, X, memory);
}
static int noOfWays(int N, int[] X, int[] memory) {
if (memory[N] != 0) {
return memory[N];
}
int noOfWays = 0;
for (int i = 0; i < X.length && (N - X[i] >= 0); i++) {
memory[N - X[i]] = noOfWays(N - X[i], X, memory);
noOfWays += memory[N - X[i]];
}
return noOfWays;
}
}
</code></pre>
<p>How do I improve my solution? There is a way to save more space?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T06:00:25.293",
"Id": "417894",
"Score": "2",
"body": "You know, most of the things in the replies you've received in your previous questions apply to this too. You should start by applying them to your coding style instead of making us waste our time repeating the same things over and over again. Please don't treat this site as a place where you just dump your coding challenge answers to get a better score. You're diminishing the value of this site for the people who want to learn to be better programmers."
}
] | [
{
"body": "<h2>Dynamic programming approach</h2>\n\n<p>My main advice is to prefer bottom-up iteration to top-down memoization. These are the two main approaches to dynamic programming as described on <a href=\"https://en.wikipedia.org/wiki/Dynamic_programming#Computer_programming\" rel=\"nofollow noreferrer\">Wikipedia</a>. Now, while there is nothing absolutely wrong with top-down approaches, bottom-up is, at least for this problem</p>\n\n<ul>\n<li>cleaner to code</li>\n<li>does not take up space on the stack</li>\n<li>runs faster if method calls are slower than iteration</li>\n</ul>\n\n<p>Finally, your code may re-compute the same values multiple times. This is not true of all top-down approaches, but is easy to avoid using bottom-up dynamic programming.</p>\n\n<h2>Bugs</h2>\n\n<ul>\n<li>incorrect if <code>X</code> is not sorted</li>\n<li>incorrect if <code>X</code> does not contain <code>1</code> due to unnecessary <code>memory[1] = 1</code></li>\n</ul>\n\n<h2>Minor style points</h2>\n\n<ul>\n<li>use more descriptive class and variable names</li>\n<li>instead of <code>N - X[i] >= 0</code> use <code>N >= X[i]</code></li>\n<li>prefer enhanced <code>for</code> loops</li>\n</ul>\n\n<pre><code>static int solution(int totalStairs, int[] stepSizeOptions) {\n int[] numberWays = new int[totalStairs+1];\n numberWays[0] = 1;\n\n for (int numStairs = 1; numStairs <= totalStairs; numStairs++) {\n for (int stepSize : stepSizeOptions) {\n if (numStairs >= stepSize) {\n numberWays[numStairs] += numberWays[numStairs - stepSize];\n }\n }\n }\n\n return numberWays[totalStairs];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T07:03:54.777",
"Id": "216036",
"ParentId": "215973",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216036",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T05:04:26.590",
"Id": "215973",
"Score": "1",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Return the number of unique ways you can climb the staircase"
} | 215973 |
<p>I try the most to solve a twoSum problem in leetcode </p>
<blockquote>
<p>Given an array of integers, return <strong>indices</strong> of the two numbers such that they add up to a specific target.</p>
<p>You may assume that each input would have <strong>exactly</strong> one solution, and you may not use the <em>same</em> element twice.</p>
<p><strong>Example:</strong></p>
<p>Given nums = [2, 7, 11, 15], target = 9,</p>
<p>Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].</p>
</blockquote>
<p>The plan:</p>
<ol>
<li>brute force to iterate len(nums) O(n) </li>
<li>search for target - num[i] with a hash table O(1)</li>
</ol>
<p>Implement</p>
<pre><code>class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_d = {}
for i in range(len(nums)):
nums_d.setdefault(nums[i], []).append(i)
for i in range(len(nums)):
sub_target = target - nums[i]
nums_d[nums[i]].pop(0) #remove the fixer
result = nums_d.get(sub_target)#hash table to search
if result:
return [i, result[0]]
return []
</code></pre>
<p>I strives hours for this solution but found that answer accepted but not passed Score 60.</p>
<blockquote>
<p>Runtime: 60 ms, faster than 46.66% of Python3 online submissions for Two Sum.
Memory Usage: 16.1 MB, less than 5.08% of Python3 online submissions for Two Sum.</p>
</blockquote>
<p>I want to refactor the codes so that to achieve at least faster than 60%.</p>
<p>Could you please provide hints?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T12:26:39.280",
"Id": "417932",
"Score": "1",
"body": "Take care not to misuse the term [refactoring](https://refactoring.com) when you just mean rewriting."
}
] | [
{
"body": "<blockquote>\n <p>You may assume that each input would have exactly one solution. </p>\n</blockquote>\n\n<p>So there's no need to iterate over <code>num</code> twice. In fact, you won't even iterate over it for the full range, because you can return when you found the solution. </p>\n\n<p>With the input given, I'd try this: </p>\n\n<pre><code>nums = [2, 7, 11, 15]\ntarget = 9\n\ndef twoSum(nums, target):\n for i in nums:\n for m in nums[nums.index(i)+1:]:\n if i + m == target:\n return [nums.index(i), nums.index(m)]\n\nprint(twoSum(nums, target)) \n</code></pre>\n\n<p>Say <code>i + m</code> is your target twoSum, you iterate over nums for each i and then look in the rest of num if there's any <code>m</code> for which <code>i + m = target</code>, and return when found. </p>\n\n<p><strong>Edit:</strong> This fails if you have duplicate integers in nums that add up to target, and it'll be slower if the solution is two elements near the end of nums. </p>\n\n<p>Also: thank you for mentioning <a href=\"https://leetcode.com/problems/two-sum/description/\" rel=\"nofollow noreferrer\">Leetcode</a>, it's new to me. Nice! </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T22:29:15.400",
"Id": "417988",
"Score": "2",
"body": "Hey, long time no see! Unfortunately the code you've supplied is worse than the one in the question, as it takes \\$O(n^2)\\$ time and either \\$O(n)\\$ or \\$O(n^2)\\$ memory, depending on the GC. Where in the question it runs in \\$O(n)\\$ time and space. Yours is however easier to understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:54:36.803",
"Id": "418086",
"Score": "0",
"body": "Hi, yes, I know, Ludisposed pointed that out as well, hence the edit. I came across the question in Triage, and thought I might as well try an answer. Hadn't thought beyond nums given, with which it yields the answer in 1+3+1=5 iterations. I'm not familiar with O(n^2), but I guess that'd be 16 here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T22:19:16.803",
"Id": "418103",
"Score": "0",
"body": "Ah, he must have deleted his comments. :( Yes it goes by the worst case, so if 11 and 15 were the targets. It's different from mathematics however, as your function runs in IIRC worst case \\$\\frac{n^2}{2}\\$ iterations. And so it's mostly just a vague guess at performance."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T08:02:14.050",
"Id": "215983",
"ParentId": "215975",
"Score": "0"
}
},
{
"body": "<h2>First some stylistic points</h2>\n\n<ul>\n<li><p><code>nums_d.setdefault(nums[i], []).append(i)</code></p>\n\n<p>The <code>setdefault</code> is unnecessary here, you can assign a list normally</p>\n\n<pre><code>nums_d[nums[i]] = [i]\n</code></pre></li>\n<li><p>When you need both the <code>index</code> and the <code>element</code> use enumerate <a href=\"https://www.python.org/dev/peps/pep-0279/\" rel=\"noreferrer\">see PEP279</a></p>\n\n<blockquote>\n<pre><code>nums_d = {}\nfor i in range(len(nums)):\n nums_d.setdefault(nums[i], []).append(i)\n</code></pre>\n</blockquote>\n\n<pre><code>nums_d = {}\nfor i, e in enumerate(nums):\n nums_d[e] = [i]\n</code></pre></li>\n<li><p>Use comprehension when possible (They use the C style looping and is considered to be faster)</p>\n\n<pre><code>nums_d = { e: [i] for i, e in enumerate(nums) }\n</code></pre></li>\n</ul>\n\n<h2>Hint</h2>\n\n<p>You loop over nums twice, but this can be done in one loop! <em>To make it O(n)</em></p>\n\n<p>Whenever you visit a new element in nums -></p>\n\n<p>Check if it's sum complement is in <code>nums_d</code>, else add the <code>target - element</code> to the dictionary with the index as value <code>t - e : i</code></p>\n\n<blockquote class=\"spoiler\">\n <p> <pre><code>nums_d = {}\nfor i, e in enumerate(nums):\n if e in nums_d:\n return [nums_d[e], i]\n nums_d[target - e] = i</code> </pre></p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T11:17:51.713",
"Id": "418026",
"Score": "1",
"body": "Your first bullet point is only true if each number in the array is unique. Otherwise you override instead of append."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T16:28:01.303",
"Id": "418064",
"Score": "2",
"body": "@Graipher True, a `defaultdict` might be more appropriate there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T00:23:00.670",
"Id": "418760",
"Score": "0",
"body": "\\$O(2n) = O(n).\\$"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T08:47:39.267",
"Id": "215985",
"ParentId": "215975",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "215985",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T05:27:12.560",
"Id": "215975",
"Score": "9",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x",
"k-sum"
],
"Title": "Hash table solution to twoSum"
} | 215975 |
<p>I'm developing a face recognizing application using the <a href="https://pypi.org/project/face_recognition/" rel="nofollow noreferrer">face_recognition Python library</a>. </p>
<p>The faces are encoded as 128-dimension floating-point vectors. In addition to this, each named known person has a variance value, which is refined iteratively for each new shot of the face along with the mean vector. I took the refining formula from <a href="https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm" rel="nofollow noreferrer">Wikipedia</a>. </p>
<p>I'm getting some false positives with the recognized faces, which I presume is because the library was developed primarily for Western faces whereas my intended audience are primarily Southern-Eastern Asian. <strong>So my primary concern with my code, is about whether or not I had gotten the mathematics correct</strong>. </p>
<p>Here's my refining algorithm in Python</p>
<pre><code>import sys
from functools import reduce
from math import hypot
# fake testing data.
# new reference face.
refenc = (0.2, 0.25, 0.4, 0.5) * 32
# previous face encoding and auxiliary info.
baseenc = (0.2, 0.3, 0.4, 0.5) * 32
v = 0.01 # variance
n = 3 # current iteration
n = min(n, 28) # heuristically limited to 28.
vnorm = lambda v: reduce(hypot, v)
vdiff = lambda u, v: list(map(lambda s,t:s-t, u, v))
delta1 = vdiff(refenc, baseenc)
if( vnorm(delta1) > 0.4375 and n > 1 ):
sys.exit() # possibly selected wrong face.
pass
newenc = [ baseenc[i] + delta1[i] / n for i in range(128) ]
delta2 = vdiff(delta1, newenc)
v = v*(n-1)/n + vnorm(delta1)*vnorm(delta2)/n
print(repr((newenc, v, n)))
</code></pre>
<p><strong>Irrelevant note</strong>
: I used struct.(un)pack to serialize in binary to save space, because the <code>repr</code> of the data is too big. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T10:01:15.427",
"Id": "417909",
"Score": "0",
"body": "Please consider updating your question with example inputs, so that a reviewer can test run it. See also [How to create a MWE](https://stackoverflow.com/help/mcve)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T10:15:57.177",
"Id": "417913",
"Score": "0",
"body": "Another comment for clarification more on the core of the question: Is there a specific rationale behind why you chose to pack/unpack your values instead of storing them separately as, e.g. as a tuple?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T11:54:27.310",
"Id": "417928",
"Score": "0",
"body": "@Alex I put testing data in the example."
}
] | [
{
"body": "<p>I can't say I understand exactly what your algorithm does. Even when looking at Wikipedia it is hard to see. So, why don't you just use the reference implementation from there? It has functions with nice names and everything (well, not quite <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> compatible, but that could be changed).</p>\n<p>Alternatively, once you have vectors of numbers and want to perform fast calculations on them, you probably want to use <code>numpy</code>, which allows you to easily perform some operation on the whole vector, like taking the difference between two vectors, scaling a vector by a scalar, taking the sum, etc.</p>\n<pre><code>import numpy as np\n\nMAGIC_CUTOFF = 0.4375\n\nclass WrongFaceException(Exception):\n pass\n\ndef norm(x):\n return np.sqrt((x**2).sum())\n\ndef update(base_encoding, new_face_encoding, v, n):\n delta1 = new_face_encoding - base_encoding\n if norm(delta1) > MAGIC_CUTOFF and n > 1:\n raise WrongFaceException(f"norm(delta1) = {norm(delta1)} > {MAGIC_CUTOFF}")\n new_encoding = base_encoding + delta1 / n\n delta2 = delta1 - new_encoding\n v = v * (n - 1) / n + norm(delta1) * norm(delta2) / n\n return new_encoding, v, n + 1\n\nif __name__ == "__main__":\n new_face_encoding = np.array((0.2, 0.25, 0.4, 0.5) * 32)\n base_encoding = np.array((0.2, 0.3, 0.4, 0.5) * 32)\n v = 0.01\n n = 3\n \n updated_encoding, v, n = update(base_encoding, new_face_encoding, v, n)\n print(updated_encoding, v, n)\n</code></pre>\n<p>In addition to using <code>numpy</code>, I expanded some of the names so it is clearer what they are, I made the cutoff value a global constant (you should give it a meaningful name), added a custom exception instead of just dying (the <code>pass</code> after it was unneeded and unreachable BTW), which makes it more clear what happened, wrapped the calling code under a <code>if __name__ == "__main__":</code> guard to allow importing from this script without running it and followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, by having operators surrounded by one space.</p>\n<p>Instead of this <code>norm</code> function, you can also use <code>scipy.linalg.norm</code>, which might be even faster.</p>\n<hr />\n<p>To answer if you used the math correctly, I would say partially yes. It looks like you implemented the explicit formula given for the sample variance:</p>\n<p><span class=\"math-container\">\\$\\sigma^2_n = \\frac{(n - 1)\\sigma^2_{n-1} + (x_n - \\bar{x}_{n-1})(x_n - \\bar{x}_n)}{n}\\$</span></p>\n<p>However, note that Wikipedia also mentions that this formula suffers from numerical instabilities, since you "repeatedly subtract a small number from a big number which scales with <span class=\"math-container\">\\$n\\$</span>".</p>\n<p>Instead you want to keep the sum of the squared differences <span class=\"math-container\">\\$M_{2,n} = \\sum_{i=1}^n (x_i - \\bar{x}_n)^2\\$</span> around and update that:</p>\n<p><span class=\"math-container\">\\$M_{2,n} = M_{2,n-1} + (x_n - \\bar{x}_{n-1})(x_n - \\bar{x}_n)\\$</span></p>\n<p>with</p>\n<p><span class=\"math-container\">\\$\\bar{x}_n = \\bar{x}_{n -1} + \\frac{x_n - \\bar{x}_{n-1}}{n}\\$</span></p>\n<p>Then the new population variance is given simply by:</p>\n<p><span class=\"math-container\">\\$\\sigma^2_n = \\frac{M_{2,n}}{n - 1}\\$</span></p>\n<p>This is a bit tricky to implement, since your <span class=\"math-container\">\\$x_i\\$</span> are actually vectors of numbers, so you would need to find out how to properly reduce it in dimension (in your previous formula you used the norm for that).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T11:12:57.623",
"Id": "216048",
"ParentId": "215984",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216048",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T08:18:24.487",
"Id": "215984",
"Score": "2",
"Tags": [
"python",
"statistics",
"clustering"
],
"Title": "Welford's online variance calculation algorithm for vectors"
} | 215984 |
<p>I have a program that prints the star pattern. </p>
<p><strong>Starr Pattern is:</strong></p>
<pre><code> *
*
*
*
* * * * * * * * *
*
*
*
*
</code></pre>
<p><strong>My code is:</strong></p>
<pre><code>$n=5;
for($i=0; $i<$n; $i++){
for($k=$n-$i; $k>0; $k--){
echo ' '.' ';
}
for($j=0; $j< ($tot = $i+1); $j++){
if($i==$j && $tot<$n){
echo '* ';
}else{
if($tot<$n){
echo ' '.' ';
}else{
echo '* ';
}
}
}
if($i == ($n-1)){
for($l=$n-1; $l>0;$l--){
echo '* ';
}
}
echo '<br/>';
}
for($i=0;$i<$n;$i++){
for($k=$n-$i; $k>0; $k--){
echo ' '.' ';
}
for($j=0; $j< ($tot = $i+1); $j++){
if($i==$j && $tot<$n){
echo '* ';
}else{
echo ' '.' ';
}
}
echo '<br/>';
}
</code></pre>
<p>My question is that how can I calculate the complexity of this code?</p>
<p>And also Is there a good way to reduce loops?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T14:35:41.203",
"Id": "417944",
"Score": "0",
"body": "Looks like a Plus `+` to me, guess it's just semantics...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T14:45:26.443",
"Id": "417946",
"Score": "0",
"body": "`good way to reduce loops` yes `str_repeat` and `chunk_split` you can see this example (a code golf answer I did) of what you can do with these 2, https://codegolf.stackexchange.com/questions/171679/i-done-did-made-a-spaceship-maw/171820#171820 basically you could make one long string with the space or `*` by using str_repeat and then split it into rows with chunk_split"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T14:50:08.800",
"Id": "417947",
"Score": "0",
"body": "Thanks, @ArtisticPhoenix, I have seen it but didn't get any logic because of the code in a single line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T14:56:17.457",
"Id": "417948",
"Score": "1",
"body": "For example `function f($n){$s='';$b=str_pad('*',($m=$n*2+1),' ',2);for($i=0;$i<$m;++$i)$s.=($i==$n)?str_repeat('*',$m):$b;return chunk_split($s, $m);}` [Sandbox](http://sandbox.onlinephpfunctions.com/code/63fad88e64131201b5d8feeef170860e8fa3840e)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T14:59:45.220",
"Id": "417949",
"Score": "0",
"body": "It looks nice. Can you please make me understand how it works."
}
] | [
{
"body": "<blockquote>\n <p>It looks nice. Can you please make me understand how it works</p>\n</blockquote>\n\n<p>For example</p>\n\n<pre><code> function f($n){$s='';$b=str_pad('*',($m=$n*2+1),' ',2);for($i=0;$i<$m;++$i)$s.=($i==$n)?str_repeat('*',$m):$b;return chunk_split($s, $m);}\n</code></pre>\n\n<p>Output</p>\n\n<pre><code> * \n * \n * \n * \n * \n***********\n * \n * \n * \n * \n</code></pre>\n\n<p><a href=\"http://sandbox.onlinephpfunctions.com/code/63fad88e64131201b5d8feeef170860e8fa3840e\" rel=\"nofollow noreferrer\">Sandbox</a></p>\n\n<p>Let me write it in a way that is easier to see</p>\n\n<pre><code>$n = 5;\n$row_len = $n*2+1;\n$output = '';\n//pad $n spaces on each side of *\n$default = str_pad('*',$row_len,' ',STR_PAD_BOTH); //is = \" * \"\n\n//loop once for each vertical row (same as width)\nfor($i=0;$i<$row_len;++$i){\n if($i==$n){\n //do the center line all *'s\n $output .= str_repeat('*',$row_len);//is = \"***********\"\n }else{\n //use the default line from above\n $output .= $default;\n }\n}\n\n//now we have a single line that is the length squared so we can chunk it\n//into equal parts, to make a square\necho chunk_split($output, $row_len); //is = \" * * ***********\"\n</code></pre>\n\n<p><a href=\"http://sandbox.onlinephpfunctions.com/code/44f69816d63af15dca63e9c62a8ce31da6a726e0\" rel=\"nofollow noreferrer\">Sandbox</a></p>\n\n<p>Basically we can create the <code>\" * \"</code> row by using string pad. Because we can pad spaces on both sides of a <code>*</code> up to the length of a row <code>($n*2)+1</code>.</p>\n\n<p>Then the center row, is just <code>*</code> so we can use string repeat to the length of the row for that line.</p>\n\n<p>Last we take our big huge line of spaces and <code>*</code> and split it into chunks (<code>\\n</code>) on the length of our row we want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T15:18:30.227",
"Id": "417952",
"Score": "2",
"body": "Hope that helps explain it a bit better. Basically were exploiting the fact that it conforms to a set pattern. So for example we know if `$n` is `5` to do 5 spaces a star and 5 more spaces `($n*2)+1` So we can just use String Pad for that and pad 5 spaces on each side. String Pad takes the total length of the string you want. So it's the full length of the row."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:05:23.577",
"Id": "418493",
"Score": "0",
"body": "I think your output is skinnier than the OPs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:26:29.937",
"Id": "418499",
"Score": "0",
"body": "@mickmackusa - it is. I didn't put a space between `* *` the stars. Shouldn't be too hard to fix, but it adds a variable in. So I was too lazy .... lol"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T01:58:28.843",
"Id": "420731",
"Score": "0",
"body": "DEREGISTERED!!!! What have you done, you mad man! What causes a person to do that?!? An occupational requirement? Witness protection?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T15:09:06.317",
"Id": "215999",
"ParentId": "215992",
"Score": "3"
}
},
{
"body": "<p>Here's my array-functional spin on the task. It is not likely to be faster than @ArtisticPhoenix's solution, but it provides the desired output without loop constructs or conditions. ...just different for the sake of being different.</p>\n\n<p>The process generates a full-sized array of strings that \"looks\" like a vertical stroke of asterisks, then replaces the middle element with a horizontal stroke element.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/LHgsZ\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$size = 7; // circumference not radius \n$vertical = str_pad('*', $size * 2 - 1, ' ', STR_PAD_BOTH); // row w/ central symbol\n$result = array_fill(0, $size, $vertical); // top-to-bottom stroke of symbols\n$result[$size / 2] = implode(' ', array_fill(0, $size, '*')); // left-to-right stroke of symbols\necho implode(PHP_EOL, $result);\n</code></pre>\n\n<p>For improved readability, I've declared the single-use variable <code>$vertical</code>.</p>\n\n<p>Output: (highlight the text with your cursor to see that the pattern has no unnecessary trailing spaces in any line.)</p>\n\n<pre><code> * \n * \n * \n* * * * * * *\n * \n * \n * \n</code></pre>\n\n<p>*notice that I am not bothering to <code>floor()</code> the \"horizontal stroke\" element key, because php casts float keys to integers. <a href=\"https://www.php.net/manual/en/language.types.array.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/language.types.array.php</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T22:44:18.573",
"Id": "216299",
"ParentId": "215992",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215999",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T12:28:00.840",
"Id": "215992",
"Score": "2",
"Tags": [
"php",
"complexity",
"ascii-art"
],
"Title": "Program that prints star pattern"
} | 215992 |
<p>I tried a binary solution to 3Sum problem in LeetCode:</p>
<blockquote>
<p>Given an array <code>nums</code> of <span class="math-container">\$n\$</span> integers, are there elements <span class="math-container">\$a\$</span>, <span class="math-container">\$b\$</span>, <span class="math-container">\$c\$</span> in <code>nums</code> such that <span class="math-container">\$a + b + c = 0\$</span>? Find all unique triplets in the array which gives the sum of zero.</p>
<p><strong>Note:</strong></p>
<p>The solution set must not contain duplicate triplets.</p>
<p><strong>Example:</strong></p>
<pre><code>Given array nums = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]
</code></pre>
</blockquote>
<p>My plan: divide and conquer <code>threeSum</code> to</p>
<ol>
<li>an iteration </li>
<li>and a <code>two_Sum</code> problem. </li>
<li>break <code>two_Sum</code> problem to
<ol>
<li>a loop </li>
<li>binary search </li>
</ol></li>
</ol>
<p>The complexity is: <span class="math-container">\$O(n^2\log{n})\$</span>.</p>
<pre><code> class Solution:
"""
Solve the problem by three module funtion
threeSum
two_sum
bi_search
"""
def __init__(self):
self.triplets: List[List[int]] = []
def threeSum(self, nums, target=0) -> List[List[int]]:
"""
:type nums: List[int]
:type target: int
"""
nums.sort() #sort for skip duplicate and binary search
if len(nums) < 3:
return []
i = 0
while i < len(nums) - 2:
complement = target - nums[i]
self.two_sum(nums[i+1:], complement)
i += 1 #increment the index
while i < len(nums) -2 and nums[i] == nums[i-1]: #skip the duplicates, pass unique complement to next level.
i += 1
return self.triplets
def two_sum(self, nums, target):
"""
:type nums: List[int]
:tppe target: int
:rtype: List[List[int]]
"""
# nums = sorted(nums) #temporarily for testing.
if len(nums) < 2:
return []
i = 0
while i < len(nums) -1:
complement = target - nums[i]
if self.bi_search(nums[i+1:], complement) != None:
# 0 - target = threeSum's fixer
self.triplets.append([0-target, nums[i], complement])
i += 1
while i < len(nums) and nums[i] == nums[i-1]:
i += 1
def bi_search(self, L, find) -> int:
"""
:type L: List[int]
:type find: int
"""
if len(L) < 1: #terninating case
return None
else:
mid = len(L) // 2
if find == L[mid]:
return find
if find > L[mid]:
upper_half = L[mid+1:]
return self.bi_search(upper_half, find)
if find < L[mid]:
lower_half = L[:mid] #mid not mid-1
return self.bi_search(lower_half, find)
</code></pre>
<p>I ran it but get the report</p>
<blockquote>
<p>Status: Time Limit Exceeded</p>
</blockquote>
<p>Could you please give any hints to refactor?</p>
<p>Is binary search is an appropriate strategy?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T00:40:07.480",
"Id": "417999",
"Score": "0",
"body": "Binary search is good at O(log n), but hash search is better at O(1)."
}
] | [
{
"body": "<p>Your <code>bi_search()</code> method is recursive. It doesn’t have to be. Python does not do tail-call-optimization: it won’t automatically turn the recursion into a loop. Instead of <code>if len(L) < 1:</code>, use a <code>while len(L) > 0:</code> loop, and assign to (eg, <code>L = L[:mid]</code>) instead of doing a recursive call. </p>\n\n<p>Better: don’t modify <code>L</code> at all, which involves copying a list of many numbers multiple times, a time consuming operation. Instead, maintain a <code>lo</code> and <code>hi</code> index, and just update the indexes as you search. </p>\n\n<p>Even better: use a built in binary search from <code>import bisect</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T13:59:01.560",
"Id": "215997",
"ParentId": "215994",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "215997",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T13:06:01.460",
"Id": "215994",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded",
"k-sum"
],
"Title": "A binary search solution to 3Sum"
} | 215994 |
<p>I need to determine the status of a parent object based on 2 variables of each of its children. I came up with a working solution, but this includes a nested "if-else if-else". Needless to say, it doesn't look very elegant. </p>
<p>I was wondering if there is a way to simplify this. I have muddled around with some map/reduce code, but did not get to anything that is more elegant than the code below. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const parent = {
children: [{
connected: true,
online: true
},
{
connected: true,
online: true
}
]
}
// all online & all connected => connected
// all online & some connected => partially disconnected
// all online & none connected => disconnected
// some online => partially offline
// none online => offline
const onlineArr = parent.children.map(c => c.online);
const connectedArr = parent.children.map(c => c.connected);
let status;
if (!onlineArr.includes(true)) {
status = 'Offline';
} else if (!onlineArr.includes(false)) {
if (!connectedArr.includes(true)) {
status = 'Disconnected';
} else if (!connectedArr.includes(false)) {
status = 'Connected';
} else {
status = 'Partially disconnected';
}
} else {
status = 'Partially offline';
}
console.log(status);</code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>As a function</h2>\n<p>When you write code, even as an example, always write it as a function. A function is returnable, and thus can be written differently than non returnable flat execution.</p>\n<h2>Comment code mismatch</h2>\n<blockquote>\n<p><em>"Comments are just lies in waiting."</em><br />\n<sub>...by unknown guru.</sub></p>\n</blockquote>\n<p>Your comments do not match the code. The comments specify lowercase status, your code capitalists the status. Which is correct is anyone's guess. <strike>I will assume the comments are correct and that the status is formatted upon display. (It makes the solution simpler)</strike> Changed my mind and will assume the code has been tested and is correct.</p>\n<h2>Inefficiency === Inelegance</h2>\n<p>The nested statements are not inelegant (in a function it would not need any <code>else</code> statements), its the two <code>Array.map</code> and three <code>Array.includes</code> that are very inefficient for the task at hand, which to me is ugly inelegance.</p>\n<h2>Solution</h2>\n<p>It is the number of online, connected children that you need to know.</p>\n<p>If the number of online children</p>\n<ul>\n<li>is the same as the number of children then all are online.</li>\n<li>is the less than as the number of children and not zero then some are online.</li>\n<li>is zero then none are online</li>\n</ul>\n<p>The same applies for connected children.</p>\n<p>Thus count the two types and use the counts to return the status, as follows</p>\n<pre><code>function connectionStatus(clients) {\n const count = clients.length;\n var onC = 0, conC = 0; \n for (const {connected, online} of clients) {\n conC += connected;\n onC += online;\n }\n if (onC === count) {\n if (conC === count) { return "Connected" }\n return conC ? "Partially disconnected" : "Disconnected";\n }\n return onC ? "Partially offline" : "Offline";\n}\n\nconnectionStatus(parent.children);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T17:27:58.167",
"Id": "440055",
"Score": "0",
"body": "I would replace _var onC = 0, conC = 0;_ with _const metrics = { connected: 0, online: 0 };_ to gain additional readability. And a chained ternary operator to return the result string perhaps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T19:08:37.093",
"Id": "440069",
"Score": "0",
"body": "@dfhwze The line between personal preference and idiomatic style often finds me writing code I am not comfortable with. I prefer nested ternaries, but don't like the down votes. Obj `metric` to encap names would decrease readability, it just adds noise. Reassigning names in loop .`{connected: con, online: on} of clients` then vars `connected += con; online += on` rather than `conC` and `onC` but was unsure re browser support. Most annoying was the strings caps. All lowercase was is my pref, not really the functions role to format bio speak, hand that to CSS or higher level code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T19:14:56.077",
"Id": "440072",
"Score": "0",
"body": "It's a pitty ppl downvote nested ternaries. They are compact and don't hurt readability at all :("
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T16:46:57.797",
"Id": "216004",
"ParentId": "215998",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T14:10:31.250",
"Id": "215998",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Classifying connectivity status based on online and connected status of multiple nodes"
} | 215998 |
<p>I have been working with Rcpp to perform a forward and backward <a href="https://en.wikipedia.org/wiki/Hilbert_curve#Applications_and_mapping_algorithms" rel="nofollow noreferrer">Hilbert Mapping</a>. Below is an implementation based on <a href="https://people.sc.fsu.edu/~jburkardt/cpp_src/hilbert_curve/hilbert_curve.cpp" rel="nofollow noreferrer">this code</a>.</p>
<p>My application is in genomics and I may be dealing with enormous datasets, which necessitates the use of very large integers for indices, so I found <a href="https://stackoverflow.com/questions/49015493/integer64-and-rcpp-compatibility">this code</a> for passing large integers to R using Rcpp and the bit64 R package and incorporated it after the <code>for</code> loop.</p>
<p>The <code>xy2d()</code> function works properly. My interest is on your thought regarding the code AFTER the <code>for</code> loop, which prepared the result for passage back to R. Please let me know what you think :)</p>
<pre><code>#include <Rcpp.h>
using namespace Rcpp;
# include <bitset>
# include <cstdint>
# include <ctime>
# include <iomanip>
# include <iostream>
using namespace std;
//****************************************************************************80
// [[Rcpp::export]]
Rcpp::NumericVector xy2d ( int m, uint64_t x, uint64_t y )
//
//****************************************************************************80
{
uint64_t d = 0;
uint64_t n;
int rx;
int ry;
uint64_t s;
n = i4_power ( 2, m );
if ( x > n - 1 || y > n - 1) {
throw std::range_error("Neither x nor y may be larger than (2^m - 1)\n");
}
for ( s = n / 2; s > 0; s = s / 2 )
{
rx = ( x & s ) > 0;
ry = ( y & s ) > 0;
d = d + s * s * ( ( 3 * rx ) ^ ry );
rot ( s, x, y, rx, ry );
}
std::vector<uint64_t> v;
v.push_back(d);
//v[0] = d
size_t len = v.size();
Rcpp::NumericVector nn(len); // storage vehicle we return them in
// transfers values 'keeping bits' but changing type
// using reinterpret_cast would get us a warning
std::memcpy(&(nn[0]), &(v[0]), len * sizeof(uint64_t));
nn.attr("class") = "integer64";
return nn;
}
</code></pre>
<p>This post will be followed up shortly with another post regarding the <code>rot()</code> function, and well as the reverse <code>d2xy()</code> function</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T16:24:29.310",
"Id": "417955",
"Score": "0",
"body": "@422_unprocessable_entity: The Hilbert mapping function works with no problems. I am seeking advice on the code AFTER the for-loop in which I prepare the results to be passed to R. \"Hilbert Mapping - xy2d function\" makes that unclear. I feel that my original title was better, would you agree?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T17:18:34.330",
"Id": "417961",
"Score": "0",
"body": "Welcome to CR. I edited the question title because I thought it can be improved as recommended [here](https://codereview.meta.stackexchange.com/a/2438/47826). Anyway it is a good question."
}
] | [
{
"body": "<ul>\n<li><p>Because we write C++, there's no reason to declare (most) variables at the beginning of the scope of your function. For example, all of <code>d</code>, <code>rx</code>, <code>ry</code> and <code>s</code> have been declared for no reason if you happen to throw and exit the function.</p></li>\n<li><p>You don't need <code>s</code> after the for-loop, so it should be local to the loop only. Similar for <code>rx</code> and <code>ry</code>.</p></li>\n<li><p>Make use of shorthand operators like <code>/=</code> and <code>+=</code>.</p></li>\n<li><p>You can make <code>v</code> const and initialize it with a suitable constructor, in this case <code>std::vector<uint64_t> v(1, d);</code> initializes <code>v</code> to hold one element equal to <code>d</code>. But really, as it stands, I see no point in using an array here if you just have a single value (I suspect your example is incomplete and not representative of your real use case, which is a shame).</p></li>\n<li><p>Because <code>len</code> can be const, make it const. This protects from unintended errors and possibly allows the compiler to perform more optimizations.</p></li>\n<li><p>As a general comment, avoid saying <code>using namespace std;</code>, it's not good for you.</p></li>\n<li><p>I don't know the interface of <code>Rcpp::NumericVector</code>, but might you initialize it directly in the spirit of <code>const Rcpp::NumericVector nn(v.cbegin(), v.cend())</code>, for instance?</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T17:26:14.617",
"Id": "418710",
"Score": "0",
"body": "These are excellent critiques. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T17:06:06.277",
"Id": "216005",
"ParentId": "216000",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216005",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T15:23:24.517",
"Id": "216000",
"Score": "5",
"Tags": [
"c++",
"c++11",
"r",
"coordinate-system",
"rcpp"
],
"Title": "Passing uint64_t from C++ to R: Hilbert Mapping - xy2d function"
} | 216000 |
<p>I am just starting my journey in to rust and will gladly accept any feedback you can give me. This is the third exercise in the Rust book chapter 8.</p>
<p>Exercise description </p>
<blockquote>
<p>Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.</p>
</blockquote>
<p>src/main.rs</p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;
mod commands;
fn main() {
let mut departments: HashMap<String, Vec<String>> = HashMap::new();
println!("Welcome to Rust IFS");
loop {
commands::print_menu();
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.expect("Invalid input");
if input.to_lowercase().contains("q") && input.len() <= 5 {
break;
} else if input.to_lowercase().contains("add") && input.to_lowercase().contains("to") {
println!("{}", commands::add_user(&mut input, &mut departments));
} else if input.to_lowercase().contains("list") && input.len() == 5 {
commands::print_users(&mut input, &mut departments);
} else if input.to_lowercase().contains("list") && input.len() > 5 {
commands::print_users_by_department(&input, &mut departments)
} else {
println!("\nInvalid input");
}
println!("Press Enter to continue...");
commands::pause();
}
}
</code></pre>
<p>src/commands.rs</p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::io::Read;
pub fn add_user(input: &mut String, departments: &mut HashMap<String, Vec<String>>) -> String {
let split: Vec<&str> = input.split_whitespace().collect();
if split.len() == 4 && split[0].contains("add") && split[2].contains("to") {
if departments.contains_key(split[3]) {
match departments.entry(String::from(split[3])) {
Entry::Vacant(e) => {
e.insert(vec![String::from(split[1])]);
}
Entry::Occupied(mut e) => e.get_mut().push(String::from(split[1])),
}
String::from("Success!")
} else {
departments.insert(String::from(split[3]), vec![String::from(split[1])]);
String::from("Success!")
}
} else {
String::from("Invalid input")
}
}
pub fn print_menu() {
println!("Type: add [name] to [department] to add an employee to a department");
println!("Type: list users to list all users");
println!("Type: list [department] to list all users in department");
println!("Type Quit to quit");
}
pub fn pause() {
std::io::stdin().read(&mut [0]).expect("Invalid input");
}
pub fn print_users(input: &mut String, departments: &mut HashMap<String, Vec<String>>) {
let split: Vec<&str> = input.split_whitespace().collect();
if split.len() == 1 {
for department in departments {
department.1.sort();
println!("{}:", department.0);
for name in department.1 {
println!("{}", name)
}
}
}
}
pub fn print_users_by_department(input: &String, departments: &mut HashMap<String, Vec<String>>) {
let split: Vec<&str> = input.split_whitespace().collect();
if split.len() == 2 {
for department in departments {
department.1.sort();
if department.0 == split[1] {
println!("{}:", department.0);
for name in department.1 {
println!("{}", name)
}
}
}
}
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T17:28:44.890",
"Id": "417963",
"Score": "0",
"body": "Welcome to CR. Can you add the challenge description?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T17:34:19.923",
"Id": "417965",
"Score": "0",
"body": "Yes i forgot about that. It's in there now."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T15:36:26.370",
"Id": "216001",
"Score": "3",
"Tags": [
"beginner",
"rust"
],
"Title": "Rust book chapter 8 department challenge"
} | 216001 |
<p>I'm trying to create a generic Makefile that will work with the following directory structure:</p>
<ul>
<li>Project Directory
<ul>
<li>Makefile</li>
<li>main.c source file</li>
<li>source directory
<ul>
<li>Source files</li>
</ul></li>
<li>include directory
<ul>
<li>Header files for each source file</li>
</ul></li>
<li>depend directory
<ul>
<li>GCC generated depend (.d) files for each source/header pair</li>
</ul></li>
<li>object directory
<ul>
<li>all compiled object (.o) files</li>
</ul></li>
</ul></li>
</ul>
<p>It should automatically generate depend files and include them to build the executable. Currently this works for my basic C projects that are all from source but I'm planning on also using this (or some slightly modified version of this) for an OpenGL project using glfw and GLAD. I would like this Makefile to remain cross-platform between MSYS2 on Windows and Linux. Any thoughts?</p>
<pre><code>TARGET = hashtest # executable name
SOURCE_DIR = source
OBJECT_DIR = objects
DEPENDS_DIR = depends
MAIN = main.c
NAMES := $(shell find $(SOURCE_DIR) -name "*.c" -printf "%f\n")
SOURCES := $(addprefix $(SOURCE_DIR)/, $(NAMES))
OBJECTS := $(addprefix $(OBJECT_DIR)/, $(NAMES:.c=.o))
DEPS := $(addprefix $(DEPENDS_DIR)/, $(NAMES:.c=.d))
DEPS += $(DEPENDS_DIR)/$(TARGET).d
INCL_DIRS := $(shell find . -type d -name "include*")
INCL_FLAG := $(addprefix -I , $(INCL_DIRS))
CC = gcc
OBJ_CFLAGS = -g -Wall $(INCL_FLAG) -MMD -MP -MF $(DEPENDS_DIR)/$*.Td -c
TARGET_CFLAGS = -g -Wall $(INCL_FLAG) -MMD -MP -MF $(DEPENDS_DIR)/$@.Td
#Add -mwindows to disable console window opening on launch (stdout can only be piped afterwards)
$(TARGET): $(OBJECTS) | $(DEPENDS_DIR)
$(CC) $(TARGET_CFLAGS) -o $@ $(OBJECTS) $(MAIN)
@mv -f $(DEPENDS_DIR)/$@.Td $(DEPENDS_DIR)/$@.d && touch $@
@echo "Build successful."
$(OBJECT_DIR)/%.o: $(SOURCE_DIR)/%.c $(DEPDIR)/%.d | $(OBJECT_DIR) $(DEPENDS_DIR)
$(CC) $(OBJ_CFLAGS) -o $@ $<
@mv -f $(DEPENDS_DIR)/$*.Td $(DEPENDS_DIR)/$*.d && touch $@
$(OBJECT_DIR):
mkdir -p $(OBJECT_DIR)
$(DEPENDS_DIR):
mkdir -p $(DEPENDS_DIR)
.PHONY: clean
$(DEPDIR)/%.d: ;
.PRECIOUS: $(DEPDIR)/%.d
clean:
rm -f $(OBJECT_DIR)/*.o
rm -f $(DEPENDS_DIR)/*.d
rm -f $(TARGET)
@echo "Clean successful."
-include $(DEPS)
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T18:28:19.087",
"Id": "417971",
"Score": "2",
"body": "My first thought is: did you try CMake? It probably provides all the features you need."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T18:29:22.647",
"Id": "417972",
"Score": "0",
"body": "What does CMake provide that isn't already in this makefile?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:21:54.013",
"Id": "418080",
"Score": "0",
"body": "I'm with @RolandIllig and you can find an explanation [here](https://prateekvjoshi.com/2014/02/01/cmake-vs-make/) on the differences."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T17:30:20.583",
"Id": "216008",
"Score": "3",
"Tags": [
"c",
"makefile",
"gcc"
],
"Title": "Generic Makefile for C projects"
} | 216008 |
<p>This is the main code. Here I'm joining vertices by edges.</p>
<pre><code>node[] gra=new node[5];
{
for (int i = 0; i < 5; i++)
gra[i] = new node(i); //I'm allocating memory for all the vertices.
}
void add_edge(int to,int from) //to represent the vertice the edge is going and from is now self explanatory
{
node new_vert=new node(to);
node temp=gra[from];
while(temp.next!=null)
temp=temp.next;
temp.next=new_vert;
}
</code></pre>
<p>Now to do this operation I'm using this loop in main method.</p>
<pre><code>for(int i=0;i<5;i++) //For simplicity I have taken 5 vertices
{
int n=sc.nextInt(); //N is Number of edges from the vertices, for example in figure for vertex 0 the number of edges are 2.
for(int j=0;j<n;j++)
{
int to=sc.nextInt();
obj.add_edge(to,i);
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/31ml3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/31ml3.png" alt="Example graph"></a></p>
<p>Is my implementation correct or efficient enough so that I can use this code for further use? </p>
<p>Feel free to ask if you don't understand the code; I will try to explain. I know I'm bad at explaining. And please forgive my English.</p>
<p>Here is my node class</p>
<pre><code> class node
{
int data;
node next;
node(int data)
{
this.data=data;
this.next=null;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T06:32:22.487",
"Id": "418013",
"Score": "0",
"body": "Hi Aniket, and welcome! Could you include the code for your `node` class? This would be very helpful in reviewing the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T08:19:40.697",
"Id": "418016",
"Score": "0",
"body": "@BenjaminKuykendall Hi Benjamin I just updated my question you can check it again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T00:30:01.110",
"Id": "418111",
"Score": "1",
"body": "It would be great if you could also include the context in which `gra` and `add_edge` are declared (i.e. the declaration of the enclosing class), for the sake of clarity. Right now, you can only guess that `gra` is a field and not a local variable from the presence of a method declaration directly after it."
}
] | [
{
"body": "<h2>Use Java <code>LinkedList</code> class</h2>\n\n<p>Almost always prefer built-in data structures to hand-rolled. For instance, your insertion routine takes O(n) time while <code>LinkedList::addLast</code> takes O(1) times.</p>\n\n<p>Also, use an <code>ArrayList</code> instead of an array to hold the lists due to problems with generic arrays in Java.</p>\n\n<h2>Write a <code>Graph</code> class</h2>\n\n<p>A class offers a great opportunity to re-organize your code. It makes it easy to separate initialization and adding edges.</p>\n\n<h2>Correctness issues</h2>\n\n<p>Validate the input to <code>addEdge</code>. Throw an exception if either <code>to</code> or <code>from</code> is not in the appropriate range.</p>\n\n<h2>Style issues</h2>\n\n<ul>\n<li>indent and capitalize properly</li>\n<li>write fewer comments: only when something need explaining</li>\n<li>write shorter comments: use sentence fragments</li>\n</ul>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.LinkedList;\n\npublic class Graph {\n private ArrayList<LinkedList<Integer>> adjacencyList;\n\n public Graph(int numberNodes) {\n adjacencyList = new ArrayList<LinkedList<Integer>>(numberNodes);\n for (int i = 0; i < numberNodes; i++) {\n adjacencyList.add(new LinkedList<Integer>());\n }\n }\n\n private boolean isValidNode(int index) {\n return index >= 0 && index < adjacencyList.size();\n }\n\n public void addEdge(int to, int from) {\n if (!isValidNode(to) || !isValidNode(from)) {\n throw new IndexOutOfBoundsException();\n }\n\n adjacencyList.get(from).addLast(to);\n }\n}\n</code></pre>\n\n<pre><code>import java.util.Scanner;\n\npublic class GraphRunner { \n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n Graph g = new Graph(5);\n\n for(int from=0; from < 5; from++) {\n int n=sc.nextInt();\n for(int j=0; j < n; j++) {\n int to=sc.nextInt();\n g.addEdge(to, from);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T11:06:36.010",
"Id": "418135",
"Score": "0",
"body": "ThankYou Benjamin for all the effort you put in reviewing my code I really appreciate it , I will definitely remember all the pointers you gave me. Love Stack Exchange community."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T20:16:36.583",
"Id": "216075",
"ParentId": "216010",
"Score": "2"
}
},
{
"body": "\n\n<p>I found your code rather confusing at first, but I think I now understand your intentions behind the code, so hopefully I can say why these intentions weren't quite clear from the beginning.</p>\n\n<p>The main source of confusion is that, for each adjacency list storing the neighbors of a specific vertex, the vertex this adjacency list corresponds to is represented in two ways: First, through the list's position in the array <code>gra</code>, and second, through the first element in the list. But the second representation is counterintuitive, because you are placing the from-vertex on the same level as the to-vertices. Using the picture you provided as an example, it would be like saying \"vertex 0 has edges to the following vertices: 0, 1 and 4\". It would be more to the point only to store the to-vertices in the list without the from-vertex, because the relation between the to-vertices and the from-vertex is already represented by the adjacency list's position in the array <code>gra</code>.</p>\n\n<p>And a few words about capitalization: Even though the Java compiler does not require class names to start with a capital letter, there are certain naming conventions which, if followed, make it easier for humans to read code. One of these conventions is that class names in Java should start with a capital letter. In your case, this would mean that the class <code>node</code> should be renamed to <code>Node</code>. You can see that even the syntax highlighter doesn't recognize <code>node</code> as a class name if it's not capitalized:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class node {\n\n int data;\n node next;\n\n node(int data) {\n this.data=data;\n this.next=null;\n }\n}\n</code></pre>\n\n<p>vs:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Node {\n\n int data;\n Node next;\n\n Node(int data) {\n this.data=data;\n this.next=null;\n }\n}\n</code></pre>\n\n<p>There are other Java conventions, like naming variables and methods in camelCase (e.g. <code>addEdge</code> instead of <code>add_edge</code>). Also, you might consider using whole words instead of abbreviations, especially if an abbreviation doesn't really save many characters (e.g. <code>newVertex</code> instead of <code>newVert</code>, or <code>graph</code> instead of <code>gra</code>). As far as I can remember, most advice in this regard I came across suggested to avoid abbrevations, and I myself also find <code>newVertex</code> easier to read than <code>newVert</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T11:09:01.013",
"Id": "418137",
"Score": "0",
"body": "Thanks for the effort Stingy I really appreciate it , yesterday someone all ready pointed about that capital letter convention and hearing same again from you, I think I should change.Thanks again man for such a good answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T00:55:48.257",
"Id": "216087",
"ParentId": "216010",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216087",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T17:58:41.807",
"Id": "216010",
"Score": "3",
"Tags": [
"java",
"graph"
],
"Title": "Graph using adjacency list in Java"
} | 216010 |
<p>I need to process an array of number pairs. Here are the constraints on the pairs:</p>
<ol>
<li>The second item may be missing, in this case 0 will be used as second item - - <code>38</code> is the same as <code>38,0</code> </li>
<li>The pair items may be a number, or a range - <code>149,0</code>, <code>149,[3,7]</code>, <code>[5,9],11</code>, <code>[3,6],[2,9]</code>, <code>[4,8]</code></li>
<li>The range may be inclusive or exclusive - <code>[8,11]</code>, <code>[3,9)</code>, <code>(4,10]</code></li>
<li>There may be any number of spaces between items - <code>[ 3 , 6 ]</code></li>
<li>The second item may be <code>>=0</code>, this is the same as bullet #1 - <code>36, >=0</code></li>
</ol>
<p>Why do I need the ranges? If I have, say, <code>149,[3,5]</code>, then I need to have 3 pairs - <code>149,3</code>, <code>149,4</code>, <code>149,5</code>. If I have <code>[8,10]</code>, then the pairs are <code>8,0</code>, <code>9,0</code>, <code>10,0</code>. You get the idea.</p>
<p>I wrote a regex to get the items from the input. I think regex is not the best choice here, maybe I'll change it. Here's my program:</p>
<pre><code>#include <string>
#include <regex>
#include <vector>
using intRange = std::pair<int, int>;
std::vector<std::pair<int, int>> pairs;
intRange getRange(const std::string &value1, const std::string &value2, const std::string &value3)
{
if (value1.length())
return intRange(std::stoi(value1), std::stoi(value1));
if (value2.length() && value3.length())
{
const short startIncrement = value2.front() == '(' ? 1 : 0;
const short endDecrement = value3.back() == ')' ? 1 : 0;
// remove the parentheses
std::string val2 = value2, val3 = value3;
val2.replace(0, 1, std::string{});
val3.pop_back();
return intRange(std::stoi(val2) + startIncrement, std::stoi(val3) - endDecrement);
}
return {};
}
bool parseRange(const std::string &input)
{
pairs.clear();
static const std::regex rx{ R"numrange(\s*(?:(\s*\d+\s*)|([\[\(]\s*\d+)\s*,\s*(\d+\s*[\]\)]))(?:,\s*(?:(\d+\s*)|\s*([\[\(]\d+)\s*,\s*(\d+\s*[\]\)])|(\s*>\s*=\s*0\s*)))?\s*)numrange" };
std::smatch matches;
if (std::regex_match(input, matches, rx))
{
// if 1st (4th) match group exists, first (second) item is a single number
// if 2nd and 3rd (5th and 6th) match groups exist, first (second) item is a range
// if neither 4th nor 5th and 6th groups exist, then second item isn't specified, and default value (0) is used
auto firstRange = getRange(matches[1], matches[2], matches[3]);
auto secondRange = getRange(matches[4], matches[5], matches[6]);
// save all pairs
for (auto first = firstRange.first; first <= firstRange.second; ++first)
for (auto second = secondRange.first; second <= secondRange.second; ++second)
pairs.emplace_back(first, second);
}
else
return false;
return true;
}
int main()
{
std::vector<std::string> inputs = {
"38",
"149,0",
"149,[3,7]",
"[5,9],11",
"[3,6],[2,9]",
"[4,8]",
"[3,9)",
"(4,10]",
"[ 3 , 6 ]",
"36, >= 0"
};
for (const auto &input : inputs)
{
if (parseRange(input))
{
std::cout << "input: " << input << '\n';
for (const auto &pair : pairs)
std::cout << pair.first << ", " << pair.second << '\n';
std::cout << "-------------------\n";
}
else
{
std::cout << "Error occurred.";
return -1;
}
}
std::cin.get();
}
</code></pre>
<p>I think there is room for improvement for this code. Please let me know where I can improve. Thanks.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T06:47:20.023",
"Id": "418014",
"Score": "0",
"body": "You say you need to process an *array* but seemingly match on a *string*. Is your original input an array but you flatten it into a string?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T08:25:09.223",
"Id": "418017",
"Score": "0",
"body": "no it's an array, i just presented the method for a single element. i'm running a simple for loop on the array"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T08:35:04.013",
"Id": "418018",
"Score": "0",
"body": "Might be good to post the entire source code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T08:57:37.957",
"Id": "418020",
"Score": "0",
"body": "I've only omitted the for loop on the array. Another thought is that, I can have a separate regex for each of those cases. don't know if it's more efficient, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T09:23:34.650",
"Id": "418021",
"Score": "0",
"body": "IMO It'd be nice to have the full code along with an example input as it makes it easier to reason about the code and architecture at large. See also [SSCCE](http://sscce.org/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T10:37:06.637",
"Id": "418024",
"Score": "0",
"body": "i've updated the post. this is still an excerpt from a larger program. anyways, it illustrates the idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T16:17:54.177",
"Id": "418586",
"Score": "0",
"body": "@yuri did you have a chance to look at the code? i especially don't like the `getRange` method's body"
}
] | [
{
"body": "<p>Just answering this question since it is unanswered. Hope, it would help: </p>\n\n<p>Since your code is mainly about RegEx, which you'd most likely know that you can use <a href=\"https://regex101.com/r/Wdvkfa/4/\" rel=\"nofollow noreferrer\">this</a> tool:</p>\n\n<ul>\n<li><p>Your original RegEx based on an exact match method takes 265 steps and 1ms to match your 10 inputs, which is good. </p>\n\n<pre><code>\\s*(?:(\\s*\\d+\\s*)|([\\[\\(]\\s*\\d+)\\s*,\\s*(\\d+\\s*[\\]\\)]))(?:,\\s*(?:(\\d+\\s*)|\\s*([\\[\\(]\\d+)\\s*,\\s*(\\d+\\s*[\\]\\)])|(\\s*>\\s*=\\s*0\\s*)))?\\s*\n</code></pre></li>\n<li><p>Sometimes, exact match may not be necessary, not sure about your case or if you might have certain boundaries, but maybe you could use a faster RegEx with a lower number of iterations, maybe something similar to <a href=\"https://regex101.com/r/Wdvkfa/3\" rel=\"nofollow noreferrer\">this</a>, if you are not looking for an exact match, which is pretty fast and might match your 10 inputs with only 50 steps: </p>\n\n<pre><code>^[0-9\\,\\[\\]\\(\\) >=]*$\n</code></pre></li>\n</ul>\n\n<p>The drawback of this method is that it is based on your input characters, i.e., numbers, <kbd>[</kbd>, <kbd>]</kbd>, <kbd>(</kbd>, <kbd>)</kbd>, <kbd>,</kbd>, <kbd>space</kbd> and <kbd>>=</kbd>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T01:52:20.283",
"Id": "217300",
"ParentId": "216012",
"Score": "2"
}
},
{
"body": "<p>The code is pretty easy to read (apart from the monster regexp, but I'm pleased you used raw-string quoting rather than filling it with backslashes!).</p>\n\n<p>Some (mostly stylistic) comments:</p>\n\n<ul>\n<li><p>If <code>getRange()</code> is an internal function, then give it internal linkage (<code>static</code> keyword, or an anonymous namespace). If it's intended to be user-visible, then it could use better argument names (perhaps <code>only</code>, <code>first</code>, <code>last</code>?).</p></li>\n<li><p>I think that <code>if (!string.empty())</code> shows intent a little better than <code>if (string.length())</code>.</p></li>\n<li><p>Avoid calling <code>std::stoi(value1)</code> twice.</p></li>\n<li><p>Prefer to pass <code>pairs</code> to <code>parseRange()</code>, rather than working with a global variable. Also it could be defined as <code>std::vector<intRange></code>.</p></li>\n<li><p>The big regexp could be split into several strings so that it can occupy several shorter lines, just as we do with ordinary string literals.</p></li>\n<li><p>I'd invert the test so we can return early:</p>\n\n<pre><code>std::smatch matches;\nif (!std::regex_match(input, matches, rx)) {\n return false;\n}\n\n// matched (rest of comment omitted)\nauto firstRange = getRange(matches[1], matches[2], matches[3]);\nauto secondRange = getRange(matches[4], matches[5], matches[6]);\n\n/* ... */\n\nreturn true;\n</code></pre></li>\n<li><p>Generation of the result pairs could alternatively be done using <code>std::inner_product()</code>. However, I think the nest of loops expresses it more clearly.</p></li>\n<li><p>You forgot to <code>#include <iostream></code> in the test program (preventing it compiling here).</p></li>\n<li><p><code>inputs</code> doesn't need to be a vector; it can be deduced (<code>auto const inputs</code>) as an initializer list.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T12:27:55.833",
"Id": "217320",
"ParentId": "216012",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217300",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T18:24:16.693",
"Id": "216012",
"Score": "5",
"Tags": [
"c++",
"parsing",
"regex"
],
"Title": "Parsing pairs of a number or number range"
} | 216012 |
<p>I have written the following program in C# to display an ASCII pyramid.</p>
<pre><code>public static void method1()
{
int k;
int kCond = 5;
int i;
int inc = 0;
for (int p = 0; p <=5; p++)
{
for(k = 0; k <= kCond; k++)
{
Console.Write(" ");
}
kCond--;
for(i=0; i<=inc; i++)
{
Console.Write("*")
}
inc +=2;
Console.WriteLine();
}
}
</code></pre>
<p>Output:</p>
<pre><code> *
***
*****
*******
*********
***********
</code></pre>
<p>My question is, is this good code from a performance point of view, or not? How could I improve it?</p>
| [] | [
{
"body": "<p>I took your code and started condensing it, and came up with the following improvements that could be made:</p>\n\n<ul>\n<li>Change the inner loops to use the <code>string</code> constructor that takes a character and a count instead of using a loop</li>\n<li>Give the method and variables more meaningful names</li>\n<li>Add a <code>size</code> parameter that can be passed to the method</li>\n<li>Put declarations and incrementing of variables in the <code>for</code> statement</li>\n<li>Use math operations on the counter rather than tracking multiple variables that increment at constant rates relative to the counter</li>\n<li>Use <code>Enumerable.Range</code> as a looping mechanism to select the strings along with <code>string.Concat</code> to join them together</li>\n<li>Have the method return a string so it can be written by the client to other things (like a log file or another control)</li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>public static string GetPyramid(int size)\n{\n return string.Concat(Enumerable.Range(0, size).Select(count =>\n new string(' ', size - count) + \n new string('*', count * 2 + 1) + \n Environment.NewLine));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T19:24:57.813",
"Id": "417978",
"Score": "0",
"body": "Two more refactorings and you can turn it into a nice linq chain generating only a single result string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T19:36:33.470",
"Id": "417981",
"Score": "0",
"body": "or alternatively with `Aggregate` and `StringBuilder` ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T19:39:16.400",
"Id": "417983",
"Score": "0",
"body": "@VisualMelon done, thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T19:23:21.023",
"Id": "216016",
"ParentId": "216014",
"Score": "4"
}
},
{
"body": "<h2>Performance</h2>\n\n<p>Why do you care about performance, and what aspect of performance matters to you? Since this method takes no inputs, you can probably get better performance by hard-coding the output string, but...</p>\n\n<p>... the performance will be fine: you haven't fallen into the usual trap of concatenating strings. It might be faster to use a <code>StringBuilder</code> to assemble the whole thing and print it out in one, or to generate whole lines at a time, but this is exactly the sort of thing you shouldn't be worrying about <em>unless</em> you have evidence that it is a real problem; reusability and maintainability are significantly more important concerns (so you don't ever have to rewrite the same functionality).</p>\n\n<h2>Other</h2>\n\n<p>Rufus L presented a nice method which returns a <code>String</code> instead of printing directly to the console. Another approach would be to pass <code>PrintPyramid</code> a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.io.textwriter?view=netframework-4.7.2\" rel=\"nofollow noreferrer\"><code>TextWriter</code></a>, so that you can have it write to wherever you want. I would rename the method to <code>WriterPyramid</code>, since that is the usual theme in .NET. Throw in some inline documentation (<code>///</code>) to describe the behaviour, and we have a sensible API:</p>\n\n<pre><code>/// <summary>\n/// Writes a pyramid of stars the given height to the given TextWriter\n/// </summary>\npublic static void WritePyramid(int height, TextWriter writer)\n{\n // TODO: implement\n}\n</code></pre>\n\n<p>You can then pass it <code>System.Console.Out</code> to print to the console, but you can pass it something else if you need to (such as a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.io.stringwriter?view=netframework-4.7.2\" rel=\"nofollow noreferrer\"><code>StringWriter</code></a>), e.g. when you are testing it.</p>\n\n<p>For something so simple this probably isn't worth it, but if you were writing lots of text, or would be writing it out in a later method call, then passing <code>TextWriter</code>s around can be very handy.</p>\n\n<hr />\n\n<p>It is generally advisable to define variables as close to their usage as possible, as it makes their purpose more apparent, and reduces the opportunity for misusing them. For example, as Rufus L suggests, don't forward-declare <code>i</code> and <code>k</code>. They are just counters, and shouldn't be available outside of their respective loops.</p>\n\n<hr />\n\n<p>Be consistent with your white-space. You have <code>p <=5</code>, <code>k <= kCond</code>, and <code>i<=inc</code> all in one method. Generally I go with whatever the IDE of choice does, and in C# that usually means <code>i <= inc</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T20:17:36.190",
"Id": "216019",
"ParentId": "216014",
"Score": "1"
}
},
{
"body": "<p>Rather than send to the console as you build. Build a string then send to the console. This avoids some of the overhead associated with writing to IO.</p>\n\n<p>In terms of performance you can use a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=netframework-4.7.2\" rel=\"nofollow noreferrer\"><code>System.Text.StringBuilder</code></a> and avoid some of the allocation overhead of <code>new String</code>. <code>StringBuilder</code> will allocate new memory as the string grows, doubling the buffer each time it does so. </p>\n\n<p><code>StringBuilder.Append</code> can be used to add a number of <code>char</code> at a time reducing the code complexity.</p>\n\n<p>You can write the built string directly to the console, or if needed convert it to a string via <code>StringBuilder.ToString</code>.</p>\n\n<p>As a function, passing the pyramid <code>size</code> would make it more useful. As an example you can also use an optional argument to define what the pyramid is built of. Optional arguments require a default value</p>\n\n<pre><code>public static void ConsolePyramid(int size, char block = '#') {\n StringBuilder pyramid = new StringBuilder();\n for (int i = 0; i <= size; i++) {\n pyramid.Append(' ', size - i);\n pyramid.Append(block, i * 2 + 1);\n pyramid.Append(Environment.NewLine);\n } \n Console.Write(pyramid);\n}\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>public static string BuildPyramidString(int size, char block = '#') {\n StringBuilder pyramid = new StringBuilder();\n for (int i = 0; i <= size; i++) {\n pyramid.Append(' ', size - i);\n pyramid.Append(block, i * 2 + 1);\n pyramid.Append(Environment.NewLine);\n } \n return pyramid.ToString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T21:24:32.630",
"Id": "216021",
"ParentId": "216014",
"Score": "2"
}
},
{
"body": "<p><strong>Indentation & spacing:</strong> This may not seem important, but it's a very easy and useful\nhabit to get into. For example, it should be obvious at a glance how many <code>for</code>\nloops a given line of code is inside. With this code as-is, two different\n<code>Console.Write</code> commands that actually execute the same number of times are at\ndifferent indentation levels.</p>\n\n<p>There are also inconsistencies with spacing around operators. For example, we have\n<code>p <=5</code>, <code>i<=inc</code>, <em>and</em> <code>k <= kCond</code>. Personally I prefer the last.</p>\n\n<hr/>\n\n<p><strong>Increment & Decrement operators:</strong> This may not seem important, but I believe\nthe <code>i++</code> and <code>kCond--</code> should be replaced by explicit <code>i += 1</code> and <code>kCond -= 1</code>.\nSome modern languages <a href=\"https://stackoverflow.com/a/3660658/2108357\">don't even have them</a>.\nEven the technical reviewer of the C# specification <a href=\"http://www.informit.com/articles/article.aspx?p=2425867\" rel=\"nofollow noreferrer\">regrets their inclusion</a> (scroll to #3).\nAvoiding the use of these operators can prevent <a href=\"https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c\">confusing scenarios</a>.</p>\n\n<hr/>\n\n<p><strong>Minimize Scope:</strong> This may not seem important, but the variable <code>k</code> is never\nreferenced outside of its for loop. Declare it there, as you did for <code>p</code>. The\nsame goes for <code>i</code>. Restricting variable references to the minimum possible scope\nmakes the code easier to read. As it stands, I have to hold the variable \"k\" in\nmy head as I read through the function. If it only existed inside its own loop,\nI could to safely forget about it.</p>\n\n<p>This may feel inefficient - if you are declaring <code>i</code> many times, are you not\nallocating memory for it multiple times? The answer is no. The C# compiler is smarter\nthan that, so <a href=\"https://stackoverflow.com/questions/1884906/declaring-a-variable-inside-or-outside-an-foreach-loop-which-is-faster-better\">the performance is exactly the same</a>.</p>\n\n<hr/>\n\n<p><strong>Reduce Repetition:</strong> This may not seem important, but right now you have two\nfor loops that are almost identical: One for printing <code>\" \"</code>, and one for\nprinting <code>\"*\"</code>. If you create a function</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>private static void PrintMultiple(string str, int times)\n</code></pre>\n\n<p>which calls <code>Console.Write</code> in a little for loop, you move that repetition out\nof your main function, making it easier to read. I'll leave the method itself to you.</p>\n\n<p>This may feel inefficient - if you are calling a method inside of a loop, are you\nnot incurring method call overhead many times? The answer is maybe. The C# compiler\nis smart enough, in some cases, to inline method calls. The only way to determine\nif it's doing that for <em>your</em> code would be to inspect the IL code generated after introducing\nthis method, or perhaps doing some very precise speed tests.</p>\n\n<p>For a sense of scale, however, <a href=\"https://stackoverflow.com/questions/13135759/what-is-the-overhead-for-a-method-call-in-a-loop\">this developer</a>\nnoticed that a method call was not being inlined, and the performance impact on their code\nwas noticeable: a 0.4 second slowdown for <em>billions</em> of method calls. When printing\na 6-line ASCII pyramid, you are unlikely to notice a difference.</p>\n\n<p>If, however, you are very concerned by nanosecond delays, one approach you\nmight consider is building your strings in larger chunks using the\n<code>new String(char, int)</code> constructor. You <em>may</em> find it to be <a href=\"https://stackoverflow.com/a/411766/2108357\">slightly more\nefficient</a> than printing them one\ncharacter at a time. Then again, you may not. Only extensive testing or IL inspection\nwill tell.</p>\n\n<hr/>\n\n<p><strong>Direct Formulas:</strong> This may not seem important, but it's easier to reason about\nvariable <em>assignments</em> than variable <em>modifications</em>. Since the value of <code>kCond</code>\nchanges by a constant amount when (and only when) the value of <code>p</code> changes, you\ncan calculate it directly instead of repeatedly subtracting from its initial value.</p>\n\n<p>This also allows you to declare the variables <code>kCond</code> and <code>i</code> inside of the main\nloop, reducing their scope.</p>\n\n<p>This may feel inefficient - If the values are being calculated from scratch every time, are we not being hurt by the fact that multiplication is slower than addition? The answer is <a href=\"https://social.msdn.microsoft.com/Forums/vstudio/en-US/001a5d05-44b7-4006-8242-70276bceb62d/performance-of-basic-operations?forum=csharpgeneral\" rel=\"nofollow noreferrer\">no, not really</a>. Both operations can be done hundreds of millions of times per second - and those numbers are from nearly a decade ago.</p>\n\n<hr/>\n\n<p><strong>Names:</strong> This may not seem important, but the name of this method says nothing\nabout what it's supposed to do, and none of these variables say anything about\nhow it is being done. If you showed me this code without also showing me the\noutput, it might take me several minutes to figure out what the code is <em>for</em>.</p>\n\n<p>At this point, the function now looks like this:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>public static void method1()\n{\n for (int p = 0; p <= 5; p += 1)\n {\n int kCond = 6 - p;\n PrintMultiple(\" \", kCond);\n\n int inc = p * 2 + 1;\n PrintMultiple(\"*\", inc);\n\n Console.WriteLine();\n }\n}\n</code></pre>\n\n<p>And some possible names for the variables become clear:</p>\n\n<pre class=\"lang-csharp prettyprint-override\"><code>public static void PrintPyramid()\n{\n for (int row = 0; row <= 5; row += 1)\n {\n int numberOfSpaces = 6 - row;\n PrintMultiple(\" \", numberOfSpaces);\n\n int numberOfStars = row * 2 + 1;\n PrintMultiple(\"*\", numberOfStars);\n\n Console.WriteLine();\n }\n}\n</code></pre>\n\n<p>I hope you'll find that our series of seemingly-unimportant changes resulted in code that is both highly readable and acceptably performant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T23:19:35.223",
"Id": "216024",
"ParentId": "216014",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T18:42:49.577",
"Id": "216014",
"Score": "1",
"Tags": [
"c#",
"beginner",
"console",
"ascii-art"
],
"Title": "Program that prints an ASCII pyramid"
} | 216014 |
<p>I am writing the linked list data structure, using <a href="https://codereview.stackexchange.com/q/215546/153727">this</a> question's requirements (the method set).</p>
<p>I have written two working methods, which do the similar thing and differs by only few lines. So, I tried to refactor them and although I move the duplicate part to the separate function, the code became more verbose. Also, it added two function calls overhead, that is not good for data structure implementations.</p>
<p><strong>The question:</strong></p>
<ol>
<li>Do you see another way to duplication elimination? </li>
<li>I understand, that in this particular case, it will be better to leave everything as it is, without refactoring. But from the point of best production practices and "pythonic" way, which variant will be better?</li>
</ol>
<p><strong>Before refactoring</strong> </p>
<pre><code>def insert_before_key(self, key, value):
new_node = Node(value)
prev, curr = self._find_key(key)
if curr:
if prev:
new_node.next = curr # differs
prev.next = new_node # differs
else:
new_node.next = self.head # differs
self.head = new_node # differs
def insert_after_key(self, key, value):
new_node = Node(value)
prev, curr = self._find_key(key)
if curr:
if prev:
new_node.next = curr.next # differs
curr.next = new_node # differs
else:
new_node.next = self.head.next # differs
self.head.next = new_node # differs
</code></pre>
<p><strong>After refactoring</strong></p>
<pre><code># Common part was moved to this function
def insert(self, key, value, with_prev, non_prev):
new_node = Node(value)
prev, curr = self._find_key(key)
if curr:
if prev:
with_prev(prev, curr, new_node)
else:
non_prev(prev, curr, new_node)
# put two little chunks of code to the nested functions
# and pass them to the "insert" function, that implement the logic
def insert_before_key(self, key, value):
def with_prev(prev, curr, new_node):
new_node.next = curr
prev.next = new_node
def non_prev(prev, curr, new_node):
new_node.next = self.head
self.head = new_node
self.insert(key, value, with_prev, non_prev)
def insert_after_key(self, key, value):
def with_prev(prev, curr, new_node):
new_node.next = curr.next
curr.next = new_node
def non_prev(prev, curr, new_node):
new_node.next = self.head.next
self.head.next = new_node
self.insert(key, value, with_prev, non_prev)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T20:04:31.270",
"Id": "417985",
"Score": "2",
"body": "This is roughly what I would have done if I had thought trying to reduce duplication was worth it here. I'm not sure it is worth it here though. I find the generalized code harder to read, and the original functions are small enough that the gain isn't huge."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T19:52:23.310",
"Id": "216018",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"linked-list"
],
"Title": "The code duplication reducing in the linked list implementation"
} | 216018 |
<p>This is my first full program I've written in C. It took me about 2 hours to pull together today. Looking for any sort of feedback on the code, formatting, cleanliness etc. I didn't follow any guides or tutorials, but did have some existing C++ knowledge and knowledge in other languages.</p>
<p>The game is Mastermind. The way it works is that the computer generates a 4 color code randomly from a pool of 7 colors. Then, the user must guess what the code is in as few guesses as possible. The user must guess 4 colors, and the feedback given is how many colors of the guess are a part of the code, and how many of the colors are placed correctly.</p>
<p>There's more on the Wikipedia page: <a href="https://en.m.wikipedia.org/wiki/Mastermind_(board_game)" rel="nofollow noreferrer">https://en.m.wikipedia.org/wiki/Mastermind_(board_game)</a></p>
<p>Thanks</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#define RESET "\x1B[0m"
#define BLOCK "█"
#define RED "\x1B[31m" BLOCK RESET
#define GRN "\x1B[32m" BLOCK RESET
#define YEL "\x1B[33m" BLOCK RESET
#define BLU "\x1B[34m" BLOCK RESET
#define MAG "\x1B[35m" BLOCK RESET
#define CYN "\x1B[36m" BLOCK RESET
#define WHT "\x1B[37m" BLOCK RESET
#define RED_C "\x1B[31m"
#define GRN_C "\x1B[32m"
#define YEL_C "\x1B[33m"
#define BLU_C "\x1B[34m"
#define MAG_C "\x1B[35m"
#define CYN_C "\x1B[36m"
#define WHT_C "\x1B[37m"
#define COLORS 6
#define LENGTH 4
enum Colors {
red,
green,
yellow,
blue,
magenta,
cyan,
white
};
static const enum Colors Color_map[] = {red, green, yellow, blue, magenta, cyan, white};
void *generate_colors(enum Colors *buffer)
{
int power = pow(COLORS + 1, LENGTH);
int colors_integer = rand() % power;
for (int i = 0; i < LENGTH; ++i)
{
int remainder = colors_integer % (COLORS + 1);
int divisor = colors_integer / (COLORS + 1);
buffer[i] = Color_map[remainder];
colors_integer = divisor;
}
}
int convert_input(char *input, enum Colors *buffer)
{
for (int c = 0; c < strlen(input); ++c)
{
char character = tolower(input[c]);
switch (character)
{
case 'r':
buffer[c] = red;
break;
case 'g':
buffer[c] = green;
break;
case 'y':
buffer[c] = yellow;
break;
case 'b':
buffer[c] = blue;
break;
case 'm':
buffer[c] = magenta;
break;
case 'c':
buffer[c] = cyan;
break;
case 'w':
buffer[c] = white;
break;
default:
return 1;
}
}
return 0;
}
char *color_to_char(enum Colors color)
{
switch (color)
{
case red:
return RED;
case green:
return GRN;
case yellow:
return YEL;
case blue:
return BLU;
case magenta:
return MAG;
case cyan:
return CYN;
default:
return WHT;
}
}
int main()
{
srand(time(NULL));
enum Colors selected_colors[4];
generate_colors(selected_colors);
int guessed = 0;
do {
char input[LENGTH];
scanf("%s", input);
if (strlen(input) == LENGTH)
{
enum Colors converted[LENGTH];
int contains_unmatched = convert_input(input, converted);
int correct_place = 0;
int correct_color = 0;
if (contains_unmatched)
{
printf("Please only choose characters from " RED_C "R, " GRN_C "G, " YEL_C "Y, " BLU_C "B, " MAG_C "M, " CYN_C "C, " WHT_C "W" RESET ".\n");
}
else
{
printf("You guessed: ");
for (int i = 0; i < LENGTH; ++i)
{
enum Colors color = converted[i];
enum Colors actual = selected_colors[i];
if (color == actual)
++correct_place;
else
{
for (int j = 0; j < LENGTH; ++j)
{
if (j != i)
{
enum Colors current = selected_colors[j];
if (color == current)
{
++correct_color;
break;
}
}
}
}
printf("%s", color_to_char(converted[i]));
}
if (correct_place == LENGTH)
{
printf("Well done! You got it right. Goodbye");
return 0;
}
else
{
printf("\n %d correct color\n %d correct place and color\n", correct_color, correct_place);
}
}
}
else
{
printf("Please enter 4 characters.\n");
}
} while (!guessed);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T05:43:47.267",
"Id": "418008",
"Score": "0",
"body": "Can you add an explanation on what this is (supposed to be) doing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T05:59:44.237",
"Id": "418009",
"Score": "0",
"body": "@yuri https://en.wikipedia.org/wiki/Mastermind_(board_game) and maybe also https://codereview.stackexchange.com/questions/202809/a-simple-mastermind-clone/202848"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T10:02:06.903",
"Id": "418134",
"Score": "1",
"body": "BTW, the program has a bug. Obviously noticeable with input like `RRRR` it can state: `2 correct color 2 correct place and color`. How to I swap my `R`'s to the correct order :-) If the hidden code only has two `R` it should report `0 correct color 2 correct place and color`."
}
] | [
{
"body": "<ul>\n<li>Maybe have a scheme to keep header files sorted. Makes it easier to spot possible duplicate includes.</li>\n<li><p><code>enum Colors</code> should be <code>enum Color</code>, every enum instance in only one at a time.</p></li>\n<li><p>To keep track of a true enumerated sequence add max enum to keep track of the number of colors.</p>\n\n<pre><code>magenta,\ncyan,\nwhite,\n\nCOLORS }; // == 7\n</code></pre>\n\n<p>(Thus, don't forget to remove <code>#define COLORS 6</code>.)</p></li>\n<li><code>Color_map</code> not really needed in this case since they are nicely enumerated. Just replace <code>buffer[i] = Color_map[remainder];</code> with <code>buffer[i] = (enum Color)remainder;</code>.</li>\n<li>Doesn't look like <code>void *generate_colors(enum Colors *buffer)</code> is returning anything, so just make it <code>void generate_colors(...</code>.</li>\n<li>Since <code>COLORS</code> now is <code>7</code> instead of <code>6</code>, replace all <code>COLORS + 1</code> with just <code>COLORS</code>.</li>\n<li>In <code>generate_colors</code>, <code>int power ...</code> can be <code>const int power ...</code>.</li>\n<li>Interface to <code>convert_input</code> can be <code>const</code> for its input, i.e., <code>int convert_input(const char *input, enum Color *buffer)</code>.</li>\n<li>Simplify and speed up start of loop. E.g., don't check <code>strlen(input)</code> every interation, it's not changing. No need to call <code>strlen</code> (see below). <code>tolower</code> needs <code>unsigned char</code> to guarantee proper functionality, thus, platform dependent on signess of <code>char</code>.</li>\n</ul>\n\n<p>Example</p>\n\n<pre><code>for (int c = 0;; ++c) // Look, no check for end of string done here\n{\n switch (tolower((unsigned char)input[c]))\n {\n case 'r':\n</code></pre>\n\n<p>...</p>\n\n<pre><code> case '\\0': // add end-of-string check here\n return 0;\n default:\n return 1;\n }\n }\n}\n</code></pre>\n\n<ul>\n<li><code>const char *color_to_char(enum Colors color)</code> since it return <code>const</code> strings.</li>\n<li>Input handling not kind on the user when entering wrong. Instead, read the whole line and parse the line for you guess.</li>\n</ul>\n\n<p>Example</p>\n\n<pre><code>char* line = NULL;\nsize_t line_len = 0u;\n\nwhile (!guessed && getline(&line, &line_len, stdin) != -1)\n{\n char input[LENGTH + 1]; // OBS: This was too small before\n sscanf(line, \" %4s\", input); // automatic skip of white space\n // and limit input to 4 real characters\n // discarding the rest of the line.\n</code></pre>\n\n<ul>\n<li>Split wide <code>printf</code> statement and don't color the commas.</li>\n</ul>\n\n<p>Snippet:</p>\n\n<pre><code>printf(\"%s\\n\", \"Please only choose characters from \"\nRED_C \"R\" RESET \", \"\nGRN_C \"G\" RESET \", \"\nYEL_C \"Y\" RESET \", \"\nBLU_C \"B\" RESET \", \"\nMAG_C \"M\" RESET \", \"\nCYN_C \"C\" RESET \", \"\nWHT_C \"W\" RESET \".\");\n</code></pre>\n\n<ul>\n<li>And if you use <code>getline</code>, free memory at end.</li>\n</ul>\n\n<p>Snippet:</p>\n\n<pre><code>}\n\nfree(line);\n\nreturn EXIT_SUCCESS;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T09:47:16.623",
"Id": "418132",
"Score": "0",
"body": "Thank you, there's lots for me to consider here! I'm curious as to why it's necessary to free memory before exiting the program- is this not something the OS should do automatically?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T09:54:00.653",
"Id": "418133",
"Score": "1",
"body": "For me it's just customary, but is really help memory leak tools to help me identify the different types of leaks a program might have. By not `free`-ing it's harder to tell if if you have unintentional memory leaks that might eat up memory in the long run. But mostly, the OS will return the memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T12:03:57.697",
"Id": "418140",
"Score": "0",
"body": "Okay, thanks. Another small query: I realize you replaced a `do..while` loop with a `while` loop. Is the only reason for this to do with the usage of `getline` in it, or are `do..while` loops something that should be generally avoided?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T13:51:36.410",
"Id": "418155",
"Score": "1",
"body": "Generally prefer `while/for` over `do..while`. They make it easier to understand the logic. In this case it was also to combine the termination of `getline` with your `guessed` logic."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:12:20.260",
"Id": "216066",
"ParentId": "216020",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T20:18:43.650",
"Id": "216020",
"Score": "7",
"Tags": [
"beginner",
"c"
],
"Title": "First C Program- Mastermind"
} | 216020 |
<p>I just finished working on a personal project, it is a sort of email type program where you create an account and you can message people, the code works (as far as I’m aware) but it requires review, different areas have different indents, I add more variable than I need, I print things that don’t need to be printed and probably way more than that.</p>
<p>(I realise that it will say import getpass ,and have nothing for it in the code , that is because i forgot to change the password inputs to getpass inputs before putting it on my drive.)</p>
<p>Where the code is located in your files you need a folder called Data with txt files: <code>accountIDs</code>, <code>addCommandList</code>, <code>isAdmin</code>, <code>names</code>, <code>nicknames</code>, <code>passwords</code>.</p>
<p>A folder called messages in it a folder called received.</p>
<pre><code>import random
from random import *
import datetime
import string
import os
import getpass
global usernames
global passwords
global jointPassList
usernames = [line.strip()for line in open('Data/names.txt', 'r')]
passwords = [line.strip()for line in open('Data/passwords.txt', 'r')]
isAdmin = [line.strip()for line in open('Data/isAdmin.txt', 'r')]
accountIDs = [line.strip()for line in open('Data/accountIDs.txt', 'r')]
nicknames = [line.strip()for line in open('Data/nicknames.txt', 'r')]
jointPassList ='\n'.join(map(str, passwords))
def main():
print('\n')
print('\n')
print('/help (1/2) for help')
currentUserIndex = usernames.index(ascname)
command =input('>>>')
if command =='/help':
print('/signout | sign out\n/details | account details\n/setpas | set password\n/userlist | all users\n/mymessages | your messages\n/message | message\n/addcommand | add command')
input()
main()
if command =='/details':
print('Name: ', ascname)
print('AccountID: ', accountIDs[currentUserIndex])
print('Nickname: ', nicknames[currentUserIndex])
input()
main()
if command =='/setpas':
newpas =input('Enter your new password: ')
passwords[currentUserIndex] = newpas
jointPassList ='\n'.join(map(str, passwords))
openfile =open('Data/passwords.txt', 'w')
openfile.write(jointPassList)
openfile.close()
input()
main()
if command =='/userlist':
userlist =open('Data/names.txt').read()
print(userlist)
input()
main()
if command =='/message':
whatuser =input('What user: ')
if whatuser in usernames:
message =input('What message would you like to send: ')
openfile =open('Data/messages/recieved/'+whatuser+'.txt', 'a')
date = str(datetime.datetime.now())
openfile.write(date + ' : ')
openfile.write(message+'\n')
openfile.close()
input()
main()
elif whatuser not in usernames:
print('Nobody was found.')
input()
main()
if command =='/mymessages':
messagesList = [line.strip()for line in open('Data/messages/recieved/'+ascname+'.txt', 'r')]
messages = '\n'.join(messagesList)
print(messages)
input()
main()
if command =='/addcommand':
openfile =open('Data/addCommandList.txt', 'a')
addcommand =input('What would you like see added to this database: ')
openfile.write(addcommand+'\n')
openfile.close()
input()
main()
if command =='/admin':
print(isAdmin[currentUserIndex])
if isAdmin[currentUserIndex] =='True':
print('Nice :)')
input()
main()
elif isAdmin[currentUserIndex] =='False':
print('You are not an Admin')
change =input()
if change =='False':
isAdmin[currentUserIndex] = True
main()
else:
main()
if isAdmin[currentUserIndex] =='False':
delete =input('Are you sure you would like to delete your account: ')
if delete =='y':
accountIDs.remove(accountIDs[currentUserIndex])
isAdmin.remove(isAdmin[currentUserIndex])
usernames.remove(usernames[currentUserIndex])
passwords.remove(passwords[currentUserIndex])
nicknames.remove(nicknames[currentUserIndex])
os.remove('Data/messages/recieved/'+ascname+'.txt')
openfile = open('Data/names.txt', 'w')
openfile.write(name + '\n')
openfile.close()
openfile = open('Data/accountIDs.txt', 'w')
openfile.write(str(accountID) + '\n')
openfile.close()
openfile = open('Data/nicknames.txt', 'w')
openfile.write(nickname + '\n')
openfile.close()
openfile = open('Data/passwords.txt', 'w')
openfile.write(password + '\n')
openfile.close()
openfile = open('Data/isAdmin.txt', 'w')
openfile.write(adminFalse + '\n')
openfile.close()
print('Complete...')
signin()
if command =='/signout':
areYouSure =input('Are you sure you would like to sign out(y/n): ')
if areYouSure =='y':
print('Signing out\n.\n.\n.')
signin()
elif areYouSure =='n':
main()
else:
main()
else:
print(command, 'is not a command in our library, type /addcommand to request new command.')
input()
main()
def signin():
existingAccount =input('Do you have an existing account (y/n): ')
if existingAccount =='y':
global ascname
global ascpass
ascname =input('Enter your username: ')
currentUsername = ascname
if ascname in usernames:
userIndex = usernames.index(ascname)
print('Correct username.')
ascpass =input('Enter your password: ')
while ascpass in passwords:
passcheck = passwords.index(ascpass)
if userIndex == passcheck:
print('welcome back', ascname + '.')
main()
else:
wrongPass =input('Incorrect password.')
input()
signin()
print('Yes')
wrongPass =input('Incorrect password.')
input()
signin()
elif ascname not in usernames:
wrongName =input('Incorrect username.')
input()
signin()
else:
#debuging
print('Error')
singin()
elif existingAccount =='n':
name =str(input('Enter your name: '))
while len(name) == 0:
name =input("You haven't entered anything, try again.")
input()
signin()
if name in open('Data/names.txt').read():
name =input('That name already exists.')
input()
signin()
usernames.append(name)
password =input('Enter your new password: ')
while len(password) < 4:
password =input('Your password must be 5 characters long.')
input()
signin()
passwords.append(password)
nickname =input('Enter your nickname: ')
accountID =random()
while accountID in accountIDs:
accountID =random()
adminFalse = str(False)
isAdmin.append(adminFalse)
openfile = open('Data/messages/recieved/' +name+ '.txt', 'w+')
openfile.write('\n')
openfile.close()
openfile = open('Data/names.txt', 'a')
openfile.write(name + '\n')
openfile.close()
openfile = open('Data/accountIDs.txt', 'a')
openfile.write(str(accountID) + '\n')
openfile.close()
openfile = open('Data/nicknames.txt', 'a')
openfile.write(nickname + '\n')
openfile.close()
openfile = open('Data/passwords.txt', 'a')
openfile.write(password + '\n')
openfile.close()
openfile = open('Data/isAdmin.txt', 'a')
openfile.write(adminFalse + '\n')
openfile.close()
signin()
else:
signin()
signin()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T14:49:58.327",
"Id": "418048",
"Score": "6",
"body": "Why don't you clean up the things that you know should be cleaned up (such as indentation) before asking for our advice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:24:40.717",
"Id": "418081",
"Score": "0",
"body": "Thank you Emma for the edit, I am very new to this. There were no incorrect indents and i have added comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T19:11:32.943",
"Id": "418090",
"Score": "2",
"body": "An answer was written while you proposed changes, invalidating the edit. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to incorporate the suggested changes and post a follow-up question instead. Please note, it may be beneficial to wait at least 2 days before doing so."
}
] | [
{
"body": "<ol>\n<li><p>Ban yourself from recursion. If you're in the function <code>main</code> don't call <code>main</code>. What you want is to have a <code>while True</code> loop and to use <code>continue</code>.</p>\n\n<pre><code>while True:\n ...\n if invalid_username:\n continue\n ...\n</code></pre></li>\n<li><p><code>json</code> is likely to make your code much easier to use. As you don't have to have 5 lists for five attributes on a user.</p></li>\n<li><code>cmd.Cmd</code> is probably what you want to use. This is as you can put all your functions in their own functions and you can focus on what the code does.</li>\n<li>Your code has a lot of useless <code>print</code> <code>input</code> and other nonsense statements. Follow he Unix way and remove them.</li>\n<li>Global variables are <em>bad</em>. Whilst the changes I'll recommend still use them, I've hidden them behind properties on a class. Which encourages safer programming practices.</li>\n<li>You should keep the database in memory, and ensure it's written to when the program ends. You can do this via <code>try</code> <code>finally</code>.</li>\n<li>I've partially changed your program to use <code>cmd.Cmd</code>, changing <code>signin</code> to also be one is up to you. I encourage you to look at the docs as the builtin <code>help</code> command is nice.</li>\n<li>Wrap your main code in an <code>if __name__ == '__main__'</code> guard.</li>\n</ol>\n\n\n\n<pre><code>import random\nfrom random import *\nimport datetime\nimport cmd\nimport json\nfrom pprint import pprint\n\ntry:\n f = open('Data.json')\nexcept FileNotFoundError:\n with open('Data.json', 'w') as w:\n json.dump({}, w)\n f = open('Data.json')\nfinally:\n with f:\n database = json.load(f)\n database.setdefault('users', [])\n data = database.setdefault('data', {})\n data.setdefault('command_list', [])\nuser = None\n\n\ndef find_user_name(database, name):\n for user in database['users']:\n if user['name'] == name:\n return user\n return None\n\n\nclass Main(cmd.Cmd):\n prompt = '>>> '\n\n @property\n def user(self):\n return user\n\n @property\n def database(self):\n return database\n\n def do_details(self, arg):\n print('Name: ', self.user['name'])\n print('AccountID: ', self.user['id'])\n print('Nickname: ', self.user['nickname'])\n\n def do_setpas(self, arg):\n self.user['password'] = input('Enter your new password: ')\n\n def do_userlist(self, arg):\n pprint([u['name'] for u in self.database['users']])\n\n def do_message(self, target_user):\n t_user = find_user_name(self.database, target_user)\n if t_user is None:\n return\n\n message = input('Message: ')\n t_user['messages'].append({\n 'from': self.user['name'],\n 'date': str(datetime.datetime.now()),\n 'message': message\n })\n\n def do_mymessages(self, arg):\n pprint(self.user['messages'])\n\n def do_addcommand(self, arg):\n self.database['data']['command_list'].append(arg)\n\n def do_admin(self, arg):\n if not self.user['admin'] and arg == 'True':\n self.user['admin'] = True\n\n def do_delete(self, arg):\n if self.user['admin']:\n return\n\n delete = input('Are you sure you would like to delete your account: ')\n if delete != 'y':\n return\n\n i = self.database.index(self.user)\n self.database.pop(i)\n\n return True\n\n def do_signout(self, arg):\n return True\n\n\ndef signin():\n global user\n\n while True:\n existing_account = input('Do you have an existing account (y/n): ')\n if existing_account == 'y':\n username = input('Username: ')\n user = find_user_name(database, username)\n if user is None:\n print('Invalid username')\n continue\n\n password = input('Password: ')\n if password != user['password']:\n print('Invalid password')\n continue\n\n Main().cmdloop()\n else:\n username = str(input('Username: '))\n while not username:\n username = input(\"You haven't entered anything, try again.\")\n\n user = find_user_name(database, username)\n if user is not None:\n print('That name already exists.')\n user = None\n continue\n\n password = input('Password: ')\n while len(password) < 4:\n print('Your password must be 5 characters long.')\n password = input('Password: ')\n\n nickname = input('Enter your nickname: ')\n id_ = random()\n while id_ in [u['id'] for u in database['users']]:\n id_ = random()\n\n user = {\n 'name': username,\n 'password': password,\n 'nickname': nickname,\n 'id': id_,\n 'messages': [],\n 'admin': False\n }\n database['users'].append(user)\n Main().cmdloop()\n\n\nif __name__ == '__main__':\n try:\n signin()\n finally:\n with open('Data.json', 'w') as f:\n json.dump(database, f)\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>Do you have an existing account (y/n): n\nUsername: Peilonrayz\nPassword: abcde\nEnter your nickname: Peilonrayz\n>>> help\n\nDocumented commands (type help <topic>):\n========================================\nhelp\n\nUndocumented commands:\n======================\naddcommand delete message setpas userlist\nadmin details mymessages signout\n\n>>> details\nName: Peilonrayz\nAccountID: 0.5494927696334424\nNickname: Peilonrayz\n>>> admin\n>>> admin True\n>>> delete\n>>> userlist\n['Peilonrayz']\n>>> signout\nDo you have an existing account (y/n): \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:37:58.760",
"Id": "216069",
"ParentId": "216022",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T22:10:36.823",
"Id": "216022",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"authentication"
],
"Title": "Authentication script in Python"
} | 216022 |
<p>I read the guiding solution to twoSum in leetcodes ; </p>
<blockquote>
<p>Given an array of integers, return <strong>indices</strong> of the two numbers such that they add up to a specific target.</p>
<p>You may assume that each input would have <strong>exactly</strong> one solution, and you may not use the <em>same</em> element twice.</p>
<p><strong>Example:</strong></p>
<pre><code>Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
</code></pre>
<p>Approach 3: One-pass Hash Table<br>
It turns out we can do it in one-pass. While we iterate and inserting elements into the table, we also look back to check if current element's complement already exists in the table. If it exists, we have found a solution and return immediately.</p>
</blockquote>
<p>and mimic a python solution </p>
<pre><code>class Solution:
def twoSum(self, nums, target) -> List[int]:
"""
:type nums: List[int]
:type target: int
"""
nums_d = {}
for i in range(len(nums)):
complement = target - nums[i]
if nums_d.get(complement) != None: #Check None not True Value
return [i, nums_d.get(complement)]
nums_d[nums[i]] = i #produce a map
return []
</code></pre>
<p>Unfortunately, my solution is only faster than 81%, which I thought was a best solution.</p>
<blockquote>
<p>Runtime: 40 ms, faster than 81.00% of Python3 online submissions for Two Sum.
Memory Usage: 14.3 MB, less than 5.08% of Python3 online submissions for Two Sum.
Next challenges:</p>
</blockquote>
<p>How could continue to improve the code, and I am curious about the approaches of the top 20%.</p>
| [] | [
{
"body": "<p>Your code looks like Java. In order to get good at Python, you'll have to give up some of the Java-isms. This code didn't need to be in a class (unless there was some external requirement you didn't show us). A function would have been fine.</p>\n\n<p>Let's start with the iteration. <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">Ned Batchelder</a> gave a talk called <a href=\"https://youtu.be/EnSu9hHGq5o\" rel=\"nofollow noreferrer\"><em>Loop Like a Native</em></a> that contains a lot of great advice for writing looping structures in Python. You should watch that for a lot of pro-tips on basic stuff.</p>\n\n<p>I'm also going to suggest that you either use type annotations, or don't use type annotations. Don't put in some annotations and then leave other type information in the docblock.</p>\n\n<p>So with just those three suggestions, we can change your code to:</p>\n\n<pre><code>def two_sum(array: Sequence[int], target: int) -> List[int]:\n ''' Given an array of integers, return indices of the two numbers such\n that they add up to a specific target.\n '''\n nums_d = {}\n\n for i, val in enumerate(nums):\n ... as before ...\n</code></pre>\n\n<p>Next is your choice of how to check if the complement has been seen before. You are calling the <code>.get()</code> method twice, once for the check and if successful you call it again. This is minor, since you'll only succeed one time. But calling the <code>.get()</code> method and then comparing it will <code>None</code> is more expensive than you may think. Try using the <code>in</code> binary operator instead. And while you're at it, just use <code>dict[key]</code> notation if you know the key is in the dictionary:</p>\n\n<pre><code> for i, val in enumerate(nums):\n complement = target - val\n\n if complement in nums_d:\n return [i, nums_d[complement]]\n\n return []\n</code></pre>\n\n<p>It's hard to predict performance improvements. But I think that \"less is more\", and in this case less opcodes is more fast. Here's what the <a href=\"https://docs.python.org/3/library/dis.html?highlight=dis#dis.dis\" rel=\"nofollow noreferrer\"><code>dis.dis</code></a> output looks like for your original code (starting after the <code>for</code> line):</p>\n\n<pre><code> >> 18 FOR_ITER 56 (to 76)\n 20 STORE_FAST 4 (i)\n\n 10 22 LOAD_FAST 2 (target)\n 24 LOAD_FAST 1 (nums)\n 26 LOAD_FAST 4 (i)\n 28 BINARY_SUBSCR\n 30 BINARY_SUBTRACT\n 32 STORE_FAST 5 (complement)\n\n 12 34 LOAD_FAST 3 (nums_d)\n 36 LOAD_METHOD 2 (get)\n 38 LOAD_FAST 5 (complement)\n 40 CALL_METHOD 1\n 42 LOAD_CONST 1 (None)\n 44 COMPARE_OP 3 (!=)\n 46 POP_JUMP_IF_FALSE 62\n</code></pre>\n\n<p>And here's what the changed code produces:</p>\n\n<pre><code> >> 14 FOR_ITER 44 (to 60)\n 16 UNPACK_SEQUENCE 2\n 18 STORE_FAST 3 (i)\n 20 STORE_FAST 4 (val)\n\n 21 22 LOAD_FAST 1 (target)\n 24 LOAD_FAST 4 (val)\n 26 BINARY_SUBTRACT\n 28 STORE_FAST 5 (complement)\n\n 23 30 LOAD_FAST 5 (complement)\n 32 LOAD_FAST 2 (nums_d)\n 34 COMPARE_OP 6 (in)\n 36 POP_JUMP_IF_FALSE 50\n</code></pre>\n\n<p>The third column (lots of numbers) is byte offset from the start of the code, so you can see the new version takes 6 fewer bytes to run, out of 28 bytes. That's about 21% less.</p>\n\n<p>Does this mean the code will run 21% faster? No. There's lots of other code in there that doesn't change. But it means it probably runs some faster -- you'll have to determine how much.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T01:40:17.463",
"Id": "216030",
"ParentId": "216025",
"Score": "3"
}
},
{
"body": "<ol>\n<li>Don't leave white space at the end of lines.</li>\n<li><a href=\"https://codereview.stackexchange.com/a/215985\">Use <code>enumerate</code></a>.</li>\n<li>When comparing with <code>None</code> use <code>is</code> and <code>is not</code>.</li>\n<li>It'd be cleaner to just use <code>in</code> rather than <code>get</code>.</li>\n<li>If you want to use <code>nums_d.get</code> then you should use it outside the <code>if</code> so you don't have to use it a <em>second</em> time when you enter the <code>if</code>.<br>\nThis however makes the code messy for not much of a benefit IMO.</li>\n<li>Unless the site forces you to return lists returning a tuple would be more Pythonic.</li>\n<li>Your comments aren't helpful, if anything they make the code harder to read for me.</li>\n<li>The variable name <code>nums</code> is easier to read then <code>nums_d</code>, the <code>_d</code> is useless.</li>\n<li><p>When returning it would be better to either:</p>\n\n<ul>\n<li>Raise an exception, as the lookup failed.</li>\n<li>Return a tuple where both values are <code>None</code>. This is so you can tuple unpack without errors.</li>\n</ul></li>\n</ol>\n\n<p>Getting the code:</p>\n\n<pre><code>def test_peil(nums: List[int], target: int) -> Tuple[int, ...]:\n lookup = {}\n for i, v in enumerate(nums):\n if target - v in lookup:\n return i, lookup[target - v]\n lookup[v] = i\n raise ValueError('Two sums target not in list.')\n</code></pre>\n\n<p>You can further improve performance <a href=\"https://codereview.stackexchange.com/a/216057\">by including Alain T.'s change for small numbers.</a></p>\n\n<pre><code>def test_peil_alain(nums: List[int], target: int) -> Tuple[int, ...]:\n if len(nums) <= 100:\n for i, n in enumerate(nums):\n if target - n in nums:\n return i, nums.index(target - n)\n else:\n lookup = {}\n for i, v in enumerate(nums):\n if target - v in lookup:\n return i, lookup[target - v]\n lookup[v] = i\n raise ValueError('Two sums target not in list.')\n</code></pre>\n\n<p>And has a performance improvement: (the graph is volatile due to only using one input sample)</p>\n\n<p><a href=\"https://i.stack.imgur.com/0srBa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0srBa.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T16:23:44.377",
"Id": "418061",
"Score": "0",
"body": "if use ` if target - v in lookup`, is it a O(n) search through the list of lookup.keys()?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T16:28:12.630",
"Id": "418065",
"Score": "0",
"body": "@Alice No it's amortized \\$O(1)\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T00:33:58.693",
"Id": "418112",
"Score": "0",
"body": "amazing, would you mind if I ask for the name of your visual tool to analyze time complexity?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T01:12:27.750",
"Id": "418116",
"Score": "0",
"body": "@JawSaw It's not on PyPI yet. But it's it's on [CR](https://codereview.stackexchange.com/q/215846) and [GitHub](https://github.com/Peilonrayz/graphtimer)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T01:51:45.850",
"Id": "216031",
"ParentId": "216025",
"Score": "4"
}
},
{
"body": "<p>The overhead of creating a dictionary makes the solution less efficient for small lists.</p>\n\n<p>This sequential alternative:</p>\n\n<pre><code>for i,n in enumerate(nums):\n if target-n in nums:\n return (i,nums.index(target-n))\n</code></pre>\n\n<p>is about twice as fast in the best case scenarios (a small list with a match in the lower indexes) but it will lose out when there are more items in the list.</p>\n\n<p>A more concise way to write the dictionary based approach (which happens to also run faster) would be this:</p>\n\n<pre><code>match = dict()\nfor i,n in enumerate(nums):\n if n in match: return (i,match[n])\n match[target-n] = i\n</code></pre>\n\n<p>You can get further acceleration (for large lists) by filtering on the maximum range of eligible numbers:</p>\n\n<pre><code>maxVal = target-min(nums)\nminVal = target-max(nums)\nmatch = dict()\nfor i,n in enumerate(nums):\n if n < minVal or n > maxVal: continue\n if n in match: return (i,match[n])\n match[target-n] = i\n</code></pre>\n\n<p><em>note that this is going to be data dependent but on average it should provide an improvement</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T16:32:36.817",
"Id": "418067",
"Score": "1",
"body": "Your 'Pythonic' code is the complete opposite of what I'd call 'Pythonic'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T17:04:25.980",
"Id": "418075",
"Score": "0",
"body": "The first part of your answer is correct in `len(nums) < 100`. I've added your code and a merge of both my answer and your answer together. I'm happy to remove my downvote if you fix the second half of your answer. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T14:57:40.467",
"Id": "216057",
"ParentId": "216025",
"Score": "1"
}
},
{
"body": "<p>What I've seen here hits the dict twice per iteration.<br>\nIf I was into this, I guess I'd try to hit the dictionary just once a number:</p>\n\n<p>How about using as a key neither the current number nor its complement, but their absolute difference?<br>\nGetting the index via <code>found = seen.setdefault(diff, value)</code>, you'd still have to check whether </p>\n\n<ol>\n<li><code>found</code> was the current index </li>\n<li>the element at <code>found</code> was the complement and not the current element (special casing <code>target / 2</code>).<br>\n(At second glance, <em>one</em> index for each difference is indeed enough…)</li>\n</ol>\n\n<p>Drawing heavily on solutions presented here (my pythons don't even like annotated function definitions?!):</p>\n\n<pre><code>def two_sum(numbers: Sequence[number], target: number) -> Sequence[int]:\n ''' Given a sequence of numbers,\n return the first pair of indices of two numbers adding up to target.\n '''\n seen = dict() # keys will be absolute differences between value and complement\n\n for i, val in enumerate(numbers):\n complement = target - val\n diff = abs(complement - val)\n found = seen.setdefault(diff, i)\n # print(complement, i, found)\n if found != i:\n if complement == val or numbers[found] != val:\n return found, i\n\n return ()\n</code></pre>\n\n<p>(actually, the results don't always live up to how I read the doc string:<br>\nwhile I hope that it returns the lowest index of the summand found last, I can see it returning the <em>highest</em> (lower) index of the other one. Resolution left…)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:40:10.203",
"Id": "418085",
"Score": "0",
"body": "(Belatedly noticed a [very similar question](https://codereview.stackexchange.com/q/215975) reading `return indices of the two numbers` as *all indices* - bummer.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:19:12.377",
"Id": "216067",
"ParentId": "216025",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216031",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-22T23:20:39.500",
"Id": "216025",
"Score": "3",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x"
],
"Title": "A One-Pass Hash Table Solution to twoSum"
} | 216025 |
<p>In my application of Monte Carlo simulation, the crucial part is to generate a random number from a binomial distribution with parameters n = size and p = 0.5. Here is my current implementation</p>
<pre><code>#include <stdio.h>
#include <stdint.h>
#include <x86intrin.h>
int64_t rbinom(int64_t size) {
if (!size) {
return 0;
}
int64_t result = 0;
while (size >= 64) {
uint64_t random64;
while (!_rdrand64_step(&random64)) {
fprintf(stderr, "HW_RND_GEN not ready\n");
}
result += _popcnt64(random64);
size -= 64;
}
uint64_t random64;
while (!_rdrand64_step(&random64)) {
fprintf(stderr, "HW_RND_GEN not ready\n");
}
result += _popcnt64(random64 & ~(UINT64_MAX << size));
return result;
}
</code></pre>
<p>However, the result of benchmarking terrifies me:</p>
<p><a href="https://i.stack.imgur.com/ACl30.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ACl30.png" alt="enter image description here"></a></p>
<p>I'm spending 99.68% of the runtime on this function! How can I optimize it?</p>
<p>The result doesn't need to be cryptographically secure, as long as it's good enough for Monte Carlo simulations.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T01:28:23.467",
"Id": "417994",
"Score": "0",
"body": "What is the value of `size` typically? Your function doesn't seem efficient for large values of `size` because it requires generating `size/64` random numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T01:30:32.383",
"Id": "417995",
"Score": "0",
"body": "@JS1 It could be very large! Like millions. Generating 64 random bits in a batch doesn’t help a lot in that case."
}
] | [
{
"body": "<p>The RDRAND instruction generated from the <code>_rdrand64_step</code> intrinsic is actually very slow, though high quality (modulo some concerns about back doors). Depending on the processor it may take hundreds (Ivy Bridge through Skylake) or even <em>thousands</em> (Intel Atom, AMD) of cycles per RDRAND. So just replacing the random number generator will help a lot.</p>\n\n<p>For example, xoroshiro128+ is a relatively fast PRNG, it has <a href=\"https://lemire.me/blog/2017/08/22/cracking-random-number-generators-xoroshiro128/\" rel=\"nofollow noreferrer\">some weaknesses</a> but they don't seem too bad for this purpose. An interesting aspect is that it contains no operation that must go to execution port 1 on Intel processors, so its operations do not \"fight\" the <code>popcnt</code> much, in contrast to PRNGs that contain multiplication.</p>\n\n<p>So overall, something like this:</p>\n\n<pre><code>static inline uint64_t rotl(const uint64_t x, int k) {\n return (x << k) | (x >> (64 - k));\n}\n\n\nstatic uint64_t s[2];\n\nuint64_t next(void) {\n const uint64_t s0 = s[0];\n uint64_t s1 = s[1];\n const uint64_t result = s0 + s1;\n\n s1 ^= s0;\n s[0] = rotl(s0, 24) ^ s1 ^ (s1 << 16); // a, b\n s[1] = rotl(s1, 37); // c\n\n return result;\n}\n\nint64_t rbinom(int64_t size) {\n if (!size) {\n return 0;\n }\n\n int64_t result = 0;\n while (size >= 64) {\n result += _popcnt64(next());\n size -= 64;\n }\n\n result += _popcnt64(next() & ~(UINT64_MAX << size));\n\n return result;\n}\n</code></pre>\n\n<p>Elsewhere in the application, the state <code>s</code> must be seeded with a non-zero random-enough number. For example, you could use <code>_rdrand64_step</code> to seed it once, at the start of the application.</p>\n\n<hr>\n\n<p>But different strategies are possible. With a <code>size</code> in the thousands or even millions (as indicated in the comments), SIMD could be used both to generate pseudo-random bits and to accumulate the pop-counts. Using some techniques from <a href=\"https://arxiv.org/pdf/1611.07612.pdf\" rel=\"nofollow noreferrer\">Faster Population Counts Using AVX2 Instructions</a> (mainly, reducing the amount of actual pop-counting by using carry-save addition) and Xorshift+ as PRNG (I avoid rotate because AVX2 does not have them built in, and multiplication because AVX2 also has no 64bit integer multiply built in), it could look like this:</p>\n\n<pre><code>__m256i bigstate0, bigstate1;\n\n__m256i xorshift128plus_avx2(__m256i *state0, __m256i *state1)\n{\n __m256i s1 = *state0;\n const __m256i s0 = *state1;\n *state0 = s0;\n s1 = _mm256_xor_si256(s1, _mm256_slli_epi64(s1, 23));\n *state1 = _mm256_xor_si256(_mm256_xor_si256(_mm256_xor_si256(s1, s0),\n _mm256_srli_epi64(s1, 18)),\n _mm256_srli_epi64(s0, 5));\n return _mm256_add_epi64(*state1, s0);\n}\n\n__m256i popcnt_AVX2(__m256i x) {\n const __m256i popcntLUT = _mm256_setr_epi8(\n 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,\n 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4\n );\n const __m256i nibmask = _mm256_set1_epi8(15);\n const __m256i zero = _mm256_setzero_si256();\n\n __m256i L = _mm256_shuffle_epi8(popcntLUT, _mm256_and_si256(x, nibmask));\n x = _mm256_srli_epi16(x, 4);\n __m256i H = _mm256_shuffle_epi8(popcntLUT, _mm256_and_si256(x, nibmask));\n return _mm256_sad_epu8(_mm256_add_epi8(L, H), zero);\n}\n\n__m256i CSA(__m256i a, __m256i b, __m256i c, __m256i *carry) {\n __m256i t0 = _mm256_xor_si256(a, b);\n __m256i t1 = _mm256_xor_si256(t0, c);\n *carry = _mm256_or_si256(_mm256_and_si256(a, b), _mm256_and_si256(t0, c));\n return t1;\n}\n\nint64_t rbinom_AVX2(int64_t size) {\n if (!size) {\n return 0;\n }\n\n int64_t result = 0;\n\n __m256i sum1 = _mm256_setzero_si256();\n __m256i sum2 = sum1;\n __m256i sum4 = sum1;\n __m256i sum = sum1;\n while (size >= 2048) {\n __m256i sample0 = xorshift128plus_avx2(&bigstate0, &bigstate1);\n __m256i sample1 = xorshift128plus_avx2(&bigstate0, &bigstate1);\n __m256i sample2 = xorshift128plus_avx2(&bigstate0, &bigstate1);\n __m256i sample3 = xorshift128plus_avx2(&bigstate0, &bigstate1);\n __m256i sample4 = xorshift128plus_avx2(&bigstate0, &bigstate1);\n __m256i sample5 = xorshift128plus_avx2(&bigstate0, &bigstate1);\n __m256i sample6 = xorshift128plus_avx2(&bigstate0, &bigstate1);\n __m256i sample7 = xorshift128plus_avx2(&bigstate0, &bigstate1);\n // reduce weight 1\n __m256i c0, c1, c2, c3;\n __m256i t0 = CSA(sample0, sample1, sample2, &c0);\n __m256i t1 = CSA(sample3, sample4, sample5, &c1);\n __m256i t2 = CSA(sample6, sample7, sum1, &c2);\n sum1 = CSA(t0, t1, t2, &c3);\n // reduce weight 2\n __m256i c4, c5;\n __m256i t3 = CSA(c0, c1, c2, &c4);\n sum2 = CSA(c3, t3, sum2, &c5);\n // reduce weight 4\n __m256i c6;\n sum4 = CSA(sum4, c4, c5, &c6);\n sum = _mm256_add_epi64(sum, _mm256_slli_epi64(popcnt_AVX2(c6), 3));\n size -= 2048;\n }\n sum1 = popcnt_AVX2(sum1);\n sum2 = popcnt_AVX2(sum2);\n sum4 = popcnt_AVX2(sum4);\n sum = _mm256_add_epi64(sum, sum1);\n sum = _mm256_add_epi64(sum, _mm256_slli_epi64(sum2, 1));\n sum = _mm256_add_epi64(sum, _mm256_slli_epi64(sum4, 2));\n result += _mm256_extract_epi64(sum, 0);\n result += _mm256_extract_epi64(sum, 1);\n result += _mm256_extract_epi64(sum, 2);\n result += _mm256_extract_epi64(sum, 3);\n\n while (size >= 64) {\n result += _mm_popcnt_u64(next());\n size -= 64;\n }\n\n result += _mm_popcnt_u64(next() & ~(UINT64_MAX << size));\n\n return result;\n}\n</code></pre>\n\n<hr>\n\n<p>Algorithmic tricks such as the <a href=\"https://en.wikipedia.org/wiki/Alias_method\" rel=\"nofollow noreferrer\">alias method</a> may be appropriate. I have no experience with this so I cannot explain it or even really recommend it, but it's something to look into.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T13:53:49.147",
"Id": "418039",
"Score": "0",
"body": "Thanks! Is it OK to seed `bigstate0` and `bigstate1` with `arc4random`, or do I must seed all static buffers with the same RNG, i.e. `_rdrand64_step`? I find using `_rdrand64_step` a little troublesome, due to those error-checking parts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T14:33:15.650",
"Id": "418042",
"Score": "0",
"body": "@nalzok `arc4random` should be OK too"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T14:37:54.690",
"Id": "418044",
"Score": "0",
"body": "Cool! Another quirky point is I thought I could replace `rtol` with [`_rtol64`](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#techs=Other&text=rotl64), but surprisingly it doesn't compile on my machine (Core i5), which supports AVX2. I guess I would stay with `rtol` until I figure out how to write inline assembly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T14:40:24.443",
"Id": "418045",
"Score": "1",
"body": "@nalzok it should be fine like this too, many compilers (eg GCC, Clang, MSVC) recognize that that function does a rotate and translate it into one instruction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T14:48:03.853",
"Id": "418047",
"Score": "0",
"body": "Thanks again and I have yet another question: you didn't use AVX512, is it because doing so would require more complicated coding compared to the AVX2 version? Or because the performance gain won't be very significant? Or because some operations are not supported for `__mm512i` yet so it's impossible to implement one at this point? I'm considering bringing the power of AVX512 to it if that's possible and worth the time..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T14:53:02.463",
"Id": "418049",
"Score": "1",
"body": "@nalzok it would be better, for more reasons than just wider vectors. For example, the CSA function can use `_mm512_ternarylogic_epi32` to save some operations. Also future processors will have `_mm512_popcnt_epi64` which is obviously great for this. I didn't use it because support for it is still uncommon, but if your processor has it then go for it."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T08:03:26.287",
"Id": "216039",
"ParentId": "216028",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T00:18:08.493",
"Id": "216028",
"Score": "3",
"Tags": [
"performance",
"c",
"random",
"statistics",
"x86"
],
"Title": "Generating random number from a binomial distribution"
} | 216028 |
<p>I have a distributed application (YARN), which runs a WebApp.</p>
<p>This application use a default port to start (8008), before I start I need to check if port is in use.</p>
<p>A container may run in the same virtual machine, hence port may be in use.
(Max I have 4 containers in WebApp).</p>
<p>I created the following code which seem to work, but want to see if there are some clean ups/improvements suggested.</p>
<pre><code>def port_in_use(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1', port))
if result == 0:
return True
else:
return False
def start_dashboard():
base_port = os.getenv('DASHBOARD_PORT_ENV_VAR', 8008)
scan_ports = True
attempts = 0
max_attempts = 10
while(scan_ports and attempts <= max_attempts):
if port_in_use(base_port):
base_port += 1
attempts += 1
else:
scan_ports = False
if attempts == max_attempts:
raise IOError('Port in use')
dashboard.configure(port=base_port)
dashboard.launch()
</code></pre>
| [] | [
{
"body": "<p>Your code has some incorrect assumptions.</p>\n\n<ul>\n<li><p>an application may listen on a specific address/port combination; <code>127.0.0.1:port</code> can be available while <code>*:port</code> is not.</p></li>\n<li><p>an application may bind a port without listening. Connects will fail, but so will your own bind.</p></li>\n<li><p>a firewall or other mechanism can interfere with connections, generating false positives in your scan.</p></li>\n</ul>\n\n<p>The reliable approach is to bind the port, just as your dashboard will, and then release it.</p>\n\n<pre><code>result = sock.bind(('', port))\nsock.close()\n</code></pre>\n\n<hr>\n\n<p>You'll need to catch the exception and this is a good opportunity to move the whole thing into a function. That will make the <code>start_dashboard</code> logic cleaner and get rid of boolean loop-terminator <code>scan_ports</code>. Just exit the loop by <code>return</code>ing the answer.</p>\n\n<pre><code>def next_free_port( port=1024, max_port=65535 ):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n while port <= max_port:\n try:\n sock.bind(('', port))\n sock.close()\n return port\n except OSError:\n port += 1\n raise IOError('no free ports')\n\ndef start_dashboard():\n\n # pass optional second parameter \"max_port\" here, else scan until a free one is found\n port = next_free_port( os.getenv('DASHBOARD_PORT_ENV_VAR', 8008) )\n\n dashboard.configure(port=port)\n dashboard.launch()\n</code></pre>\n\n<p>You can use netcat to make ports in-use for testing: <code>nc -l -p 9999</code> will listen on port 9999; press control-C to end it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T17:42:42.637",
"Id": "418077",
"Score": "0",
"body": "Thank you for the answer, check is local, so no firewall in place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T19:06:22.893",
"Id": "418088",
"Score": "0",
"body": "I mean a host firewall, like iptables on Linux."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T01:53:04.630",
"Id": "418118",
"Score": "0",
"body": "Sounds good, any recommendation for Python style? Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T01:59:52.317",
"Id": "418119",
"Score": "0",
"body": "Using .bind I get: >>> port_in_use(22) if port is in use, which may just require to handle the OS exception.\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 3, in port_in_use\nOSError: [Errno 98] Address already in use"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T06:37:55.673",
"Id": "418126",
"Score": "1",
"body": "the code can be a little shorter and clearer; see edits for a fleshed-out example."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T08:49:22.450",
"Id": "216042",
"ParentId": "216037",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "216042",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T07:09:53.037",
"Id": "216037",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"networking",
"socket"
],
"Title": "Python scanner for the first free port in a range"
} | 216037 |
<p>I've been doing a task for an interview that I will have soon.
The requirement is to code the following problem in C#.</p>
<blockquote>
<p>Write a program (and prove that it works) that: Given a text file, count the occurrence of each unique word in the file.
For example; a file containing the string “Go do that thing that you do so well” should find these counts:
1: Go
2: do
2: that
1: thing
1: you
1: so
1: well</p>
</blockquote>
<p>I coded my solution and it's working fine for the tests I gave.</p>
<p>I'm looking for any ways that I can improve my code and to get feedback on the solution. Is there's any way I could to the problem more efficiently.</p>
<p>Thank you in advance.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace CountOccurrence
{
class Program
{
static void Main(string[] args)
{
string text = System.IO.File.ReadAllText(@"F:\Ex\Myfile.txt"); // User ReadAllText to copy the file's text into a string
string textToLower = text.ToLower(); // Converts the string to lower case string
Regex reg_exp = new Regex("[^a-z0-9]"); // Regular expressions to replace non-letter and non-number characters with spaces. It uses the pattern [^a-z0-9].The a-z0-9 part means any lowercase letter or a digit.
textToLower = reg_exp.Replace(textToLower, " "); // The code uses the Regex object’s Replace method to replace the characters that match the pattern with a space character.
string[] Value = textToLower.Split(new char[] {' '},
StringSplitOptions.RemoveEmptyEntries); // Split the string and remove the empty entries
Dictionary<string, int> CountTheOccurrences = new Dictionary<string, int>(); // Create a dictionary to keep track of each occurrence of the words in the string
for (int i = 0; i < Value.Length; i++) // Loop the splited string
{
if (CountTheOccurrences.ContainsKey(Value[i])) // Check if word is already in dictionary update the count
{
int value = CountTheOccurrences[Value[i]];
CountTheOccurrences[Value[i]] = value + 1;
}
else // If we found the same word we just increase the count in the dictionary
{
CountTheOccurrences.Add(Value[i], 1);
}
}
Console.WriteLine("The number of counts for each words are:");
foreach (KeyValuePair<string, int> kvp in CountTheOccurrences)
{
Console.WriteLine("Counts: " + kvp.Value + " for " + kvp.Key); // Print the number of counts for each word
}
Console.ReadKey();
}
}
}
</code></pre>
| [] | [
{
"body": "<h2>Efficiency</h2>\n\n<p>I won't say much about efficiency - because without a clear use-case it will be hard to know whether possible changes would be worth the effort - but my main concern would be fact that you force a whole file into a string, of which you immediately produce a second copy. It would be nice to see a version which takes a stream of some description rather than a whole file, as this could (in theory) cope with very large files (ones which can't fit in memory), could have much better memory characteristics, and with a bit of effort could start processing the file before it has read the whole thing, so that you are not stalled waiting for the whole file before you can begin (though an asynchronous implementation would be necessary to fully exploit such possibilities).</p>\n\n<h2>API</h2>\n\n<p>Don't hard-code the input file-name. Put this code in a nicely packaged method, and take the input as a parameter. This parameter could be a file-name, but it could also be a <code>Stream</code> or <code>String</code> (if you intend to always read the whole thing at the start) or whatever; you can always provide a convenience method to cover important use-cases.</p>\n\n<p>And don't print the output to the console: if the calling code wants to print the counts to the console, let it do that, but give it the information it needs to do what it wants, rather than deciding what to do with the information for it. Returning the dictionary (perhaps as an <code>IDictionary</code>, so that you aren't coupled to the particular class) produces a much more useful interface.</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>IDictionary<string, int> CountWordOccurances(string text);\n</code></pre>\n\n<p>If your specification says that you <em>must</em> be printing these counds to the console, then you can write a method to print out the dictionary (perhaps to an arbitrary <code>TextWriter</code>, rather than only <code>Console.WriteLine</code>, which is no fun to test against), and write another method which composes the two.</p>\n\n<h2>Comments</h2>\n\n<p>Comments should be useful, explaining why code is doing what it is doing or providing some important context. <code>// Converts the string to lower case string</code> says nothing which <code>text.Tolower()</code> doesn't already, and is liable to rot as the method is modified. <code>The code uses the Regex object’s Replace method to replace the characters that match the pattern with a space character.</code> is far too wordy, and just states what the code is doing, without any indication as to why it might be doing that. We can <em>see</em> that it uses a Regex object, and we can <em>see</em> that that is uses the replace method, and we can <em>see</em> that it replaces matches with a <code>\" \"</code>: none of this needs clarifying.</p>\n\n<h2>Variables</h2>\n\n<p>I'm not terribly fond of your variable naming. They don't escape the method, so it doesn't really matter what style you use (though everyone uses lowerCamelCase, see the <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"noreferrer\">Microsoft Naming Guidelines</a>), but you must be consistent. <code>Value</code> -> <code>value</code> (or <code>values</code>, since it is a collection). <code>CountTheOccurances</code> is not a great name; <code>counts</code> or <code>wordCounts</code> would scan much better. <code>reg_exp</code> encodes no information beyond that which is clear from the type. Something like <code>letterFilter</code> might be better.</p>\n\n<p>I'd be inclined to ditch <code>textToLower</code>, and just replace <code>text</code>: it's so easy to use the <em>old</em> variable accidentally when they have such similar names. If you wanted the separation to be clear, you could put the reading of the text and to-lowering in a different scope (or even method), so that only <code>textToLower</code> appears for the rest of the method; however, you've already confused matters by re-using <code>textToLower</code> as <code>textToLowerAfterRegex</code>.</p>\n\n<h2>Splitting</h2>\n\n<p>Your regex bit doesn't really make sense; you are replacing every character that doesn't map to a lower-case latin letter or arabic numeral with a space: where is the specification which tells you what counts as a word or not? I'll leave someone who knows more about unicode to comment on how you should do this sort of thing properly, but your code is deficient, not least because it will cut \"naïve\" into \"na\" and \"ve\".</p>\n\n<p>You can use <code>Regex.Split</code> instead of performing a replacement and then splitting, and use something like <code>\\p{L}</code> to cover a wider variety of letters (just for example). A LINQ where can then be used to filter out empty entries.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Regex nonLetters = new Regex(@\"[^\\p{L}]\");\nreturn nonLetters.Split(text).Where(s => s.Length > 0);\n</code></pre>\n\n<p>A more efficient alternative might be to use a regex which matches words, and return captures instead of splitting; however, again, if performance is a concern, then you need to benchmark under realistic conditions.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>Regex wordMatcher = new Regex(@\"\\p{L}+\");\nreturn wordMatcher.Matches(text).Select(c => c.Value);\n</code></pre>\n\n<p>I'd be strongly inclined to separate this 'extracting words' bit from the 'counting words' bit, and to avoid <code>ToLower</code>ing at this point. Indeed, rather than using <code>ToLower()</code> to group words, consider supplying the dictionary a case-insensitive string comparer such as <code>StringComparer.CurrentCultureIgnoreCase</code>.</p>\n\n<h2>Counting</h2>\n\n<p>Though there is merit in using a separate <code>ContainsKey</code> call and <code>[key]</code> lookup, it's more efficient and a bit tidier to use <code>TryGetValue</code>. Here are 2 obvious ways of using it.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>if (CountTheOccurrences.TryGetValue(value[i], out int count))\n{\n CountTheOccurrences[value[i]] = count + 1;\n}\nelse\n{\n CountTheOccurrences.Add(value[i], 1);\n}\n\n// or\n\nint count;\nif (!CountTheOccurrences.TryGetValue(value[i], out count))\n{\n Count = 0;\n}\nCountTheOccurrences[value[i]] = count + 1;\n</code></pre>\n\n<p>Personally I prefer the second one (<code>count</code> doesn't leak if not-found), but the first is closer to what you already have.</p>\n\n<p>Another option is to ditch the loop completely, and use a LINQ <code>GroupBy</code> call, reducing the code complexity alot. In the code below, I write a custom general-purpose <code>CountOccurances</code> method, which could be reused for other purposes, and makes the intention of the code plain without compromising on performance (<code>GroupBy</code> would introduce significant overheads).</p>\n\n<h2>Example Rewrite</h2>\n\n<p>The below incorporates most of the ideas above, with a couple of other adjustments. The separation of concerns is maybe a little excessive, but while the number of lines of code seems to have increased, essentially all the complexity is hidden away in the completely generic (and potentially widely reusable (I wish LINQ had it already)) <code>CountOccurrences</code> method; the other methods are trivial, but none-the-less encapsulate domain information behind a nice API.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>/// <summary>\n/// Convenience method which prints the number of occurrences of each word in the given file\n/// </summary>\npublic static void PrintWordCountsInFile(string fileName)\n{\n var text = System.IO.File.ReadAllText(fileName);\n var words = SplitWords(text);\n var counts = CountWordOccurrences(words);\n WriteWordCounts(counts, System.Console.Out);\n}\n\n/// <summary>\n/// Splits the given text into individual words, stripping punctuation\n/// A word is defined by the regex @\"\\p{L}+\"\n/// </summary>\npublic static IEnumerable<string> SplitWords(string text)\n{\n Regex wordMatcher = new Regex(@\"\\p{L}+\");\n return wordMatcher.Matches(text).Select(c => c.Value);\n}\n\n/// <summary>\n/// Counts the number of occurrences of each word in the given enumerable\n/// </summary>\npublic static IDictionary<string, int> CountWordOccurrences(IEnumerable<string> words)\n{\n return CountOccurrences(words, StringComparer.CurrentCultureIgnoreCase);\n}\n\n/// <summary>\n/// Prints word-counts to the given TextWriter\n/// </summary>\npublic static void WriteWordCounts(IDictionary<string, int> counts, TextWriter writer)\n{\n writer.WriteLine(\"The number of counts for each words are:\");\n foreach (KeyValuePair<string, int> kvp in counts)\n {\n writer.WriteLine(\"Counts: \" + kvp.Value + \" for \" + kvp.Key.ToLower()); // print word in lower-case for consistency\n }\n}\n\n/// <summary>\n/// Counts the number of occurrences of each distinct item\n/// </summary>\npublic static IDictionary<T, int> CountOccurrences<T>(IEnumerable<T> items, IEqualityComparer<T> comparer)\n{\n var counts = new Dictionary<T, int>(comparer);\n\n foreach (T t in items)\n {\n int count;\n if (!counts.TryGetValue(t, out count))\n {\n count = 0;\n }\n counts[t] = count + 1;\n }\n\n return counts;\n}\n</code></pre>\n\n<p>Note that every method has inline-documentation, which describes its job (though I'll grant the summaries are not very good; with a proper spec be able to writer better APIs with better documentation).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T13:46:21.190",
"Id": "418038",
"Score": "5",
"body": "First I want to thank you very much for taking the time to explain to me and write me the feedback. I can see clearly now what I was doing wrong and I gained a lot by reading carefully through your explanation. I must say that I'm at the beginning of my programming career and I have still a lot to learn and improve. But I will try my best to improve my code every time. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T13:15:51.293",
"Id": "216051",
"ParentId": "216046",
"Score": "17"
}
},
{
"body": "<p>Just a few things to add to VisualMelons answer:</p>\n\n<p>Instead of a <code>for</code> loop, you can use a <code>foreach</code> loop:</p>\n\n<pre><code> foreach (string word in Value)\n {\n ...\n</code></pre>\n\n<hr>\n\n<p>Using <code>Dictionary<string,int>.TryGetValue</code>:</p>\n\n<p>The <code>out int count</code> value defaults to <code>0</code> if the word is not present in the dictionary, so it's valid to write:</p>\n\n<pre><code> foreach (string word in Value)\n {\n CountTheOccurrences.TryGetValue(word, out int count);\n CountTheOccurrences[word] = count + 1;\n }\n</code></pre>\n\n<p>You don't have to check the returned value from <code>TryGetValue()</code> and you can add a new entry via the indexer.</p>\n\n<hr>\n\n<p>You have to consider what a word is:</p>\n\n<p>The English term: \"doesn't\", how would you count that: as one word or as \"doesn\" + \"t\" (or even \"does\" + \"not\")? I'm not expert in English, but I would consider it to be one word, because neither \"doesn\" nor \"t\" can be counted for as words in grammatical sense. (The word counter in Microsoft Word counts \"doesn't\" and other contractions as one word). You can take that into account by extending VisualMelons regex pattern a little bit:</p>\n\n<pre><code>public static IEnumerable<string> SplitWords(string text)\n{\n Regex wordMatcher = new Regex(@\"[\\p{L}']+\");\n return wordMatcher.Matches(text).Cast<Match>().Select(c => c.Value);\n}\n</code></pre>\n\n<p>Here the pattern is extended with <code>[]</code> and a <code>'</code>.</p>\n\n<p>Alternatively you can use the <code>\\b</code> anchor, which matches boundaries between alpha-numeric and non-alpha-numeric chars:</p>\n\n<pre><code>@\"\\b[\\w']+\\b\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T21:07:33.143",
"Id": "418095",
"Score": "1",
"body": "Wow, I don't think I've never noticed possible usage of `TryGetValue`... that or I just didn't like it (I prefer not to depend on that sort of detail) +1 as usual ;)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T19:06:45.853",
"Id": "216073",
"ParentId": "216046",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "216051",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T09:55:51.597",
"Id": "216046",
"Score": "13",
"Tags": [
"c#",
"performance",
"interview-questions",
"hash-map"
],
"Title": "Count the occurrence of each unique word in the file"
} | 216046 |
<p>I have a function which contains two switches, which check for Command Code and Response Code after that updating UI elements. The code is working fine.</p>
<p>How I can reduce or improve those switch cases?</p>
<pre><code>private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
byte[] buffer = new byte[serialPort.BytesToRead];
serialPort.Read(buffer, 0, buffer.Length);
if (buffer.Length > 1)
{
#region FRAME VALIDATOR
FrameResponseValidator frameResponseValidator = new FrameResponseValidator();
bool isFrameValid = frameResponseValidator.ValidateFrame(buffer);
#endregion FRAME VALIDATOR
if (isFrameValid)
{
int commandCode = buffer[1];
int responesCode = 0;
switch (commandCode)
{
case Constants.HANDSHAKE_COMMAND_CODE:
responesCode = buffer[3];
_counter++;
break;
case Constants.ERASE_COMMAND_CODE:
responesCode = buffer[2];
_counter++;
break;
case Constants.NO_OF_PACKET_COMMAND_CODE:
responesCode = buffer[2];
_counter++;
break;
case Constants.WRITE_COMMAND_CODE:
responesCode = buffer[2];
_counter++;
break;
case Constants.DATA_COMMAND_CODE:
responesCode = buffer[2];
_counter++;
break;
case Constants.VERIFY_COMMAND_CODE:
responesCode = buffer[2];
_counter++;
break;
case Constants.CHECKSUM_COMMAND_CODE:
responesCode = buffer[2];
_counter++;
break;
case Constants.READ_VERSION_COMMAND_CODE:
this.DisplayCurrentVersion(buffer);
responesCode = buffer[1];
_counter++;
break;
case Constants.CONNECTION_ALIVE:
responesCode = buffer[1];
break;
default:
break;
}
switch (responesCode)
{
case Constants.HANDSHAKE_AND_WRITE_ACK_SUCCESS:
if (_counter == 1)
{
timer.Stop();
connectionTimer.Start();
this.Dispatcher.Invoke(() =>
{
lblConnectionStatus.Content = "Connected";
lblConnectionStatus.Background = Brushes.Green;
});
}
else if (_counter == 4)
{
_noOfPackets = packetList.Count;
this.PacketToSendInfoCommand(_noOfPackets);
}
// For Temp Purpose {Will be refactored as per new protocol}
else if (_counter == _noOfPackets + 7)
{
VerifyCommandWithCheckSum(_totalCheckSum);
}
else if (_counter != 1 || _counter != 4)
{
// Check the isFileSelected if the file is selected
if (isFileSelected && _packetCounter != packetList.Count)
{
this.Dispatcher.Invoke(() =>
{
double percentage = Math.Round(((double)_packetCounter / _noOfPackets) * 100);
lblStatus.Content = "Writing data... " + _packetCounter + "/" + _noOfPackets + " & Perce: " + percentage + "%";
pbProcess.Value = percentage;
});
//Thread.Sleep(10);
this.SendPacket(packetList[_packetCounter]);
}
else
{
isFileSelected = false;
}
}
break;
case Constants.ERASE_SUCCESS:
this.Dispatcher.Invoke(() =>
{
pbProcess.Value = 50;
lblStatus.Content = "Erase successfull!";
});
this.AllowToWriteCommand();
break;
case Constants.PACKET_WRITE_SUCCESS:
this.Dispatcher.Invoke(() =>
{
pbProcess.Value = 70;
lblStatus.Content = "Write Successfull!";
});
this.VerifyCommand();
this.Dispatcher.Invoke(() =>
{
pbProcess.Value = 90;
lblStatus.Content = "Verfiying...";
});
break;
case Constants.VERIFY_FAILED:
MessageBox.Show("Final checksum verification failed! Try again");
this.Dispatcher.Invoke(() =>
{
pbProcess.Value = 0;
lblStatus.Content = "Execution aborted! Try again";
});
break;
case Constants.VERIFY_SUCCESS:
this.Dispatcher.Invoke(() =>
{
pbProcess.Value = 100;
lblStatus.Content = "Verify Success!";
MessageBox.Show("Verify Successs!");
});
DisposePort();
break;
case Constants.PACKET_FAILED_RESPONSE:
MessageBox.Show("Failed to write a frame!");
this.SendPacket(packetList[_packetCounter]);
break;
case Constants.READ_VERSION_SUCCESS:
break;
case Constants.CONNECTION_ALIVE:
// this will be refactor later
connectionTimer.Interval = 70000;
break;
default:
MessageBox.Show("Unknown response!");
break;
}
}
else
{
var sdsds = buffer;
MessageBox.Show("Invalid Response");
}
}
}
catch (Exception ex)
{
ExceptionHandler exceptionHandler = new ExceptionHandler();
exceptionHandler.HandleException(ex);
}
}
</code></pre>
| [] | [
{
"body": "<h2>Fall through switch cases</h2>\n<ul>\n<li><p>Identical case blocks. You can have many clauses fall through to the same block. <code>/* Example A * /</code></p>\n</li>\n<li><p>Share code in similar cases. You can have two blocks with the first falling through to the next via <code>goto case</code> , thus share some of the code. <code>/* Example B * /</code></p>\n</li>\n<li><p>The default clause means the code is 0, I dont know if that is in <code>Constants</code> but it feels like it might fall through to the default in the second switch where you show an error. <code>/* Example C */</code></p>\n</li>\n</ul>\n<p>eg Note the two possible exceptions</p>\n<pre><code>int responesCode = 0;\nswitch (buffer[1]) {\n case Constants.HANDSHAKE_COMMAND_CODE:\n responesCode = buffer[3]; // could be IndexOutOfRangeException\n _counter++;\n break;\n case Constants.ERASE_COMMAND_CODE: /* Example A */\n case Constants.NO_OF_PACKET_COMMAND_CODE:\n case Constants.WRITE_COMMAND_CODE:\n case Constants.DATA_COMMAND_CODE:\n case Constants.VERIFY_COMMAND_CODE:\n case Constants.CHECKSUM_COMMAND_CODE:\n responesCode = buffer[2]; // could be IndexOutOfRangeException\n _counter++;\n break;\n case Constants.READ_VERSION_COMMAND_CODE: \n this.DisplayCurrentVersion(buffer);\n _counter++;\n goto case Constants.CONNECTION_ALIVE; /* Example B */\n case Constants.CONNECTION_ALIVE: /* Example B */\n responesCode = buffer[1]; \n break;\n default:\n MessageBox.Show("Unknown response!"); /* Example C */\n return;\n}\n</code></pre>\n<hr />\n<h2>Code complexity.</h2>\n<p>Try to keep complexity down where possible.</p>\n<p>Examples</p>\n<hr />\n<ol>\n<li>There is no need to cast to a <code>double</code> then call <code>Math.Round</code> (BTW rounding will show 100% before it is 100%) in the percentage calculation (Assuming <code>pbProcess.value</code> is an <code>int</code>) The value is floored in integer calculations so you only get 100% when it is 100%</li>\n</ol>\n<p>You have something like</p>\n<pre><code>double percentage = Math.Round(((double)_packetCounter / _noOfPackets) * 100);\nlblStatus.Content = "Writing data... " + percentage + "%";\npbProcess.value = percentage;\n</code></pre>\n<p>Can be</p>\n<pre><code>pbProcess.value = _packetCounter * 100 / _noOfPackets; // Could be div by zero????\nlblStatus.Content = "Writing data... " + pbProcess.value + "%";\n</code></pre>\n<hr />\n<ol start=\"2\">\n<li>In the second switch in the first clause the last <code>else</code> has a redundant <code>if</code> statement. The conditions have already been meet.</li>\n</ol>\n<p>eg.</p>\n<pre><code>} else if (_counter != 1 || _counter != 4) {\n\n// should be just the else\n} else {\n</code></pre>\n<hr />\n<h2>Poor error handling</h2>\n<p>You have two points that look like errors where you invoke the <code>messageBox</code> for <code>"Unknown response!"</code>, and <code>"Invalid response!"</code> and just continue execution.</p>\n<p>You also have generic catch. It looks like a cover all solution and that you are unsure as to the range of possible errors. You are using the catch to cover poor quality code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T16:02:03.160",
"Id": "418054",
"Score": "0",
"body": "Thanks! It would be better if you suggest more about second switch case and more about *poor error handling*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T16:23:44.323",
"Id": "418060",
"Score": "1",
"body": "@PrashantPimpale The second switch case is ok. There is not much more I can add regarding the error handling as the source of likely errors are in the various methods you call, it would be bad advice for me to guess. All I can add is...Check each call for all the possible errors, Can you handle the errors in within the call. Can you preempt the errors and avoid them. Are the errors critical (must exit/reset state), Can you avoid needing the try catch altogether. If not consider creating custom errors that are more meaningful within the context of your code. Don't use errors to control flow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T19:39:50.740",
"Id": "418092",
"Score": "2",
"body": "@Blindman67: In C# your Example B for the switch statement is not allowed like it is in C/C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T01:36:19.850",
"Id": "418117",
"Score": "0",
"body": "I was thinking to combine both switch cases into one hence the role of `_counter` will be vanished."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T14:22:17.830",
"Id": "216056",
"ParentId": "216047",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216056",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T10:31:57.770",
"Id": "216047",
"Score": "2",
"Tags": [
"c#",
"serial-port"
],
"Title": "Handling command code and response code in serial port's DataReceived method"
} | 216047 |
<p>I want to create a wrapper class for byte arrays so that I can use them as keys in <code>fastutil</code>'s <a href="http://fastutil.di.unimi.it/docs/it/unimi/dsi/fastutil/objects/Object2LongAVLTreeMap.html" rel="nofollow noreferrer"><code>Object2LongAVLTreeMap</code></a>. I have created a wrapper like this:</p>
<pre><code>(deftype Bytes [^bytes ba]
Comparable
(compareTo
[this other]
(let [m (alength ^bytes (.ba this))
n (alength ^bytes (.ba other))
l (min m n)]
(loop [i 0]
(if (< i l)
(let [a (aget ^bytes (.ba ^Bytes this) i)
b (aget ^bytes (.ba ^Bytes other) i)
d (compare a b)]
(if (zero? d)
(recur (inc i))
d))
(compare m n))))))
</code></pre>
<p>The wrapper needs to implement <code>Comparable</code> for the insertions in the AVL Tree.</p>
<p>I am looking for feedback regarding my overall approach and my implementation of <code>compareTo</code>. I will be inserting lots of entries into the tree so I don't want to be creating unnecessary objects, etc. during the comparison.</p>
<p><strong>EDIT:</strong> I believe the code above has a bug. See my comment below.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T13:44:22.860",
"Id": "418037",
"Score": "0",
"body": "I wouldn't have accepted my answer quite yet. A little over an hour isn't very long for a question to be up on Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T20:22:59.483",
"Id": "418093",
"Score": "0",
"body": "Ah okay. I'll leave it open a little longer. Thanks for point out the reflection issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T20:31:38.507",
"Id": "418094",
"Score": "0",
"body": "Np. Honestly, considering it's outside the loop, the effect will likely be minimal, but it's the only thing I noticed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T13:38:48.907",
"Id": "418154",
"Score": "0",
"body": "I believe the code above has a bug: `(compare a b)` compares two (signed) bytes. For example, if `a` is `(unchecked-byte 0xFF)` and `b` is `(unchecked-byte 0x00))`, it returns `-1` rather than `1`. In my case, this caused the byte arrays to be inserted incorrectly in the AVL tree. A solution is to set `a` to `(bit-and (aget ba i) 0xFF)` and `b` to `(bit-and (aget ^bytes (.ba ^Bytes o) i) 0xFF)`."
}
] | [
{
"body": "<p>First, your calls to <code>.ba</code> aren't being resolved for <code>other</code>, so that's forcing use of reflection. If you run <code>lein check</code>, you'll see:</p>\n\n<pre><code>Reflection warning, thread_test.clj:22:22 - reference to field ba on java.lang.Object can't be resolved.\n</code></pre>\n\n<p>This has the potential to slow the method down, although it only happens once per call, so the effect wouldn't be huge.</p>\n\n<p>Use explicit type hints to ensure it knows what types you're working with, just like you did below that:</p>\n\n<pre><code>(let [m (alength ^bytes (.ba ^Bytes this))\n n (alength ^bytes (.ba ^Bytes other))\n</code></pre>\n\n<p>I tried type hinting the parameters instead, and got an error I've never gotten before. I think it was looking for a <code>compareTo</code> with <code>Object</code> parameters, so saying the parameters were <code>Bytes</code> was throwing it.</p>\n\n<hr>\n\n<p>Other than that, I don't see anything performance related. I'll just point out, in case you don't know, <code>this</code>' <code>ba</code> is actually in scope. You can use it directly which gets rid of some bulk, although makes some of the code less symmetrical:</p>\n\n<pre><code>(deftype Bytes [^bytes ba]\n Comparable\n (compareTo\n [_ other]\n (let [m (alength ba) ; Here\n n (alength ^bytes (.ba ^Bytes other))\n l (min m n)]\n (loop [i 0]\n (if (< i l)\n (let [a (aget ba i) ; And here\n b (aget ^bytes (.ba ^Bytes other) i)\n d (compare a b)]\n (if (zero? d)\n (recur (inc i))\n d))\n (compare m n))))))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T13:18:26.303",
"Id": "216052",
"ParentId": "216050",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216052",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T12:02:59.540",
"Id": "216050",
"Score": "2",
"Tags": [
"sorting",
"clojure",
"wrapper"
],
"Title": "Using deftype to create a wrapper class for byte arrays"
} | 216050 |
<p>Here is my current <code>toggle</code> function:</p>
<pre><code>$scope.toggleSelect = event => {
$scope.selection = event.target.innerHTML;
if ($scope.selection === 'Select All') {
$scope.emailList = $scope.users.filter(user => !user.report.emailed);
} else {
$scope.emailList = $scope.emailList = [];
}
};
</code></pre>
<p>Here are my thoughts and questions about the best practices:</p>
<ol>
<li><p>I make an assignment to <code>$scope.emailList</code> in the if and else statement. Instead of separate assignments, is one assignment better? Refactoring to one assignment will pollute the code with unnecessary variables, but it may make the code more readable?</p>
<pre><code>$scope.toggleSelect = event => {
$scope.selection = event.target.innerHTML;
const emailListUpdate;
if ($scope.selection === 'Select All') {
emailListUpdate = $scope.users.filter(user => !user.report.emailed);
} else {
emailListUpdate = $scope.emailList = [];
}
$scope.emailList = emailListUpdate;
};
</code></pre>
<p>The main benefit I see here is that anybody reading the code can skim to the last line and know the overall purpose. Overall, I don't see this to be a beneficial refactor since I don't think it adds additional readability and potentially makes it harder to follow. I would appreciate thoughts on this.</p></li>
<li><p>Ternary or <code>if/else</code>:</p>
<p>I reviewed a great <a href="https://stackoverflow.com/questions/4192225/prettiness-of-ternary-operator-vs-if-statement">post</a> about the benefits and use cases of using ternary or <code>if/else</code>. Here is what the code would look like refactored to a ternary:</p>
<pre><code>$scope.toggleSelect = event => {
$scope.selection = event.target.innerHTML;
$scope.emailList = $scope.selection === 'Select All' ? $scope.users.filter(user => !user.report.emailed); : [];
};
</code></pre>
<p>Quoting from the article linked above:</p>
<blockquote>
<p>An if/else statement emphasizes the branching first and what's to be done is secondary, while a ternary operator emphasizes what's to be done over the selection of the values to do it with.</p>
</blockquote>
<p>I feel the <code>if/else</code> feels more natural, but I'm not sure if that is just related to my lack of experience using ternary.</p></li>
<li><p>I have another <code>toggleItem</code> function used when a checkbox is clicked.</p>
<pre><code>$scope.toggleItem = (event, user) => {
if (event.target.checked) {
$scope.emailList.push(user);
} else {
$scope.emailList = _.reject($scope.emailList, item => item._id === user._id);
}
</code></pre></li>
</ol>
<p>I've thought about combining both of my <code>toggle</code> functions but overall I think it is better to keep them separate instead of trying to make a generic <code>toggle</code> function with multiple use cases.</p>
<p>In the <code>toggleItem</code> function above, I think it is cleaner (and more obvious) to use an <code>if/else</code> instead of a ternary since I am only making an assignment in the else statement.</p>
<p>I'm trying to improve on writing cleaner code, If anyone has any input or thoughts on best practices to use here or how to clean up this code it would be appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T14:32:10.227",
"Id": "418041",
"Score": "0",
"body": "Second snippet second last line should not be there...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T14:47:05.873",
"Id": "418046",
"Score": "0",
"body": "Please provide some context for this code. What exactly does it do? Is it Angular? If so, please add a tag and add some details. See [ask]."
}
] | [
{
"body": "<h2>Short and sweet is best.</h2>\n<p>Your statement</p>\n<blockquote>\n<p><em>"The main benefit I see here is that anybody reading the code can skim to the last line and know the overall purpose"</em></p>\n</blockquote>\n<p>That makes no sense at all, you say all that is needed to understand the functions is</p>\n<pre><code>$scope.emailList = emailListUpdate;\n</code></pre>\n<p>Nobody jumping into someone else code will just skim, the only people that skim code are those that know the code.</p>\n<p>You can make a few assumptions.</p>\n<ul>\n<li>All that read your code are competent coders.</li>\n<li>All that read your code have read the project specs.</li>\n<li>Every line of code will be read by a coder new to the code.</li>\n</ul>\n<h2>Example</h2>\n<p>The best code is brief as possible without being a code golf entrant.</p>\n<p>Notes</p>\n<ul>\n<li>Why <code>innerHTML</code>, should it not be <code>textContent????</code></li>\n<li>This function is not a toggle. It is based on selection value.</li>\n<li>The ternary expression is too long, break the line so it does need to be scrolled</li>\n<li>The ternary has a syntax error. Misplaced <code>;</code></li>\n<li>the <code>;</code> on the last line after "}" is redundant.</li>\n</ul>\n<p>Code, best option.</p>\n<pre><code>$scope.selectEmailUsers = event => {\n $scope.selection = event.target.textContent;\n $scope.emailList = $scope.selection === "Select All" ? \n $scope.users.filter(user => !user.report.emailed); : [];\n // ^ remove syntax error\n}; // << remove the ;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T15:00:08.767",
"Id": "216058",
"ParentId": "216054",
"Score": "5"
}
},
{
"body": "<p>Some comments here are inspired by below line:</p>\n\n<p><code>Programs must be written for people to read, and only incidentally for machines to execute. — Abelson and Sussman</code></p>\n\n<ul>\n<li><p>When I first looked at the code, first thing I could not stop appreciating was avoiding the ternary operator. Using <code>if</code> makes it easier to setup correct expectations on what is happening without extra attention.</p></li>\n<li><p><code>'Select All'</code> is a CONSTANT which is deciding the method output. So, my suggestion is to move it to the top of the method and assign to a variable.</p></li>\n<li><p>When the code contains conditional execution, having a single place that consumes the result of different blocks would be good choice. I see in your second block of code you made that change. <code>$scope.emailList = emailListUpdate;</code></p></li>\n<li><p><code>$scope.emailList = _.reject($scope.emailList, item => item._id === user._id);</code> I review lot of code internally. No way I would accept code like this. It's not about how smartly we can write code, it's about how easy it is for others to understand. Separate the logic from return statements. Give it a meaningful name to convey what it is and why are you filtering.</p></li>\n<li><p><code>$scope.users.filter(user => !user.report.emailed)</code> is smart! But <code>$scope.users.filter((user) => { return user.report.emailed === false })</code> is easier to understand what's happening.</p></li>\n</ul>\n\n<p>Hope this helps!</p>\n\n<p><strong>Edit:</strong>\nI am curious to understand why my answer deserve negative vote. Someone please take a minute to help me understand.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T12:23:27.223",
"Id": "418143",
"Score": "0",
"body": "Where ever you got that quote from, it is absurd \"only incidentally... to execute\" . First Programs are not source code. Second, the few people that can read source code have specialized knowledge, training and experience related to the programs application Third source codes PRIMARY purpose is to be machine readable, without ambiguity, as such to be, interpreted / compiled / transpiled to a consistently executable form for targeted platforms in a sustainable efficient manner without error or bug"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T18:33:06.377",
"Id": "418170",
"Score": "4",
"body": "@Blindman67 the quote, as noted, is from the authors of [SICP](https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html); if you have to argue, argue with them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T00:22:44.773",
"Id": "418192",
"Score": "0",
"body": "@morbusg Thank you for adding the reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T18:06:22.233",
"Id": "418307",
"Score": "0",
"body": "At a guess `console.log(\"Hello World\")` with 8 redundant lines (I counted 9 `;`). Re your edit Guessing I would think you got a down vote for the last point. The two expressions you give are not equivalent `v => !v` not the same as `v => v === false`. Personally I am temped to down vote due to the quote and the 2nd last point, The 2nd point I have read it three times and still not sure why you find the expression unacceptable and you offer no alternative. However your a newbie here so will say Hi welcome to CR, I am looking forward to your next post. "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T05:46:18.707",
"Id": "418342",
"Score": "1",
"body": "@Blindman67 Thanks, I had few learnings discussing with you. BTW, I am a newbie to CR but not to JavaScript. Glad to hear you that you will follow my answers, I can assure you I will not try chasing others answers with my opinions. Thanks for welcoming to CR. I am sure I will have wonderful time trying to help people write code with mindfulness based on my experiences."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T08:07:47.567",
"Id": "216099",
"ParentId": "216054",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": "216058",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T13:58:23.237",
"Id": "216054",
"Score": "2",
"Tags": [
"javascript",
"comparative-review"
],
"Title": "Toggle Function in JavaScript"
} | 216054 |
<p>I wrote a Java program that when its executable .jar is opened manually, it re-opens itself inside the operating system's shell console. The purpose of this is to have a C#-style console application where the user can enter commands, without the user needing to manually open the shell console and run the <code>java -jar ...</code> command to open the application.</p>
<p>Would you consider this a good implementation?</p>
<p>Would you make a custom console GUI instead of using the OS's console?</p>
<pre><code>public static void main(String[] args){
if(args.length == 0){ // then re-open in console with argument to indicate that there's no need to re-open next time.
try {
String os = System.getProperty("os.name").toLowerCase();
String path = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath();
if(os.contains("mac")){
String command = "tell application \"Terminal\"\n" +
"do script \"java -jar \'" + path + "\' console\"\n" +
"activate\n" +
"end tell";
Runtime.getRuntime().exec( new String[]{"osascript", "-e", command} );
System.exit(0);
} else if(os.contains("win")) {
Runtime.getRuntime().exec("cmd /c start cmd.exe /K java -jar \"" + path + "\" console");
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
System.out.println("Enter command. 'help' for list of commands.");
while(true)
nextCommand();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T08:43:10.520",
"Id": "418214",
"Score": "0",
"body": "The standard way of handling this is you distribute you code as a zip. User runs the `bin/run.bat`, `bin/launch.exe` whatever. If he somehow invokes `Foobar.main` in `lib/foobar.jar` in some other way, maybe he knows what he is doing. Just ensure you have the parameters and let anything else slide."
}
] | [
{
"body": "<p>A few empty lines here and there would do wonders to the readability.</p>\n\n<hr>\n\n<p>This will also relaunch the application if it was started from a terminal without arguments.</p>\n\n<hr>\n\n<pre><code>String path = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath();\n</code></pre>\n\n<hr>\n\n<pre><code>String os = System.getProperty(\"os.name\").toLowerCase();\n...\nif(os.contains(\"mac\")){\n</code></pre>\n\n<p>Unfortunately that is a quite fragile way to detect the current operating system, but it will do.</p>\n\n<hr>\n\n<p>On nay other operating system, you simply start reading commands (or not), are you aware of that?</p>\n\n<p>You should have the command reading in an <code>else</code> branch.</p>\n\n<hr>\n\n<pre><code>System.exit(0);\n</code></pre>\n\n<p>Please stop sprinkling your code with those. <code>System.exit</code> makes the JVM exit <strong><em>immediately</em></strong>, it is like a SIGKILL on UNIX. That means that not even <code>final</code> branches are being run when invoked.</p>\n\n<hr>\n\n<pre><code>while(true)\n nextCommand();\n</code></pre>\n\n<p>I assume that there is a \"quit\" command which calls <code>System.exit</code>, that might be a bad idea. A better idea would be to have something like this:</p>\n\n<pre><code>while(commandExecutor.isActive()) {\n commandExecutor.readAndExecuteCommand());\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T09:56:07.923",
"Id": "216104",
"ParentId": "216059",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216104",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T15:24:30.440",
"Id": "216059",
"Score": "5",
"Tags": [
"java",
"console",
"windows",
"macos"
],
"Title": "Java program that relaunches itself in OS's terminal application"
} | 216059 |
<p>I am trying to make an efficient prime number calculator. I've seen ones that can go up to close to 1 trillion in right around 4 hours, however I left mine on overnight and didn't get anywhere near that. I am asking this to see if anyone here knows a more efficient way for me to get up to a really high number really quickly. I also want to see if my everything else is up to standard as this is only my "2nd year" (classes where you self teach) coding.</p>
<pre><code>#include <vector>
#include <iostream>
int main()
{
std::vector<int> primes; //vector that will have all numbers in it
primes.push_back(3); //push back the first 2 primes (not 2 due to never checking % 2 numbers)
primes.push_back(5);
for (unsigned long long i = 7;; i += 2) //loop controlling the number that will be output
{
for (int j = 0; i % primes[j] != 0; ++j) //loop that "scrolls" through my vector
{
if (sqrt(i) <= primes[j]) //if the square root of the number you're outputting is lower than the number you're checking against
{
std::cout << i << std::endl; //output
primes.push_back(i);
break;
}
else
continue;
}
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T15:54:48.717",
"Id": "418053",
"Score": "9",
"body": "If you search for \"Eratosthenes\" on this site, you'll find quite a few examples of a method that's (considerably) faster."
}
] | [
{
"body": "<p>The <code>std::vector<></code> is a dynamically sized container. The allocation strategy is implementation dependent, but for sake of the argument, assume the <code>.capacity()</code> of a <code>std::vector<></code> starts off at 1 and doubles each time the vector's size exceeds the current capacity. This capacity increase requires a reallocation of storage, and possibly a copying of the entire array contents to a new location. If you are generating 1 trillion primes, you'll need 40 reallocations and will have done 1 trillion number copies over the course of the 40 reallocations. This is wasting time. If the operating system gets involved with virtual memory paging, you are going to suck up a lot more time.</p>\n\n<p>This overhead can be eliminated by simply <a href=\"http://www.cplusplus.com/reference/vector/vector/reserve/\" rel=\"nofollow noreferrer\"><code>.reserve(size_type n)</code></a>-ing the expected size of the vector ahead of time. With sufficient memory allocated to the vector upfront, no reallocations will occur, and no copies will occur.</p>\n\n<hr>\n\n<pre><code> for (unsigned long long i = 7;; i += 2) \n {\n for (int j = 0; i % primes[j] != 0; ++j) \n {\n if (sqrt(i) <= primes[j]) \n {\n</code></pre>\n\n<p>When <code>i</code> is a prime number or semi-prime number in the order of, say, one million, you are looping over all the prime numbers upto the square root of a million, to see if any of them can divide your current number.</p>\n\n<p>How many different values will <code>sqrt(i)</code> evaluate to over those thousand iterations? Or phrased another way, how many times are you computing the same square root? You may want to move that <code>sqrt(i)</code> calculation out of the inner loop.</p>\n\n<hr>\n\n<pre><code> for (unsigned long long i = 7;; i += 2) \n</code></pre>\n\n<p>If you let this loop run over night, or even over a fort-night, will this loop ever end? No! <code>i</code> will overflow the <code>long long</code> and become negative, and slowly increment back towards positive numbers and repeat. Forever is not long enough. Use, at the very least, <code>i > 0</code> as the loop test condition.</p>\n\n<hr>\n\n<p>A <code>long long</code> has at least 64 bits. A <code>double</code> has only a 52 bit mantissa. This means when you pass a large <code>long long</code> to <code>sqrt( )</code>, you will end up losing a few bits of precision, which can make your <code>sqrt()</code> return slightly the wrong value. When you test <code>sqrt(i) <= primes[j]</code>, if <code>i</code> is greater than 2^52, and is a perfect square, you might return a value slightly less than the correct value and fail to test the last prime value, and erroneously declare the perfect square a prime number.</p>\n\n<hr>\n\n<p>You are stuffing <code>long long</code> values into a <code>std:vector<int></code> container. After a while, they ain't gonna fit.</p>\n\n<hr>\n\n<p>You are using <code>long long</code> for your prime number candidates, which means you expect to find some prime numbers above 2^31.</p>\n\n<p>The Prime Number Theorem tells us the density of prime numbers in that range to be around 1/21. Or, after testing numbers up to 21 billion, you should have found around 1 billion prime numbers.</p>\n\n<p>Your prime number index <code>j</code> is declared as an <code>int</code>. An <code>int</code> is only guaranteed to have 16 bits. You would need at least a <code>long</code> to guarantee 32 bits. But if you hope to find prime numbers up to 2^52, you have to expect to find 2^45 primes, which even exceeds a <code>long</code>. Your <code>j</code> index should be a <code>long long</code> as well.</p>\n\n<hr>\n\n<p>Finally, as mentioned in the comments, look at the Sieve of Eratosthenes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T03:56:31.187",
"Id": "216137",
"ParentId": "216061",
"Score": "7"
}
},
{
"body": "<p>This might be a peripheral advice </p>\n\n<p>using <code>std::cout</code> is a <strong>slow procedure</strong>, you may do better with defining a temporary buffer of some significant size and use <code>std::cout</code> as soon as the buffer fills then reuse the buffer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:26:45.057",
"Id": "216260",
"ParentId": "216061",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T15:49:51.433",
"Id": "216061",
"Score": "4",
"Tags": [
"c++",
"performance",
"primes"
],
"Title": "Efficient Prime Number Generator in c++"
} | 216061 |
<p>This is a registration and login script I have made in Python 3. It uses a MySQL database. In the future I might use it with my Blackjack game and add a row called <code>money</code>, but for now I would like to hear your opinion about this script since I have little to no experience in SQL.</p>
<pre><code>import cymysql
from getpass import getpass
def get_user_info():
while True:
email = input("Input your Email address (max. 64 chars.): ")
password = getpass("Input a password (max. 64 chars.): ")
if len(email) < 64 and len(password) < 64:
return email, password
def register(cur, email, password):
cur.execute("INSERT INTO `users` (`Email`, `Password`) VALUES (%s, %s)", (email, password))
print("You've succesfully registered!")
def login(cur, email, password):
cur.execute("SELECT * FROM `users` WHERE `Email`=%s AND `Password`=%s LIMIT 1", (email, password))
rows = cur.fetchall()
if rows:
print("You've succesfully logged-in!")
else:
print("You failed logging-in!")
def check_account(cur, email):
cur.execute("SELECT * FROM `users` WHERE `Email`=%s LIMIT 1", (email,))
row = cur.fetchone()
return row
def main():
conn = cymysql.connect(
host='127.0.0.1',
user='root',
passwd='',
db='david'
)
cur = conn.cursor()
email = ''
password = ''
email, password = get_user_info()
check = check_account(cur, email)
if check:
login(cur, email, password)
else:
register(cur, email, password)
cur.close()
conn.close()
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<ol>\n<li><code>cymysql.connect</code> is <a href=\"https://github.com/nakagami/CyMySQL/blob/master/cymysql/connections.py#L324\" rel=\"noreferrer\">a context manager</a> and so you should use it in a <code>with</code> statement.</li>\n<li><code>conn.cursor</code> isn't a context manager. Which is very fishy, even more so that the original version of cymysql, pymysql, is.</li>\n<li>Seperate SQL interactions from UI interactions. This is as multiple parts of the UI may need to use the same SQL interactions, however since they're mangled, it'll lead to code duplication or errors in your UI.</li>\n<li>You don't need to do <code>email = ''</code>, if you want to tell people it's a string then you can do <code>email: str</code>. A better thing to do however is use <code>typing</code> and make your code fully typed.</li>\n<li>You may want to verify that the email is a valid email address. It doesn't look like your SQL does that, but I don't know enough about it.</li>\n</ol>\n\n\n\n<pre><code>import cymysql\nfrom getpass import getpass\n\n\ndef get_user_info():\n while True:\n email = input(\"Input your Email address (max. 64 chars.): \")\n password = getpass(\"Input a password (max. 64 chars.): \")\n if len(email) < 64 and len(password) < 64:\n return email, password\n\n\ndef register(cur, email, password):\n cur.execute(\"INSERT INTO `users` (`Email`, `Password`) VALUES (%s, %s)\", (email, password))\n\n\ndef login(cur, email, password):\n cur.execute(\"SELECT * FROM `users` WHERE `Email`=%s AND `Password`=%s LIMIT 1\", (email, password))\n return bool(cur.fetchall())\n\n\ndef check_account(cur, email):\n cur.execute(\"SELECT * FROM `users` WHERE `Email`=%s LIMIT 1\", (email,))\n return bool(cur.fetchone())\n\n\ndef main():\n conn = cymysql.connect(\n host='127.0.0.1',\n user='root',\n passwd='',\n db='david'\n )\n with conn:\n cur = conn.cursor()\n email, password = get_user_info()\n check = check_account(cur, email)\n if check:\n loggedin = login(cur, email, password)\n if loggedin:\n print(\"You've succesfully logged-in!\")\n else:\n print(\"You failed logging-in!\")\n else:\n register(cur, email, password)\n print(\"You've succesfully registered!\")\n cur.close()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T19:10:46.207",
"Id": "418089",
"Score": "0",
"body": "Hey! Thanks for the answer, but in my original script I have conn.close() at the end of main(). Should I use it in the updated script too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T19:16:48.020",
"Id": "418091",
"Score": "0",
"body": "@MariaLaura You're not guarantee to reach the `conn.close()` - If I raise a keyboard interrupt, or kill the script does `conn.close()` run your way?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:57:45.960",
"Id": "216072",
"ParentId": "216065",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "216072",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T17:58:54.390",
"Id": "216065",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"sql",
"mysql"
],
"Title": "Registration and login script"
} | 216065 |
<p><strong>Problem</strong></p>
<blockquote>
<p>Reverse digits of a 32-bit signed integer. When the reversed integer overflows return 0. <a href="https://codereview.stackexchange.com/questions/216300/reverse-int-within-the-32-bit-signed-integer-range-%E2%88%92231-231-%E2%88%92-1-op">Optimized code here</a>.</p>
</blockquote>
<p><strong>Feedback</strong></p>
<p>I'm looking for any ways I can optimize this with modern C++ features overall. I hope my use of const-correctness, exception handling, and assertions is implemented well here, please let me know. Is there any way I can use byte operations to reverse the int and keep track of the sign possibly?</p>
<p>Based on the submission feedback from LeetCode, is it safe to say that the time complexity is <span class="math-container">\$O(n)\$</span> and space complexity is <span class="math-container">\$O(n)\$</span>? If I can reduce the complexity in anyway would love to know!</p>
<p><a href="https://i.stack.imgur.com/8Lqbw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Lqbw.png" alt="enter image description here"></a></p>
<pre><code>#include <cassert>
#include <climits>
#include <stdexcept>
#include <string>
class Solution
{
public:
int reverse(int i) {
bool is_signed = false;
if(i < 0) { is_signed = true; }
auto i_string = std::to_string(i);
std::string reversed = "";
while(!i_string.empty()) {
reversed.push_back(i_string.back());
i_string.pop_back();
}
try {
i = std::stoi(reversed);
} catch (const std::out_of_range& e) {
return 0;
}
if(is_signed) { i *= -1; }
return i;
}
};
int main()
{
Solution s;
assert(s.reverse(1) == 1);
assert(s.reverse(0) == 0);
assert(s.reverse(123) == 321);
assert(s.reverse(120) == 21);
assert(s.reverse(-123) == -321);
assert(s.reverse(1207) == 7021);
assert(s.reverse(INT_MAX) == 0);
assert(s.reverse(INT_MIN) == 0);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:39:31.697",
"Id": "418083",
"Score": "0",
"body": "This https://leetcode.com/problems/reverse-integer/ ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T19:03:40.317",
"Id": "418087",
"Score": "0",
"body": "Yes that's the one"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T23:42:13.850",
"Id": "418512",
"Score": "0",
"body": "The problem is ill-posed. If 'the' reverse of `120` is `21`, how can you know whether 'the' reverse of `21` should be `120` or `12`? What makes 'the' reverse of `1` number `1` and not `10000`? How can you tell your code **solves the problem** if the correct **solution is not defined?**"
}
] | [
{
"body": "<p><strong>General comments</strong></p>\n\n<ul>\n<li><p>There is no reason to use a class. Instead, the functionality should be made into a free function.</p></li>\n<li><p>Your code is overly complicated. There is no reason to make new string from which you erase characters one-by-one. Instead, you can convert the input integer to a string and use a standard function to reverse that.</p></li>\n<li><p>Also, pay attention to const correctness. This protects from unintended mistakes and helps the compiler optimize more.</p></li>\n</ul>\n\n<p>I would simplify your function to just:</p>\n\n<pre><code>int reverse(int i) \n{\n try\n {\n auto reversed{ std::to_string(i) };\n std::reverse(reversed.begin(), reversed.end());\n\n const auto result{ std::stoi(reversed) };\n return i < 0 ? -1 * result : result;\n }\n catch (const std::out_of_range& e) \n {\n return 0;\n }\n}\n</code></pre>\n\n<p><strong>Further comments</strong></p>\n\n<ul>\n<li><p>If you want to have a fast solution, you should avoid <code>std::string</code> altogether. This you can do by \"iterating\" through the digits using arithmetic operations (division and modulus), as in (using <code>std::string</code> to only show you what is happening):</p>\n\n<pre><code>int x = 1234;\nstd::string s;\n\nwhile (x > 0)\n{\n s.push_back('0' + (x % 10));\n x /= 10;\n}\n\nstd::cout << s << \"\\n\"; // Prints 4321\n</code></pre>\n\n<p>I will let you take it from here to use these ideas to make your program even faster.</p></li>\n<li><p>Regarding your theoretical question concerning complexity, if we assume that the input is treated as a string of n characters, there is <span class=\"math-container\">\\$\\Omega(n)\\$</span> lower bound by a trivial adversary argument. Basically, if you don't spend at least n time, you can't read the whole of the input, and then you cannot guarantee correct output on every instance.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T01:59:48.803",
"Id": "418195",
"Score": "0",
"body": "Trying the digit iteration now, great concept that I'm adding to my toolbox. Fantastic feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T20:11:55.940",
"Id": "418319",
"Score": "0",
"body": "if you'd like to see the optimized version I've edited my post"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T21:08:58.820",
"Id": "418323",
"Score": "1",
"body": "@greg I'd be happy to comment on that as well, but you shouldn't change your code after you've received an answer. Instead, you should post it as a separate question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T21:09:58.663",
"Id": "418324",
"Score": "1",
"body": "@esote Great, thanks for the edits! I know how to use Latex now on this site too :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T23:15:39.590",
"Id": "418510",
"Score": "0",
"body": "Updated the code here https://codereview.stackexchange.com/questions/216300/reverse-int-within-the-32-bit-signed-integer-range-%E2%88%92231-231-%E2%88%92-1-op learning math operations to pop and push digits has been very valuable in optimizing this"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:50:41.103",
"Id": "216070",
"ParentId": "216068",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "216070",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:31:16.167",
"Id": "216068",
"Score": "4",
"Tags": [
"c++",
"c++11",
"interview-questions",
"integer"
],
"Title": "Reverse int within the 32-bit signed integer range"
} | 216068 |
<p>After reading some articles about immutability, I found out that there are <a href="https://en.wikipedia.org/wiki/Persistent_data_structure" rel="noreferrer">persistent data structures</a>. In the following, I implemented a stack as a persistent data structure.</p>
<p>What I like about the code in the current state </p>
<ul>
<li>it contains <a href="https://francescocirillo.com/pages/anti-if-campaign" rel="noreferrer">no if-statements</a></li>
<li>no method is longer than one line </li>
<li>it works like recursion</li>
</ul>
<h1>Implementation</h1>
<p>The implementation is based on the abstraction <code>Stack</code>, which has two concrete data-types: <code>EmptyStack</code> and <code>NonEmptyStack</code>. A <code>Stack</code> needs to implement 4 methods as described below.</p>
<pre class="lang-java prettyprint-override"><code>public interface Stack<E> {
/**
* @return the number of elements
*/
int size();
/**
* adds a new element to the top of the {@code Stack}
*
* @param top represents the new element to be added
* @return a {@code Stack} with {@code top} on it
*/
Stack<E> push(E top);
/**
* removes the top element of the {@code Stack}
*
* @return a {@code Stack} without the top element
*/
Stack<E> pop();
/**
* @return if {@code Stack} is empty {@code Optional.empty};
* otherwise {@code Optional.of(E)} where {@code E} is the top element
*/
Optional<E> top();
}
</code></pre>
<p>The <code>EmptyStack</code> represents the base case: when a <code>Stack</code> has no element. For each method it is easy to predict all return values:</p>
<ul>
<li>the <code>size</code> is always <code>0</code></li>
<li><code>push()</code> always will return a <code>NonEmptyStack</code> with the new top element and the current instance as the previous version</li>
<li><code>pop()</code> can't return a top element; so it always will return an <code>EmptyStack</code></li>
<li><code>top()</code> can't return a top element; so it always will return an <code>Optional.empty</code></li>
</ul>
<pre class="lang-java prettyprint-override"><code>class EmptyStack<E> implements Stack<E> {
@Override
public int size() {
return 0;
}
@Override
public Stack<E> push(E top) {
return new NonEmptyStack<>(top, this);
}
@Override
public Stack<E> pop() {
return this;
}
@Override
public Optional<E> top() {
return Optional.empty();
}
}
</code></pre>
<p>On the other hand there is the <code>NonEmptyStack</code> which represents a <code>Stack</code> that contains elements. A <code>NonEmptyStack</code> is made up of its element on the top and a <code>Stack</code> as its tail, which represents the previous version.</p>
<ul>
<li>the <code>size</code> is always the size of the previous version plus 1 for the new top element </li>
<li><code>push()</code> always will return a <code>NonEmptyStack</code> with the new top element and the current instance as the previous version</li>
<li><code>pop()</code> always returns the tail</li>
<li><code>top()</code> always returns the element which represents the top and since it can be <code>null</code> I used <code>Optional.ofNullable</code></li>
</ul>
<pre class="lang-java prettyprint-override"><code>class NonEmptyStack<E> implements Stack<E> {
private final Stack<E> tail;
private final E top;
NonEmptyStack(E top, Stack<E> tail) {
this.tail = tail;
this.top = top;
}
@Override
public int size() {
return 1 + tail.size();
}
@Override
public Stack<E> push(E top) {
return new NonEmptyStack<>(top, this);
}
@Override
public Stack<E> pop() {
return tail;
}
@Override
public Optional<E> top() {
return Optional.ofNullable(top);
}
}
</code></pre>
<p><code>EmptyStack</code> and <code>NonEmptyStack</code> are package-private therewith a client only interacts with a <code>Stack</code> instead of two different implementations of it. For that I created a Factory <code>StackFactory</code> which returns an <code>EmptyStack</code> as a <code>Stack</code> and the clients never interacts directly with a concrete implementation.</p>
<pre class="lang-java prettyprint-override"><code>public class StackFactory<E> {
public Stack<E> create() {
return new EmptyStack<>();
}
}
</code></pre>
<h1>Unit Tests</h1>
<pre class="lang-java prettyprint-override"><code>import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
class EmptyStackTest {
private final Stack<String> EMPTY_STACK = new EmptyStack<>();
@Test
void givenAnEmptyStack_whenQueryTheSize_thenExpect0() {
// arrange
// act
int size = EMPTY_STACK.size();
// assert
assertEquals(0, size);
}
@Test
void givenAnEmptyStack_whenPushAnElementToIt_thenExpectANonEmptyStack() {
// arrange
// act
Stack<String> stack = EMPTY_STACK.push("first");
// assert
assertTrue(stack instanceof NonEmptyStack);
}
@Test
void givenAnEmptyStack_whenRemoveTheFirstElement_thenExpectAnEmptyStack() {
// arrange
// act
Stack<String> stack = EMPTY_STACK.pop();
// assert
assertTrue(stack instanceof EmptyStack);
}
@Test
void givenAnEmptyStack_whenAccessTopElement_thenExpectItDoNotExists() {
// arrange
// act
Optional<String> top = EMPTY_STACK.top();
// assert
assertTrue(!top.isPresent());
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>import org.junit.jupiter.api.Test;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class NonEmptyStackTest {
private final String ITEM = "first";
@Test
void givenEmptyStackAndItem_whenInstantiateAndQueryTheSize_thenExpect1() {
// arrange
Stack<String> stack = new NonEmptyStack<>(ITEM, new EmptyStack<>());
// act
int size = stack.size();
// assert
assertEquals(1, size);
}
@Test
void givenNonEmptyStackWitOneItemAndANewItem_whenInstantiateAndQueryTheSize_thenExpect2() {
// arrange
NonEmptyStack<String> nonEmptyStack = new NonEmptyStack<>(ITEM, new EmptyStack<>());
Stack<String> stack = new NonEmptyStack<>(ITEM, nonEmptyStack);
// act
int size = stack.size();
// assert
assertEquals(2, size);
}
@Test
void givenEmptyStackAndItem_whenPushTheItemToTheStack_thenTheItemShouldBeInTheStack() {
// arrange
Stack<String> stack = new EmptyStack<>();
// act
Stack<String> nonEmptyStack = stack.push(ITEM);
// assert
assertEquals(Optional.of(ITEM), nonEmptyStack.top());
}
@Test
void givenNonEmptyStackAndItem_whenPushTheItemToTheStack_thenTheItemShouldBeInTheStack() {
// arrange
Stack<String> emptyStack = new EmptyStack<>();
Stack<String> firstChange = emptyStack.push("value");
// act
Stack<String> stack = firstChange.push(ITEM);
// assert
assertEquals(Optional.of(ITEM), stack.top());
}
@Test
void givenNonEmptyStackWithOneItem_whenRemoveTheTopItem_thenExpectEmptyStack() {
// arrange
Stack<String> testCandidate = new NonEmptyStack<>(ITEM, new EmptyStack<>());
// act
Stack<String> stack = testCandidate.pop();
// assert
assertTrue(stack instanceof EmptyStack);
}
@Test
void givenNonEmptyStackWithTwoItems_whenRemoveTheTopItem_thenExpectNonEmptyStack() {
// arrange
Stack<String> testCandidate = new NonEmptyStack<>(ITEM, new EmptyStack<>()).push(ITEM);
// act
Stack<String> stack = testCandidate.pop();
// assert
assertTrue(stack instanceof NonEmptyStack);
}
@Test
void givenNonEmptyStack_whenQueryTopItem_thenExpectTopItem() {
// arrange
Stack<String> stack = new NonEmptyStack<>(ITEM, new EmptyStack<>());
// act
Optional<String> top = stack.top();
// assert
assertEquals(Optional.of(ITEM), top);
}
}
</code></pre>
<h1>Example</h1>
<pre class="lang-java prettyprint-override"><code>public class Main {
public static void main(String[] args) {
Stack<String> stack = new StackFactory<String>().create()
.push("first")
.push("second")
.push("third");
Stack<String> modified = stack.pop()
.pop();
modified.top()
.ifPresent(System.out::println); // "first"
modified.pop()
.top()
.ifPresent(System.out::println); // nothing happens
}
}
</code></pre>
<hr>
<p>This little experiment was very entertaining. I appreciate every feedback and thank you very much for reading my code! :]</p>
| [] | [
{
"body": "<p>In this implementation, <code>null</code> entries are problematic. From the public interface, it is impossible to tell if the stack has a null entry, or has reached the bottom: in both cases, <code>top()</code> will return <code>Optional.empty()</code>.</p>\n\n<p>It seems wrong to silently convert <code>null</code>s into <code>Optional.empty()</code>s. I would do one of the following:</p>\n\n<ol>\n<li><p>Do not store <code>null</code> entries in the stack. Instead, throw an exception on <code>push</code>ing a <code>null</code> value.</p></li>\n<li><p>Stop using <code>Optional</code>s and instead throw an exception when <code>top</code> is called on an empty stack. Add an <code>empty</code> method to determine if the stack is empty.</p></li>\n</ol>\n\n<p>Other than that, very clean simple code! A few smaller comments.</p>\n\n<p>Note that <code>push</code> has the same implementation in both <code>EmptyStack</code> and <code>NonEmptyStack</code>. If you like, they could inherit from a single abstract class implementing <code>push</code>. This is a judgement call: repeated code is kinda bad, but adding a whole new abstract class is complicated. Perhaps the the cure is worse than the disease...</p>\n\n<p>Computing <code>size</code> is slow: time O(n). If you are worried about this, you could compute and store the size in the constructor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T11:47:53.703",
"Id": "418139",
"Score": "1",
"body": "Since Java 8, methods defined in an interface can have a default implementation. So you wouldn't have to create a separate abstract class to avoid the code duplication in the `push` methods."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T23:47:46.310",
"Id": "216084",
"ParentId": "216071",
"Score": "6"
}
},
{
"body": "\n\n<p>The need to instantiate a <code>StackFactory</code> in order to create a <code>Stack</code> seems superfluous. I would suggest making <code>create()</code> a <code>static</code> method, which in turn would mean that, instead of the class <code>StackFactory</code>, it will be the method <code>create()</code> that needs a type parameter:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class StackFactory {\n\n public static <E> Stack<E> create() {\n return new EmptyStack<>(); //compiler can infer the type parameter for the newly created Stack from the method's return type\n }\n}\n</code></pre>\n\n<p>Then you can call the method like this:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Stack<String> stack = StackFactory.<String>create()\n .push(\"first\")\n .push(\"second\")\n .push(\"third\");\n</code></pre>\n\n<p>Note that, in the above example, you need to explicitly pass the type parameter <code>String</code> to the method <code>create()</code>, because the newly created <code>Stack</code> is not directly assigned to a variable of type <code>Stack<String></code> and the compiler can therefore not infer the type parameter <code>E</code> for the call to the method <code><E> create()</code> to be <code>String</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T12:49:02.833",
"Id": "216110",
"ParentId": "216071",
"Score": "3"
}
},
{
"body": "<p>I'd like to point out, that it's unnecessary to create a new instance of <code>EmptyStack</code> every time you need an empty stack. A single static instance can be used. Additionally <code>StackFactory</code> can be avoided by having a static factory method in <code>EmptyStack</code>.</p>\n\n<pre><code>public class EmptyStack<E> implements Stack<E> {\n\n private static final Stack<?> INSTANCE = new EmptyStack<>();\n\n @SuppressWarnings(\"unchecked\")\n public static <X> Stack<X> instance() {\n return (Stack<X>) INSTANCE;\n }\n\n private EmptyStack() {}\n\n // ...\n\n}\n</code></pre>\n\n<p>For a nicer API, I'd add a static <code>empty()</code> method to the <code>Stack</code> interface:</p>\n\n<pre><code>public interface Stack<E> {\n\n public static <X> Stack<X> empty() {\n return EmptyStack.instance();\n }\n\n // ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T11:23:52.530",
"Id": "216148",
"ParentId": "216071",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216084",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T18:55:32.720",
"Id": "216071",
"Score": "8",
"Tags": [
"java",
"object-oriented",
"stack",
"immutability"
],
"Title": "Stack as a Persistent Data Structure Implementation"
} | 216071 |
<p>I'm learning Go and I wrote this for a programming challenge. It is working (building and running) but I feel the code is not what Go code should be: </p>
<ul>
<li>Am I using the <code>struct</code> element correctly? especially struct methods?</li>
<li>In the <code>playTurn()</code> method, I reassign results (else not taken into account) because scope. How to write it better? Pointer?</li>
<li>I am struggling with <code>int</code>, <code>float64</code> and casting all the time. What's the good practice in this context were I need float for precision in-between but inputs and outputs are int? </li>
</ul>
<p><strong>What does this code do?</strong> It plays a 2D racing game between 4 pod-racers.
In an infinite loop controlled by the programming challenge server, this code reads inputs about pods states (cf. comments) and outputs the next action my pods should take.
The part I want to discuss is the simulation part: the code also forecast what my pod state should be after taking the next action.
I don't really care if there are bugs right now (since I am writing unit tests to catch them), still I am open to any criticism.</p>
<p>However, I am worried I didn't write in a <strong>Go-like manner</strong>. See my 3 questions. As a consequence of a better Go code, I expect better performances.</p>
<p>Full script:</p>
<pre><code>package main
import (
"fmt"
"math"
"os"
"strconv"
)
// Pod is life
type Pod struct {
position Dot
vx, vy, angle, nextCpID int
hasShieldOn bool
}
func squaredDist(a, b Dot) int {
return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y)
}
func distance(a, b Dot) float64 {
return math.Sqrt(float64(squaredDist(a, b)))
}
func (pod Pod) getAngle(p Dot) float64 {
d := distance(p, pod.position)
dx := float64(p.x-pod.position.x) / d
dy := float64(p.y-pod.position.y) / d
a := math.Acos(dx) * 180.0 / math.Pi
// If the point I want is below me, I have to shift the angle for it to be correct
if dy < 0 {
a = 360.0 - a
}
return a
}
func (pod Pod) diffAngle(p Dot) float64 {
a := pod.getAngle(p)
pangle := float64(pod.angle)
right := 0.0
if pangle <= a {
right = a - pangle
} else {
right = 360.0 - pangle + a
}
left := 0.0
if pangle >= a {
left = pangle - a
} else {
left = pangle + 360.0 - a
}
if right < left {
return right
}
return -left
}
func (pod Pod) rotate(p Dot) int {
a := pod.diffAngle(p)
// Can't turn more than 18° in one turn !
if a > 18.0 {
a = 18.0
} else if a < -18.0 {
a = -18.0
}
pod.angle += int(math.Round(a))
if pod.angle >= 360.0 {
pod.angle = pod.angle - 360.0
} else if pod.angle < 0.0 {
pod.angle += 360.0
}
return pod.angle
}
func (pod Pod) boost(t int) (int, int) {
if pod.hasShieldOn {
return pod.vx, pod.vy
}
pangle := float64(pod.angle)
pod.vx += int(math.Round(math.Cos(pangle) * float64(t)))
pod.vy += int(math.Round(math.Sin(pangle) * float64(t)))
return pod.vx, pod.vy
}
// t shoud become a float later on
func (pod Pod) move(t int) (int, int) {
pod.position.x += pod.vx * t
pod.position.y += pod.vy * t
return pod.position.x, pod.position.y
}
func (pod Pod) endTurn() (int, int) {
// todo rounding position if needed
pod.vx = int(float64(pod.vx) * 0.85)
pod.vy = int(float64(pod.vy) * 0.85)
return pod.vx, pod.vy
}
func (pod Pod) playTurn(p Dot, t int) {
pod.angle = pod.rotate(p)
pod.vx, pod.vy = pod.boost(t)
pod.position.x, pod.position.y = pod.move(1)
pod.vx, pod.vy = pod.endTurn()
fmt.Fprintf(os.Stderr, "\nPredicted Pod position : ")
fmt.Fprintf(os.Stderr, "\n(%d, %d) speed (%d,%d)", pod.position.x, pod.position.y, pod.vx, pod.vy)
}
// Dot is king
type Dot struct {
x, y int
}
func main() {
var laps int
fmt.Scan(&laps)
var checkpointCount int
fmt.Scan(&checkpointCount)
var checkPoints []Dot
for i := 0; i < checkpointCount; i++ {
var checkpointX, checkpointY int
fmt.Scan(&checkpointX, &checkpointY)
checkPoints = append(checkPoints, Dot{checkpointX, checkpointY})
}
var myPods [2]Pod
var itsPods [2]Pod
for {
for i := 0; i < 2; i++ {
// x: x position of your pod
// y: y position of your pod
// vx: x speed of your pod
// vy: y speed of your pod
// angle: angle of your pod
// nextCheckPointId: next check point id of your pod
var x, y, vx, vy, angle, nextCheckPointID int
fmt.Scan(&x, &y, &vx, &vy, &angle, &nextCheckPointID)
myPods[i] = Pod{Dot{x, y}, vx, vy, angle, nextCheckPointID, false}
fmt.Fprintf(os.Stderr, "\nActual Pod position : ")
fmt.Fprintf(os.Stderr, "\n(%d, %d) speed (%d,%d)", myPods[i].position.x, myPods[i].position.y, myPods[i].vx, myPods[i].vy)
}
for i := 0; i < 2; i++ {
// x2: x position of the opponent's pod
// y2: y position of the opponent's pod
// vx2: x speed of the opponent's pod
// vy2: y speed of the opponent's pod
// angle2: angle of the opponent's pod
// nextCheckPointId2: next check point id of the opponent's pod
var x2, y2, vx2, vy2, angle2, nextCheckPointID2 int
fmt.Scan(&x2, &y2, &vx2, &vy2, &angle2, &nextCheckPointID2)
itsPods[i] = Pod{Dot{x2, y2}, vx2, vy2, angle2, nextCheckPointID2, false}
}
// fmt.Fprintln(os.Stderr, "Debug messages...")
for _, pod := range myPods {
nx := checkPoints[pod.nextCpID].x - 3*pod.vx
ny := checkPoints[pod.nextCpID].y - 3*pod.vy
// Predicting where my pods will be next turn:
pod.playTurn(Dot{nx, ny}, 100)
//
fmt.Println(strconv.Itoa(nx) + " " + strconv.Itoa(ny) + " 100")
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T01:11:50.333",
"Id": "418115",
"Score": "2",
"body": "What does this code do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T09:30:09.350",
"Id": "418220",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T14:29:14.603",
"Id": "418267",
"Score": "0",
"body": "thanks for the feedback & the edit. Should I split it into 3 posts : OOP in Go, is it a pointers use case, how to manage int and float64 ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T14:03:09.093",
"Id": "421305",
"Score": "0",
"body": "@Poutrathor I've not taken the time to read through your code yet, but I did notice the use of value receivers. It doesn't make sense to have functions like `move` on a type, and in those funcs statements like `pod.position.x += pod.vx * t` (assigning values), unless you're dealing with pointer receivers. Otherwise, you'd just be reassigning values on a copy, but the object itself is never changed."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T19:37:27.177",
"Id": "216074",
"Score": "3",
"Tags": [
"performance",
"object-oriented",
"programming-challenge",
"go",
"pointers"
],
"Title": "Writing Go object code that respects Go guidelines"
} | 216074 |
<p>I am learning C and this is an exercise from <strong>The C Programmnig Languange</strong> by Brian and Ritchie.</p>
<blockquote>
<p>Write a program "detab" that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every <span class="math-container">\$n\$</span> columns. Should <span class="math-container">\$n\$</span> be a variable or a symbolic parameter?</p>
</blockquote>
<p>Here's my try, and I've made <span class="math-container">\$n\$</span> a parameter. I would appreciate any feedback and explanation on symbolic parameter.</p>
<pre><code>#include <stdio.h>
#define TABLENGTH 8
void detab(int n);
int main () {
int c, noOfTabs;
noOfTabs = 0;
while ((c = getchar()) != EOF) {
if (c == '\t') {
++noOfTabs;
} else if (noOfTabs > 0) {
detab(noOfTabs);
noOfTabs = 0;
putchar(c);
}
}
return 0;
}
void detab (int n) {
while (n > 0) {
--n;
int i;
for (i = 0; i < TABLENGTH; ++i) {
putchar(' ');
}
}
}
</code></pre>
| [] | [
{
"body": "<p>The code is not ready for review, because it <em>does not</em> solve the exercise. It blindly replaces each tab with <code>TABLENGTH</code> spaces. This is not detabbing; the amount of blanks must give you <em>a next tab stop</em>. For example, for</p>\n\n<pre><code>a\\tb\naa\\tb\naaa\\tb\n</code></pre>\n\n<p>the output should be</p>\n\n<pre><code>a b\naa b\naaa b\n</code></pre>\n\n<p>(number of blanks is 7, 6, and 5 respectively, to align <code>b</code> at the tab stop, the 8th column). Your code produces</p>\n\n<pre><code>a b\naa b\naaa b\n</code></pre>\n\n<p>instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T22:08:35.407",
"Id": "216080",
"ParentId": "216076",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T20:48:59.660",
"Id": "216076",
"Score": "0",
"Tags": [
"beginner",
"c"
],
"Title": "Replace tabs in input and variable vs symbolic parameter"
} | 216076 |
<p>I am currently writing my first TDD application. The project is in Xamarin.Forms and tested in xUnit. I am also using Autofac and Moq.</p>
<blockquote>
<p>The first class below is testing second class (VM). The VM is:</p>
<ul>
<li><code>LoadGroups</code> method is populating collection of group names (strings),</li>
<li><code>LoadFromFile</code> method is loading from CSV file string with data and creates collection of objects,</li>
<li><code>PopulateDb</code> method takes collection of objects and seeds DB with them.</li>
</ul>
</blockquote>
<p>I wonder if maybe more experienced developers will have any comments or suggestions regarding the code or architecture, before I will continue with next View Models, to avoid corrections.</p>
<p><a href="https://github.com/przemyslawbak/Flashcards/blob/master/Flascards.UnitTests/ViewModels/MainPageViewModelTests.cs" rel="nofollow noreferrer">Test class</a>:</p>
<pre><code>public class MainPageViewModelTests
{
List<Phrase> phrases;
private MainPageViewModel _viewModel;
private Mock<IPhraseEditViewModel> _phraseEditViewModelMock;
private Mock<IMainDataProvider> _mainDataProviderMock;
public MainPageViewModelTests()
{
//instances
phrases = new List<Phrase>
{
new Phrase { Category = "newCat1", Definition = "newDef1", Group = "newGr1", Learned = false, Name = "newName1", Priority = "newPrio1", Id = 7 }
};
_phraseEditViewModelMock = new Mock<IPhraseEditViewModel>();
_mainDataProviderMock = new Mock<IMainDataProvider>();
//setup
_mainDataProviderMock.Setup(dp => dp.GetGroups())
.Returns(new List<string>
{
"Group #1",
"Group #2",
"Group #3"
});
_mainDataProviderMock.Setup(dp => dp.PickUpFile())
.ReturnsAsync("goodData.csv");
_mainDataProviderMock.Setup(dp => dp.GetStreamFromCSV("goodData.csv"))
.Returns("Name|Definition|Category|Group|Priority\nname1 |def1|cat1|gr1|prio1\nname2 |def2|cat2|gr2|prio2");
_mainDataProviderMock.Setup(dp => dp.GetStreamFromCSV("emptyData.csv"))
.Returns("");
//VM instance
_viewModel = new MainPageViewModel(_mainDataProviderMock.Object, CreatePhraseEditViewModel);
}
private IPhraseEditViewModel CreatePhraseEditViewModel() //method for creating PhraseEditVM
{
var phraseEditViewModelMock = new Mock<IPhraseEditViewModel>();
phraseEditViewModelMock.Setup(vm => vm.LoadPhrase(It.IsAny<int>()))
.Callback<int?>(phraseId =>
{
phraseEditViewModelMock.Setup(vm => vm.Phrase)
.Returns(new Phrase());
});
_phraseEditViewModelMock = phraseEditViewModelMock; //field = var(!!)
return phraseEditViewModelMock.Object;
}
[Fact]
public void LoadGroups_ShouldLoadOnce_True()
{
_viewModel.LoadGroups(); //loads groups twice
_viewModel.LoadGroups();
Assert.Equal(3, _viewModel.Groups.Count); //counts how many groups are loaded
}
[Fact]
public void LoadGroups_ShouldLoad_True()
{
_viewModel.LoadGroups(); //loads collection of groups (from setup)
Assert.Equal(3, _viewModel.Groups.Count); //counts groups
var phrase = _viewModel.Groups[0];
Assert.NotNull(phrase);
Assert.Equal("Group #1", phrase); //compares group name
}
[Fact]
public void AddPhrase_ShouldBeExecuted_True()
{
_viewModel.PhraseEdit = false; //set up PhraseEdit prop
_viewModel.AddPhraseCommand.Execute(null); // executes command
Assert.True(_viewModel.PhraseEdit); //verifies PhraseEdit prop
_phraseEditViewModelMock.Verify(vm => vm.LoadPhrase(null), Times.Once); //counts loaded phrases
}
[Fact]
public void LoadFromFile_ShouldConvertReturnedCorrectFormatString_ReturnsPhraseList()
{
_viewModel.LoadFromFile("goodData.csv"); //loads phrases from the file
Assert.Equal(2, _viewModel.LoadedPhrases.Count); //counts loaded phrases from the file
var phrase = _viewModel.LoadedPhrases[0];
Assert.NotNull(phrase); //checks if phrase is not null, below compares props
Assert.Equal("name1", phrase.Name);
Assert.Equal("def1", phrase.Definition);
Assert.Equal("cat1", phrase.Category);
Assert.Equal("gr1", phrase.Group);
Assert.Equal("prio1", phrase.Priority);
}
[Fact]
public void PopulateDb_ShouldSeedDbWithPhrases_CallsDpSavePhrase()
{
_viewModel.LoadedPhrases = phrases; //populates collection
_viewModel.PopulateDb(_viewModel.LoadedPhrases); //populates Db with phase list - 1 item
_mainDataProviderMock.Verify(dp => dp.SavePhrase(It.IsAny<Phrase>()), Times.Once); //counts saved phrases
}
[Fact]
public void LoadFile_ShouldBeExecuted_CallsOnLoadFileExecute()
{
_viewModel.LoadFile.Execute(null); //execute command
Assert.Equal(2, _viewModel.LoadedPhrases.Count()); //counts loaded phrases from the file
Assert.Equal(3, _viewModel.Groups.Count); //counts loaded groups
_mainDataProviderMock.Verify(dp => dp.SavePhrase(It.IsAny<Phrase>()), Times.AtLeast(2)); //counts saved phrases
}
[Fact]
public void PopulateDb_ShouldSeedDbOnce_True()
{
_viewModel.LoadedPhrases = phrases; //populates collection
_viewModel.PopulateDb(_viewModel.LoadedPhrases); //seeds Db twice
_viewModel.PopulateDb(_viewModel.LoadedPhrases);
_mainDataProviderMock.Verify(dp => dp.SavePhrase(It.IsAny<Phrase>()), Times.Once); //should seed only once
}
[Fact]
public void LoadFromFile_WithFilePathParameterIsNull_ReturnsEmptyCollection()
{
List<Phrase> expected = new List<Phrase>();
expected.Clear(); //expectations
List<Phrase> method = _viewModel.LoadFromFile("");//loads phrases from the file with empty path parameter
_viewModel.LoadFromFile(""); //loads phrases from the file with empty path string
Assert.Empty(_viewModel.LoadedPhrases); // check if LoadedPhrases is empty
Assert.Equal(expected, method); //compare expectations with method returns
}
[Fact]
public void PopulateDb_GetsEmptyCollectionParameter_DoesNothing()
{
_viewModel.LoadedPhrases.Clear(); //collection is empty
_viewModel.PopulateDb(_viewModel.LoadedPhrases); //PopulateDb with empty collection
_mainDataProviderMock.Verify(dp => dp.SavePhrase(It.IsAny<Phrase>()), Times.Never); //with empty collection SavePhrase runs never
}
[Fact]
public void LoadFromFile_GetsPathToEmptyFile_ReturnsEmptyCollection()
{
List<Phrase> expected = new List<Phrase>();
expected.Clear(); //expectations
List<Phrase> method = _viewModel.LoadFromFile("emptyData.csv"); //loads phrases from the file with empty content
Assert.Empty(_viewModel.LoadedPhrases); // check if LoadedPhrases is empty
Assert.Equal(expected, method); //compare expectations with method returns
}
//TODO:
//zły format pliku
//brak | w pliku
}
</code></pre>
<p><a href="https://github.com/przemyslawbak/Flashcards/blob/master/Flascards.UnitTests/ViewModels/MainPageViewModelTests.cs" rel="nofollow noreferrer">Tested View Model class</a>:</p>
<pre><code>public interface IMainPageViewModel
{
void LoadGroups();
}
public class MainPageViewModel : ViewModelBase, IMainPageViewModel
{
List<Phrase> oldPhrases = new List<Phrase>(); //verification for PopulateDb method;
private Func<IPhraseEditViewModel> _phraseEditVmCreator;
private IMainDataProvider _dataProvider;
public string FileLocation { get; set; }
public ObservableCollection<string> Groups { get; set; }
public List<Phrase> LoadedPhrases { get; set; }
public bool PhraseEdit { get; set; }
public IPhraseEditViewModel SelectedPhraseEditViewModel { get; set; }
public MainPageViewModel(IMainDataProvider dataProvider,
Func<IPhraseEditViewModel> phraseditVmCreator) //ctor
{
_dataProvider = dataProvider;
_phraseEditVmCreator = phraseditVmCreator;
Groups = new ObservableCollection<string>();
LoadedPhrases = new List<Phrase>();
//commands tests
AddPhraseCommand = new DelegateCommand(OnNewPhraseExecute);
LoadFile = new DelegateCommand(OnLoadFileExecute);
}
public ICommand AddPhraseCommand { get; private set; }
public ICommand LoadFile { get; private set; }
private void OnNewPhraseExecute(object obj)
{
SelectedPhraseEditViewModel = CreateAndLoadPhraseEditViewModel(null);
}
private IPhraseEditViewModel CreateAndLoadPhraseEditViewModel(int? phraseId)
{
//Application.Current.MainPage.Navigation.PushAsync(new PhraseEditPage());
var phraseEditVm = _phraseEditVmCreator();
PhraseEdit = true;
phraseEditVm.LoadPhrase(phraseId);
return phraseEditVm;
}
private async void OnLoadFileExecute(object obj)
{
LoadedPhrases.Clear();
FileLocation = await _dataProvider.PickUpFile();
LoadedPhrases = LoadFromFile(FileLocation);
PopulateDb(LoadedPhrases);
LoadGroups();
}
public void LoadGroups() //loads group list from the DB
{
Groups.Clear();
foreach (var group in _dataProvider.GetGroups())
{
Groups.Add(group);
}
}
public List<Phrase> LoadFromFile(string filePath)
{
if (filePath != "")
{
string stream = "";
LoadedPhrases.Clear();
stream = _dataProvider.GetStreamFromCSV(filePath);
Dictionary<string, int> myPhraseMap = new Dictionary<string, int>(); //exception for wrong format
var sr = new StringReader(stream);
using (var csv = new CsvReader(sr, true, '|'))
{
int fieldCount = csv.FieldCount;
string[] headers = csv.GetFieldHeaders();
for (int i = 0; i < fieldCount; i++)
{
myPhraseMap[headers[i]] = i;
}
while (csv.ReadNextRecord())
{
Phrase phrase = new Phrase
{
Name = csv[myPhraseMap["Name"]],
Definition = csv[myPhraseMap["Definition"]],
Category = csv[myPhraseMap["Category"]],
Group = csv[myPhraseMap["Group"]],
Priority = csv[myPhraseMap["Priority"]],
Learned = false
};
LoadedPhrases.Add(phrase);
}
}
}
else
{
LoadedPhrases.Clear();
}
return LoadedPhrases;
}
public void PopulateDb(List<Phrase> phrases)
{
if (oldPhrases != phrases) //populates only if collection is new
{
foreach (var item in phrases)
{
_dataProvider.SavePhrase(item);
}
oldPhrases = phrases;
}
}
}
</code></pre>
<p><a href="https://github.com/przemyslawbak/Flashcards/tree/master/Flashcards/Flashcards" rel="nofollow noreferrer">GitHub repository of the project</a></p>
| [] | [
{
"body": "<h2><code>MainPageViewModel</code></h2>\n\n<p>You provide an interface with a single method:</p>\n\n<blockquote>\n<pre><code>public interface IMainPageViewModel\n{\n void LoadGroups();\n}\n</code></pre>\n</blockquote>\n\n<p>Yet, the implementation provides a rich set of public members:</p>\n\n<blockquote>\n<pre><code>public string FileLocation { get; set; }\npublic ObservableCollection<string> Groups { get; set; }\npublic List<Phrase> LoadedPhrases { get; set; }\npublic bool PhraseEdit { get; set; }\npublic IPhraseEditViewModel SelectedPhraseEditViewModel { get; set; }\n// and so on ..\n</code></pre>\n</blockquote>\n\n<p>I'm not a fan of this, because this means there is a clear difference between the public API of the implementation and its interface. Perhaps some of these members are specific to the implementation, but surely <code>ObservableCollection<string> Groups { get; }</code> should be part of the interface. Or <code>IReadOnlyCollection<string></code> if only readonly mode is allowed. I guess the former would be required for your use cases.</p>\n\n<p>You are mixing naming conventions lowercase <code>oldPhrases</code> vs _lowercase <code>_dataProvider</code>. Stick to a single standard.</p>\n\n<p>Be careful designing mutable properties <code>ObservableCollection<string> Groups { get; set; }</code>. It allows consumers to bypass the interface method <code>LoadGroups()</code> to set <code>Groups</code>. This might be considered a breach of encapsulation. Also, a null reference can easily occur:</p>\n\n<blockquote>\n<pre><code>public void LoadGroups()\n{\n Groups.Clear(); // possible NullReferenceException\n foreach (var group in _dataProvider.GetGroups())\n {\n Groups.Add(group);\n }\n}\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://stackoverflow.com/questions/43167307/how-to-use-async-method-in-delegatecommand\">There is alot to say</a> about <code>DelegateCommand</code> using an <code>async void</code> action like <code>OnLoadFileExecute</code>. I would opt to use a (custom) <code>AsyncDelegateCommand</code> that takes a <code>Task</code> instead, optionally with a nested <code>CancelCommand</code>.</p>\n\n<p>Method <code>LoadFromFile</code> mixes IO, mapping and changing instance state. This might be a bit too much for a single method. Consider splitting this up in classes/methods that each have their own responsibility. Readability could also be improved by inverting the if-statement with an early exit to avoid deep nested statements. </p>\n\n<pre><code>if (string.IsNullOrEmpty(filePath))\n{\n LoadedPhrases.Clear(); // assuming the instance can never be null\n Clear();\n return;\n}\n\n// remaining method body ..\n</code></pre>\n\n<p>If <code>filePath</code> is null, you probably get an annoying exception, so prefer <code>string.IsNullOrEmpty</code> over <code>!= \"\"</code>.</p>\n\n<p>Use <code>var</code> when the type is obvious to write more compact and clean code: <code>Phrase phrase = new Phrase(..</code> -> <code>var phrase = new Phrase(..</code>.</p>\n\n<p><code>PopulateDb</code> doesn't seem right. You check on reference equality of the collections. But what if a different stores the same or some of the same items? You would save certain items more than once: <code>_dataProvider.SavePhrase(item);</code> -> if the item is also contained in <code>oldPhrases</code>. You have many unit tests, but in TDD you should also find these edge cases I would expect.</p>\n\n<blockquote>\n<pre><code>if (oldPhrases != phrases) //populates only if collection is new\n</code></pre>\n</blockquote>\n\n<h2><code>MainPageViewModelTests</code></h2>\n\n<p>You have written <a href=\"https://en.wikipedia.org/wiki/White-box_testing\" rel=\"nofollow noreferrer\">white-box tests</a>, and you've done it the correct way. The only class you instantiate is the class under test:</p>\n\n<blockquote>\n<pre><code>_viewModel = new MainPageViewModel(..\n</code></pre>\n</blockquote>\n\n<p>While other dependencies get mocked:</p>\n\n<blockquote>\n<pre><code>_phraseEditViewModelMock = new Mock<IPhraseEditViewModel>();\n_mainDataProviderMock = new Mock<IMainDataProvider>();\n</code></pre>\n</blockquote>\n\n<p>Allowing for tests against the dependencies without needing to worry about any of their possible implementations:</p>\n\n<blockquote>\n<pre><code>_phraseEditViewModelMock.Verify(vm => vm.LoadPhrase(null), Times.Once);\n</code></pre>\n</blockquote>\n\n<p>However, you did not write any significant number of <a href=\"https://en.wikipedia.org/wiki/Black-box_testing\" rel=\"nofollow noreferrer\">black-box tests</a>: tests where you check output given some input. By writing more of these tests for edge cases in particular, you would have found a couple of <code>NullReferenceException</code> errors.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-28T19:44:43.927",
"Id": "229816",
"ParentId": "216079",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T21:49:02.587",
"Id": "216079",
"Score": "3",
"Tags": [
"c#",
"unit-testing",
"xamarin",
"moq"
],
"Title": "TDD test class for ViewModel class"
} | 216079 |
<p>I'm looking for some feedback regarding my implementation of a generic singly-linked list in C#. I'm also looking for some tips on how to implement other techniques such as using <code>IEnumerable</code> or other .NET interfaces I'm currently not aware of.</p>
<p>Node.cs</p>
<pre class="lang-c prettyprint-override"><code>using System;
namespace SinglyLinkedLists
{
public class Node<T>
{
private Node<T> _next;
private T _data;
public Node<T> next{
get { return _next; }
set { _next = value; }
}
public T data{
get { return _data; }
set { _data = value; }
}
public Node(T newData){
this._data = newData;
this._next = null;
}
public static void printNodes(Node<T> head){
Node<T> currentNode = head;
while (currentNode != null){
Console.WriteLine(currentNode.data);
currentNode = currentNode.next;
}
}
}
}
</code></pre>
<p>SinglyLinkedLists.cs</p>
<pre class="lang-c prettyprint-override"><code>using System;
namespace SinglyLinkedLists
{
public class SinglyLinkedLists<T>
{
private Node<T> head;
private Node<T> previous;
private Node<T> current;
private Node<T> tail;
private int numberOfNodes = 0;
public SinglyLinkedLists()
{
head = null;
previous = null;
current = null;
tail = null;
}
public void PrintList(){
Node<T> current = head;
while (current != null){
Console.WriteLine(current.data);
current = current.next;
}
}
public void AddLast(T data){
Node<T> newNode = new Node<T>(data);
if (tail == null){
head = tail = newNode;
}
else{
tail.next = newNode;
tail = newNode;
}
numberOfNodes++;
}
public void AddLastTwo(T data){
Node<T> newNode = new Node<T>(data);
if (head == null){
head = newNode;
}
else{
current = head;
while (current.next != null){
current = current.next;
}
current.next = newNode;
}
numberOfNodes++;
}
public void RemoveNode(T data){
Node<T> nodeToRemove = new Node<T>(data);
current = head;
if(head.data.Equals(nodeToRemove.data)){
current = head.next;
head = current;
}
else{
while (current != null){
if (current.data.Equals(nodeToRemove.data)) {
previous.next = current.next;
current = previous;
}
else{
previous = current;
current = current.next;
}
}
}
numberOfNodes--;
}
public int ListSize(){
return numberOfNodes;
}
public bool InList(T data){
Node<T> nodeToLookFor = new Node<T>(data);
Node<T> current = head;
while (current != null){
if (current.data.Equals(nodeToLookFor.data)){
return true;
}
current = current.next;
}
return false;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T22:25:42.053",
"Id": "418105",
"Score": "6",
"body": "_I'm also looking for some tips on how to implement [..]_ - You should remove this request from your question as it makes it off-topic because we are not implementing new features for you. But if you already know about `IEnumerable` why don't you add it yourself?"
}
] | [
{
"body": "<p>A few things that stuck out to me:</p>\n\n<p>You don't gain anything by having the <code>Node</code> class public. The user of your linked list should only need to be concerned about the data.</p>\n\n<p>It seems very illogical to me to have the <code>Node</code> class printing the <code>LinkedList</code>. This should more properly be only part of the <code>LinkedList</code> itself. It would probably be advantageous though for the <code>Node</code> class to override the <code>ToString()</code> method to make it easier to print the data.</p>\n\n<p>From a quick perusal, I couldn't see any use for the <code>previous</code> property except in the <code>RemoveNode</code> method. I would suggest keeping it local to that method.</p>\n\n<p>A comment explaining the purpose of the <code>AddLastTwo</code> method. To me it appears to iterate over the list to find the last node, instead of using the <code>last</code> property of the class, like the <code>AddLast</code>.</p>\n\n<p>To me names like <code>AddLast</code> and <code>RemoveNode</code> are over complicated. If a node isn't being added to the end then it would be an insert operation not an add. It shouldn't be necessary to tell the user that it's being added to the end. Likewise the user doesn't need to know that the data is stored in a node, they are simply concerned with removing the data.</p>\n\n<p>When you are using default <code>get</code> and <code>set</code> methods it's much easier to use the default syntax:</p>\n\n<pre><code>public Node<T> next{get;set;}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T02:30:52.667",
"Id": "216091",
"ParentId": "216081",
"Score": "2"
}
},
{
"body": "<p>This is a small answer but is kind of important in my opinion. <code>bool InList(T data)</code> and <code>int ListSize()</code> are existing patterns among .Net classes, they should be named <code>Contains</code> and <code>Count</code>. The lesson to come out of this is that you should try to reuse common names when the pattern fits.</p>\n\n<p>Also, your class name shouldn't be pluralized. <code>SinglyLinkedLists</code> -> <code>SinglyLinkedList</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T13:43:38.467",
"Id": "216338",
"ParentId": "216081",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T22:10:55.160",
"Id": "216081",
"Score": "2",
"Tags": [
"c#",
"beginner",
".net",
"linked-list",
"reinventing-the-wheel"
],
"Title": "Generic Singly-Linked List implementation"
} | 216081 |
<p>This is a simple C clone of the website <a href="https://hackertyper.net" rel="nofollow noreferrer">hackertyper.net</a>. The code can be found on <a href="https://github.com/Hurricane996/hackertyper" rel="nofollow noreferrer">Github</a> and is reproduced below:</p>
<h1>Makefile</h1>
<pre><code>PREFIX=/usr/local
BINDIR=$(PREFIX)/bin
DATAROOTDIR=$(PREFIX)/share
DATADIR=$(DATAROOTDIR)
MAN1DIR=$(DATAROOTDIR)/man/man1
CFLAGS=-Wall -pedantic -std=c99
LDFLAGS=-lncurses
all: hackertyper
.PHONY: all clean install
hackertyper: hackertyper.o
cc -o $@ $^ $(LDFLAGS)
hackertyper.o: src/hackertyper.c
cc -c $(CFLAGS) -o $@ $^
src/hackertyper.c: src/hackertyper.h
src/hackertyper.h:src/hackertyper.h.in
sed "s@%datadir%@$(DATADIR)@g" src/hackertyper.h.in > src/hackertyper.h
clean:
rm -f hackertyper{,.o} src/hackertyper.h
install:
install -D -m644 data/hackertyper.txt $(DATADIR)/hackertyper.txt
install -D -m644 man/hackertyper.1 $(MAN1DIR)/hackertyper.1
install -D -m755 hackertyper $(BINDIR)/hackertyper
</code></pre>
<h1>src/hackertyper.c</h1>
<pre><code>#include "hackertyper.h"
char* filename;
FILE* file;
char chars_per_nl = 1;
int main(int argc, char* argv[]) {
parse_args(argc, argv);
if(open_file(filename) == -1){
return -1;
}
init();
int clear_msg_flag = 0;
nc_color_green();
int running = 1;
while(running) {
// buffer here so that buffering happens before clear_msg
int input_ch = getch();
// message was drawn last time and we need to clear it
if(clear_msg_flag) {
clear_msg_flag = 0;
clear_msg();
}
switch(input_ch){
//C-c
case 3:
running = 0;
break;
//C-d
case 4:
clear();
nc_color_red();
draw_msg("ACCESS DENIED");
clear_msg_flag = 1;
break;
// C-g
case 7:
clear();
nc_color_green();
draw_msg("ACCESS GRANTED");
clear_msg_flag = 1;
break;
case KEY_BACKSPACE:
backspace();
break;
default:
for(int i = 0; i < 5; i++) {
int output_ch = fgetc(file);
if(output_ch == EOF) {
rewind(file);
output_ch = fgetc(file);
}
if(output_ch != '\r')
addch(output_ch);
}
refresh();
break;
}
}
end();
}
void parse_args(int argc, char* argv[]) {
if(argc > 1) {
for(int i = 0; i < argc; i++) {
if(strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
printf(HELP_TEXT);
exit(0);
}
if(strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) {
printf(VERSION_TEXT);
exit(0);
}
if(strcmp(argv[i], "-f") == 0) {
if(i+1 >= argc) {
fprintf(stderr, HELP_TEXT);
exit(-1);
}
filename = argv[i+1];
}
}
}
}
int open_file(char* filename) {
filename = filename ? filename : default_filename;
file = fopen(filename, "r");
return file == NULL ? -1 : 0;
}
void init(){
initscr();
raw();
noecho();
scrollok(stdscr, true);
keypad(stdscr, true);
// check line endings
// TODO: expand this to work with endings besides \n and \r\n
char ch;
while(ch !='\n' && ch !='\r'){
ch = fgetc(file);
}
if (ch == '\r') {
chars_per_nl = 2;
}
rewind(file);
if(has_colors()){
start_color();
init_pair(1, COLOR_GREEN, COLOR_BLACK);
init_pair(2, COLOR_RED, COLOR_BLACK);
}
}
void nc_color_green(){
if(has_colors()){
attroff(COLOR_PAIR(2));
attron(COLOR_PAIR(1));
}
}
void nc_color_red(){
if(has_colors()){
attroff(COLOR_PAIR(1));
attron(COLOR_PAIR(2));
}
}
void nc_color_default(){
if(has_colors()){
attroff(COLOR_PAIR(1));
attroff(COLOR_PAIR(2));
}
}
void backspace(){
fseek(file,-1 ,SEEK_CUR);
int x,y;
getyx(stdscr,y,x);
if(x == 0) {
if( y == 0 ) {
return;
}
x = getmaxx(stdscr);
// set x to x minus 1
move(--y,--x);
char ch = ' ';
while(ch == ' ' && x != 0){
move(y,--x);
ch=inch();
}
fseek(file, -chars_per_nl, SEEK_CUR);
} else {
move(y,x-1);
}
delch();
}
void draw_msg(char* msg) {
int len = strlen(msg);
unsigned char hash = '#';
unsigned char space = ' ';
int w;
int h;
getmaxyx(stdscr, h, w);
move(h/2 - 2, w/2 - len/2 - 3);
for(int i = 0; i < len + 6; i ++)
addch(hash);
move(h/2 - 1, w/2 - len/2 - 3);
addch(hash);
for(int i = 0; i < len + 4; i ++)
addch(space);
addch(hash);
move(h/2, w/2 - len/2 - 3);
printw("# %s #", msg);
move(h/2 + 1, w/2 - len/2 - 3);
addch(hash);
for(int i = 0; i < len + 4; i ++)
addch(space);
addch(hash);
move(h/2 + 2, w/2 - len/2 - 3);
for(int i = 0; i < len + 6; i ++)
addch(hash);
}
void clear_msg(){
nc_color_green();
clear();
move(0, 0);
// seek file to next line
int ch = 0;
while(ch != '\n'){
ch = fgetc(file);
}
}
void end(){
endwin();
fclose(file);
}
</code></pre>
<h1>src/hackertyper.h.in</h1>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
#include <string.h>
#define default_filename "%datadir%/hackertyper.txt"
#define HELP_TEXT "\
Usage: hackertyper [-f file] [-h] [-v]\n\
Print text from file to stdout on pressing keys, similar to behavior of website https://www.hackertyper.org/\n\
\n\
Options:\n\
-f FILE, --filename FILE Print text from FILE rather than from default file\n\
-h, --help Print this help string\n\
-v, --version Print version information\n\
"
#define VERSION_TEXT "\
hackertyper 2.1\n\
Copyright (C) 2019 Lani Willrich\n\
License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>\n\
This is free software: you are free to change and redistribute it.\n\
There is NO WARRANTY, to the extent permitted by law.\n\
Written by Lani Willrich\n\
"
void parse_args(int argc,char* argv[]);
int open_file(char* filename);
void init();
void nc_color_red();
void nc_color_green();
void nc_color_default();
void backspace();
void draw_msg(char* msg);
void clear_msg();
void end();
</code></pre>
<p>Some irrelevant files have not been listed including an auto-generated man page and the data files.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T22:51:28.927",
"Id": "216082",
"Score": "5",
"Tags": [
"c"
],
"Title": "C clone of Hackertyper.net"
} | 216082 |
<p>This program draws a random music note on a staff, refreshing the note every second. It compiles with g++ and also emscripten, so it is runnable in both the browser and on desktop.</p>
<p>This is my first attempt at graphics programming, so I'm not interested in feedback on how I'm using OpenGL. In particular, I'm vaguely considered that I'm using shaders poorly. Do I really write a new shader program for each sort of thing I have to draw?</p>
<p>My code seems tightly coupled to OpenGL. I would really love tips to make this less coupled.</p>
<p>This code uses <a href="https://github.com/tomdalling/opengl-series/blob/master/source/02_textures/source/tdogl/Bitmap.h" rel="nofollow noreferrer">Bitmap.h</a>, <a href="https://github.com/tomdalling/opengl-series/blob/master/source/02_textures/source/tdogl/Bitmap.cpp" rel="nofollow noreferrer">Bitmap.cpp</a>, <a href="https://github.com/tomdalling/opengl-series/blob/master/source/common/platform.hpp" rel="nofollow noreferrer">platform.hpp</a>, and <a href="https://github.com/tomdalling/opengl-series/blob/master/platforms/linux/platform_linux.cpp" rel="nofollow noreferrer">platform_linux.cpp</a> by Thomas Dalling. These files assume that <a href="https://github.com/nothings/stb/blob/master/stb_image.h" rel="nofollow noreferrer">stb_image.h</a> is located on the system include path. <code>shader.cpp</code> is modified from the shader code in <a href="http://www.opengl-tutorial.org/beginners-tutorials/tutorial-2-the-first-triangle/" rel="nofollow noreferrer">this tutorial</a>, but it's just standard shader-loading code. This project uses a unity build.</p>
<p>Output:
<a href="https://i.stack.imgur.com/TZFHI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TZFHI.png" alt="Program output"></a></p>
<p><strong>Makefile</strong></p>
<pre><code>all: a.out index.html
EMS_OPTS = -s FULL_ES3=1 \
-s WASM=1 \
-s NO_EXIT_RUNTIME=1 \
-s USE_GLFW=3 \
-s USE_LIBPNG=1 \
-DEMSCRIPTEN
CXX_FLAGS = -Wall -Wextra -std=c++17
LD_LFAGS = -lGL -lGLU -lglfw -lGLEW -lpng
index.html: main.cpp Drawable.cpp Drawable.h
emcc main.cpp -o index.html ${CXX_FLAGS} ${EMS_OPTS} --preload-file resources/whole-note.png
a.out: main.cpp Drawable.cpp Drawable.h
g++ -g main.cpp ${CXX_FLAGS} ${LD_LFAGS}
</code></pre>
<p><strong>Drawable.h</strong></p>
<pre><code>#ifndef DRAWABLE_H_
#define DRAWABLE_H_
#include <chrono>
#include <memory>
#include <vector>
class Drawable
{
public:
virtual ~Drawable() {}
virtual void draw() const = 0;
virtual void update() {};
Drawable(const Drawable& other) = delete;
Drawable& operator=(const Drawable& other) = delete;
Drawable() {}
};
class Note : public Drawable
{
public:
Note(GLuint program);
~Note();
virtual void draw() const;
void setY(double value);
private:
GLuint vao, vbo, ibo, texture, program;
};
class Staff : public Drawable
{
public:
Staff(GLuint program, Note& note);
~Staff();
virtual void draw() const;
virtual void update();
private:
GLuint vao, vbo, program;
static const GLfloat points[30];
Note& note;
std::chrono::time_point<std::chrono::system_clock> start;
std::vector<float> valid_positions;
};
#endif
</code></pre>
<p><strong>Drawable.cpp</strong></p>
<pre><code>#include <algorithm>
#include <random>
#include "Drawable.h"
namespace
{
GLfloat vertices[] = {
// X, Y, Z U, V
0.2, 0.0, 0.0, 1.0, 1.0,
-0.2, 0.0, 0.0, 0.0, 1.0,
0.2, 0.0, 0.0, 1.0, 0.0,
-0.2, 0.0, 0.0, 0.0, 0.0,
};
}
Note::Note(GLuint program) :
program(program)
{
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// X, Y, Z (dest) coordinates
glVertexAttribPointer(0,
3,
GL_FLOAT,
GL_FALSE,
5 * sizeof(GL_FLOAT),
NULL);
glEnableVertexAttribArray(0);
// U, V (src) coordinates
glVertexAttribPointer(1,
2,
GL_FLOAT,
GL_FALSE,
5 * sizeof(GL_FLOAT),
(const GLvoid *)(3 * sizeof(GL_FLOAT)));
glEnableVertexAttribArray(1);
// TODO: Pass this in?
auto bmp = tdogl::Bitmap::bitmapFromFile(ResourcePath("whole-note.png"));
bmp.flipVertically();
// Index buffer object
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
static const GLuint indexData[] = {
0, 1, 2,
2, 1, 3
};
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indexData), indexData,
GL_STATIC_DRAW);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,
0,
GL_RGBA,
(GLsizei)bmp.width(),
(GLsizei)bmp.height(),
0,
GL_RGBA,
GL_UNSIGNED_BYTE, bmp.pixelBuffer());
glBindTexture(GL_TEXTURE_2D, 0);
}
void Note::setY(double value)
{
static const float HALF_DIM = .2;
vertices[1] = value + HALF_DIM;
vertices[6] = value + HALF_DIM;
vertices[11] = value - HALF_DIM;
vertices[16] = value - HALF_DIM;
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
Note::~Note()
{
glDeleteProgram(program);
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ibo);
glDeleteVertexArrays(1, &vao);
glDeleteTextures(1, &texture);
}
void Note::draw() const
{
glUseProgram(program);
glBindVertexArray(vao);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
GLint uniform = glGetUniformLocation(program, "texture_");
glUniform1i(uniform, 0);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
}
Staff::Staff(GLuint program, Note& note) :
program(program),
note(note),
start(std::chrono::system_clock::now()),
valid_positions{.5, .55, .6, .65, .7, .75, .8, .85}
{
note.setY(valid_positions[0]);
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW);
glVertexAttribPointer(
0,
3,
GL_FLOAT,
GL_FALSE,
0,
(void*)0
);
glEnableVertexAttribArray(0);
glBindVertexArray(0);
}
Staff::~Staff()
{
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
glDeleteProgram(program);
}
void Staff::draw() const
{
glUseProgram(program);
glBindVertexArray(vao);
glDrawArrays(GL_LINES, 0, 10);
note.draw();
}
const GLfloat Staff::points[30] = {
-1.0f, 0.9f, 0.0f,
1.0f, 0.9f, 0.0f,
-1.0f, 0.8f, 0.0f,
1.0f, 0.8f, 0.0f,
-1.0f, 0.7f, 0.0f,
1.0f, 0.7f, 0.0f,
-1.0f, 0.6f, 0.0f,
1.0f, 0.6f, 0.0f,
-1.0f, 0.5f, 0.0f,
1.0f, 0.5f, 0.0f,
};
void Staff::update()
{
const auto current_time = std::chrono::system_clock::now();
const auto duration = std::chrono::duration_cast<std::chrono::seconds>(current_time - start).count();
if (duration >= 1)
{
start = std::chrono::system_clock::now();
std::vector<float> new_position;
std::sample(valid_positions.begin(), valid_positions.end(),
std::back_inserter(new_position), 1,
std::mt19937{std::random_device{}()});
note.setY(new_position[0]);
}
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <memory>
#ifdef EMSCRIPTEN
#include <GLES3/gl3.h>
#include "emscripten.h"
#else
#include <GL/glew.h>
#include <unistd.h>
#endif
#include <GLFW/glfw3.h>
#include "platform_linux.cpp"
#include "Bitmap.h"
#include "Bitmap.cpp"
#include "shader.hpp"
#include "shader.cpp"
#include "Drawable.h"
#include "Drawable.cpp"
#define FRAMES_PER_SECOND 30
#ifdef EMSCRIPTEN
static const char* noteVertSource = "\
precision mediump float;\n\
attribute vec4 position;\n\
attribute vec2 verTexCoord;\n\
varying vec2 fragTexCoord;\n\
void main()\n\
{\n\
fragTexCoord = verTexCoord;\n\
gl_Position = position;\n\
}";
static const char* noteFragSource = "\
precision mediump float;\n\
uniform sampler2D texture_;\n\
varying vec2 fragTexCoord;\n\
void main()\n\
{\n\
gl_FragColor = texture2D(texture_, fragTexCoord);\n\
}";
#else
static const char* noteVertSource = "\
attribute vec4 position;\n\
attribute vec2 verTexCoord;\n\
varying vec2 fragTexCoord;\n\
void main()\n\
{\n\
fragTexCoord = verTexCoord;\n\
gl_Position = position;\n\
}";
static const char* noteFragSource = "\
uniform sampler2D texture_;\n\
varying vec2 fragTexCoord;\n\
void main()\n\
{\n\
gl_FragColor = texture2D(texture_, fragTexCoord);\n\
}";
#endif
static const char* vertSource = "\
#ifdef EMSCRIPTEN\n\
precision mediump float;\n\
#endif\n\
attribute vec4 position;\n\
void main()\n\
{\n\
gl_Position = position;\n\
}";
static const char* fragSource = "\
#ifdef EMSCRIPTEN\n\
precision mediump float;\n\
#endif\n\
void main()\n\
{\n\
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n\
}";
void GLAPIENTRY
MessageCallback( GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam )
{
(void) source;
(void) id;
(void) length;
(void) userParam;
const char *repr = type == GL_DEBUG_TYPE_ERROR ? "** GL ERROR **" : "";
fprintf(stderr, "GL CALLBACK: %s type = 0x%x, severity = 0x%x, message = %s\n",
repr, type, severity, message );
}
class GLFWContext
{
public:
GLFWContext(size_t width, size_t height, const char *name)
{
// Initialise GLFW
if( !glfwInit() )
{
throw std::runtime_error("Failed to initialize GLFW");
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Open a window and create its OpenGL context
window = glfwCreateWindow(width, height, name, nullptr, nullptr);
if (!window)
{
glfwTerminate();
throw std::runtime_error("Failed to open GLFW window. "\
"If you have an Intel GPU, they are not 3.3 compatible. "\
"Try the 2.1 version of the tutorials.\n");
}
glfwMakeContextCurrent(window);
}
~GLFWContext()
{
glfwDestroyWindow(window);
glfwTerminate();
}
bool isActive()
{
return glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
glfwWindowShouldClose(window) == 0;
}
void update()
{
glfwSwapBuffers(window);
glfwPollEvents();
}
private:
GLFWwindow* window;
};
class Game : public Drawable
{
public:
Game(GLFWContext& glfw) : glfw(glfw) {}
virtual void draw() const
{
glClear(GL_COLOR_BUFFER_BIT);
for (auto& object : objects)
object->draw();
}
inline void add(std::unique_ptr<Drawable> object)
{
objects.push_back(std::move(object));
}
virtual void update()
{
for (auto& object : objects) object->update();
glfw.update();
}
private:
GLFWContext& glfw;
std::vector<std::unique_ptr<Drawable>> objects;
};
void main_loop(void* arg)
{
#ifndef EMSCRIPTEN
const auto start = std::clock();
#endif
Game *game = (Game *)arg;
assert(game);
game->draw();
game->update();
unsigned int err = 0;
while ( (err = glGetError()) )
{
std::cerr << err << "\n";
}
#ifndef EMSCRIPTEN
const auto seconds_elapsed = (std::clock() - start) /
static_cast<double>(CLOCKS_PER_SEC);
if (seconds_elapsed < 1.0 / FRAMES_PER_SECOND)
{
usleep(1000000 * (1.0 / FRAMES_PER_SECOND - seconds_elapsed));
}
#endif
}
int main( void )
{
GLFWContext context(1024, 768, "Music game");
// Initialize GLEW
#ifndef EMSCRIPTEN
glewExperimental = true; // Needed for core profile
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
return -1;
}
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(MessageCallback, 0);
#endif
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0.9f, 0.9f, 0.9f, 1.0f);
// Create and compile our GLSL program from the shaders
const GLuint linesProgram = LoadShaders(vertSource, fragSource);
const GLuint noteProgram = LoadShaders(noteVertSource, noteFragSource);
Game game(context);
Note note(noteProgram);
note.setY(.75);
game.add(std::unique_ptr<Drawable>(
new Staff(linesProgram, note)));
#ifdef EMSCRIPTEN
emscripten_set_main_loop_arg(main_loop, &game, FRAMES_PER_SECOND, 1);
#else
do{
main_loop(&game);
} while (context.isActive());
#endif
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T10:05:24.907",
"Id": "418661",
"Score": "0",
"body": "This looks very interesting, can you add some images so it attracts more people to answer. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T21:44:05.437",
"Id": "418746",
"Score": "0",
"body": "@422_unprocessable_entity Thank you for the advice. Edited."
}
] | [
{
"body": "<h2>Advice</h2>\n<p>Rather than use escaped characters.</p>\n<pre><code>static const char* noteVertSource = "\\\nprecision mediump float;\\n\\\nattribute vec4 position;\\n\\\nattribute vec2 verTexCoord;\\n\\\nvarying vec2 fragTexCoord;\\n\\\nvoid main()\\n\\\n{\\n\\\n fragTexCoord = verTexCoord;\\n\\\n gl_Position = position;\\n\\\n}";\n</code></pre>\n<p>You can now use RAW strings:</p>\n<pre><code>static const char* noteVertSource = R"FUNC(\nprecision mediump float;\nattribute vec4 position;\nattribute vec2 verTexCoord;\nvarying vec2 fragTexCoord;\nvoid main()\n{\n fragTexCoord = verTexCoord;\n gl_Position = position;\n};\n)FUNC";\n</code></pre>\n<p>Note: FUNC is an arbitrary string (that can be empty). It just matches the characters between <code>R"<del>(</code> and <code>)<del>"</code></p>\n<h2>Code Review:</h2>\n<p>Don't use C style casts:</p>\n<pre><code> (const GLvoid *)(3 * sizeof(GL_FLOAT)));\n</code></pre>\n<p>C++ has its own casts to make things obvious.</p>\n<pre><code>reinterpret_cast<const GLvoid *>(3 * sizeof(GL_FLOAT))\n</code></pre>\n<p>By using the C++ casts you make it easy to search for dangerous casts (like this).</p>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T04:26:33.550",
"Id": "418645",
"Score": "0",
"body": "@user1118321 You are correct (and have fixed). But the compiler would not have noticed. As the close quotes required a `)<del>\"` the other quote would have been naturally embedded in the string (which may have been an issue from some other system but not the C++ compiler)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T21:44:31.190",
"Id": "418747",
"Score": "0",
"body": "Learning about raw strings is by far the best thing to happen to me this week."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T20:11:05.400",
"Id": "216366",
"ParentId": "216083",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T23:45:58.680",
"Id": "216083",
"Score": "8",
"Tags": [
"c++",
"opengl"
],
"Title": "Note-drawing program"
} | 216083 |
<p>I completed a short coding challenge and just want to know if I should use shorter methods of which I am unaware, or make it more readable.</p>
<pre><code> /*
*
* Complete the vowelsAndConsonants function.
* Print your output using 'console.log()'.
*/
function vowelsAndConsonants(s) {
var strConsonants = "";
var strVowels = "";
var i;
for (i in s) {
if (s.charAt(i) == "a" || s.charAt(i) == "e" || s.charAt(i) == "i" ||
s.charAt(i) == "o" || s.charAt(i) == "u") {
strVowels += s.charAt(i);
}
else if (s.charAt(i) != "a" || s.charAt(i) != "e" || s.charAt(i) != "i"
|| s.charAt(i) != "o" || s.charAt(i) != "u") {
strConsonants += s.charAt(i);
}
}
// console.log(strVowels);
i = 0;
for (i in strVowels) {
console.log(strVowels.charAt(i));
}
// console.log(strConsonants);
i = 0;
for (i in strConsonants) {
console.log(strConsonants.charAt(i));
}
}
</code></pre>
| [] | [
{
"body": "<p>The shorter method can be achieved using Regex and it is also the fastest according to <a href=\"http://jsben.ch/\" rel=\"nofollow noreferrer\">JSBEN.CH</a>:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var str = \"The quick brown fox jumps over a lazy dog\";\nvar vowels = str.match(/[aeiou]/gi);\nvar consonants = str.match(/[^aeiou$]/gi);\n vowels.concat([''],consonants).forEach(function(k){\n console.log(k);\n });</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>According to comments from others, the code can be further improved as follow:</p>\n\n<pre><code>const str = \"The quick brown fox jumps over a lazy dog\"; \nconst vowels = str.match(/[aeiou]/gi); \nconst consonants = str.match(/[^aeiou]/gi); \nvowels.concat([''],consonants).forEach(k => { console.log(k); } );\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T20:38:08.227",
"Id": "418321",
"Score": "1",
"body": "There's no reason to put the `$` into the character class of the regular expression. The indentation of the last 3 lines is a bit off, but apart from this: nice solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T21:02:58.553",
"Id": "418322",
"Score": "0",
"body": "You could also use the `const` keyword for the variable declarations. And I think the callback function in the forEach method would be even a bit nicer like this `forEach( consonant => { console.log(consonant)})`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T19:36:49.663",
"Id": "216188",
"ParentId": "216086",
"Score": "4"
}
},
{
"body": "<p>Instead of providing you a \"better\" solution, I will try to give you some feedback the code.</p>\n\n<hr>\n\n<h1>Block indentation</h1>\n\n<blockquote>\n <pre><code>function vowelsAndConsonants(s) {\nvar strConsonants = \"\";\nvar strVowels = \"\";\nvar i;\n// ..\n</code></pre>\n</blockquote>\n\n<p>To work with code it is important that it is formatted in a readable way. There are some style guides out there for example <a href=\"https://google.github.io/styleguide/jsguide.html\" rel=\"noreferrer\">from google</a> </p>\n\n<pre><code>function vowelsAndConsonants(s) {\n var strConsonants = \"\";\n var strVowels = \"\";\n var i;\n // ..\n</code></pre>\n\n<hr>\n\n<h1><a href=\"https://blog.codinghorror.com/code-smells/\" rel=\"noreferrer\">Type Embedded in Name</a></h1>\n\n<pre><code>var strConsonants = \"\";\nvar strVowels = \"\";\n</code></pre>\n\n<p>In this variable names the type is embedded in the name</p>\n\n<blockquote>\n <p>Avoid placing types in method names; it's not only redundant, but it forces you to change the name if the type changes.</p>\n</blockquote>\n\n<hr>\n\n<h1><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in\" rel=\"noreferrer\">Array iteration and for...in</a></h1>\n\n<p>For your task is the order important:</p>\n\n<blockquote>\n <p>Input string, output vowels and consonants to log, separately but in order</p>\n</blockquote>\n\n<p>You can read <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in\" rel=\"noreferrer\">on MDN about the for..in loop</a>,that it do not guaranties a traversal in order:</p>\n\n<blockquote>\n <p><strong>Note</strong>: <code>for...in</code> should not be used to iterate over an Array where the index order is important. [...]</p>\n \n <p>[...] iterating over an array may not visit elements in a consistent order. Therefore, it is better to use a for loop with a numeric index (or Array.prototype.<code>forEach()</code> or the <code>for...of</code> loop) when iterating over arrays where the order of access is important.</p>\n</blockquote>\n\n<hr>\n\n<h1>Make the Else-Statement Implicit</h1>\n\n<blockquote>\n <pre><code>if (s.charAt(i) == \"a\" || \n s.charAt(i) == \"e\" || \n s.charAt(i) == \"i\" || \n s.charAt(i) == \"o\" || \n s.charAt(i) == \"u\") {\n strVowels += s.charAt(i);\n} else if (s.charAt(i) != \"a\" || \n s.charAt(i) != \"e\" || \n s.charAt(i) != \"i\" || \n s.charAt(i) != \"o\" || \n s.charAt(i) != \"u\") {\n strConsonants += s.charAt(i);\n}\n</code></pre>\n</blockquote>\n\n<p>Currently the if-else statement tries to express: <em>If you are a, e, i, o, u do something, else if you are not from a, e, i, o, u do something</em>.</p>\n\n<p>This is semanticly the same as: <em>If you are a, e, i, o, u do something, else do something</em>.</p>\n\n<p>Additional we can wrap the condition of the <code>vowels</code> into its own method to make the code more readable.</p>\n\n<pre><code>function isVowel(letter) {\n return letter === \"a\" || \n letter === \"e\" || \n letter === \"i\" || \n letter === \"o\" || \n letter === \"u\"\n}\n</code></pre>\n\n<p>The if-statement could now look like</p>\n\n<pre><code>var letter = s.charAt(i)\nif (isVowel(letter)) {\n strVowels += letter;\n} else {\n strConsonants += letter;\n}\n</code></pre>\n\n<hr>\n\n<h1>String Concatenation..</h1>\n\n<blockquote>\n <pre><code>strVowels += letter\n</code></pre>\n \n <p>Every time Strings get merged by <code>+</code> a new String gets created, because Strings are immutable, that means that for each concatenation new memory space gets allocated.</p>\n</blockquote>\n\n<p>Better would be to use an array instead of a string an <code>push</code> into it.</p>\n\n<pre><code>vowels.push(letter)\n</code></pre>\n\n<hr>\n\n<h1>Example Refactoring</h1>\n\n<pre><code>function isVowel(letter) {\n return letter === \"a\" ||\n letter === \"e\" ||\n letter === \"i\" ||\n letter === \"o\" ||\n letter === \"u\"\n}\n\nfunction vowelsAndConsonants(s) {\n var consonants = [];\n var vowels = [];\n\n for (var letter of s) {\n if (isVowel(letter)) {\n vowels.push(letter)\n } else {\n consonants.push(letter)\n }\n }\n\n for (var vowel of vowels) {\n console.log(vowel);\n }\n\n for (var constant of consonants) {\n console.log(constant);\n }\n}\n</code></pre>\n\n<p>and from here you can still use some methods like <code>forEach</code> or using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"noreferrer\">ternary operator</a> to shorten an if-else</p>\n\n<pre><code>function isVowel(letter) {\n return letter === \"a\" ||\n letter === \"e\" ||\n letter === \"i\" ||\n letter === \"o\" ||\n letter === \"u\"\n}\n\nfunction print(x) {\n console.log(x)\n}\n\nfunction vowelsAndConsonants(s) {\n var consonants = [];\n var vowels = [];\n\n for (var letter of s) {\n isVowel(letter)\n ? vowels.push(letter)\n : consonants.push(letter)\n }\n\n vowels.forEach(print)\n consonants.forEach(print)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T08:56:39.563",
"Id": "216221",
"ParentId": "216086",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T00:51:12.140",
"Id": "216086",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"programming-challenge"
],
"Title": "Input string, output vowels and consonants to log, separately but in order"
} | 216086 |
<p>Preface: I've perused the other related questions before creating this one but I believe that those solutions weren't applicable to my situation. I'll concede that its possible that I may not have understood a possible solution (if any). </p>
<p>I'm working on refactoring an old poker game that I created, which is a .NET Framework console application, and I came across this method.</p>
<pre><code> /// <summary>
/// Evaluates the value of the player hand and computer hand.
/// </summary>
/// <param name="pComputerHand">The computer's current hand.</param>
/// <param name="pPlayerHand">The player's current hand.</param>
/// <returns>Returns true if the player won and false if the player lost. This value is stored in the the bool won variable.</returns>
private static bool CompareHands(SuperCard[] pComputerHand, SuperCard[] pPlayerHand)
{
// Stores the value of the player and computer hands.
int playerHandValue = 0;
int computerHandValue = 0;
// Evaluates the value of computer hand
foreach(SuperCard card in pComputerHand)
{
computerHandValue += (int)card.CardRank;
}
// Evaluates the value of player hand
foreach(SuperCard card in pPlayerHand)
{
playerHandValue += (int)card.CardRank;
}
// If there is a royal flush in the computer's hand and the player's hand, the player lost.
if (PokerHands.RoyalFlush(pPlayerHand) & PokerHands.RoyalFlush(pComputerHand))
{
Console.WriteLine("\nBoth players have a royal flush!");
return false;
}
// If there is a royal flush in the player's hand, the player won.
if (PokerHands.RoyalFlush(pPlayerHand))
{
Console.WriteLine("\nYou have a royal flush!");
return true;
}
// If there is a royal flush in the computer's hand, the player lost.
if (PokerHands.RoyalFlush(pComputerHand))
{
Console.WriteLine("\nThe computer has a royal flush!");
return false;
}
#region Straight Flush
// If there is a straight flush in the computer's hand and the player's hand, the player lost.
if (PokerHands.StraightFlush(pPlayerHand) & PokerHands.StraightFlush(pComputerHand))
{
Console.WriteLine("\nBoth players have a straight flush!");
return false;
}
// If there is a straight flush in the player's hand, the player won.
if (PokerHands.StraightFlush(pPlayerHand))
{
Console.WriteLine("\nYou have a straight flush!");
return true;
}
// If there is a straight flush in the computer's hand, the player lost.
if (PokerHands.StraightFlush(pComputerHand))
{
Console.WriteLine("\nThe computer has a straight flush!");
return false;
}
#endregion
#region Four Of A Kind
// If there is a four of a kind in the computer's hand and the player's hand, the player lost.
if (PokerHands.FourOfAKind(pPlayerHand) & PokerHands.FourOfAKind(pComputerHand))
{
Console.WriteLine("\nBoth players have a four of a kind!");
return false;
}
// If there is a four of a kind in the player's hand, the player won.
if (PokerHands.FourOfAKind(pPlayerHand))
{
Console.WriteLine("\nYou have a four of a kind!");
return true;
}
// If there is a four of a kind in the computer's hand, the player lost.
if (PokerHands.FourOfAKind(pComputerHand))
{
Console.WriteLine("\nThe computer has four of a kind!");
return false;
}
#endregion
#region Full House
// If there is a full house in the computer's hand and the player's hand, the player lost.
if (PokerHands.FullHouse(pPlayerHand) & PokerHands.FullHouse(pComputerHand))
{
Console.WriteLine("\nBoth players have a full house!");
return false;
}
// If there is a full house in the player's hand, the player won.
if (PokerHands.FullHouse(pPlayerHand))
{
Console.WriteLine("\nYou have a full house!");
return true;
}
// If there is a four of a kind in the computer's hand, the player lost.
if (PokerHands.FullHouse(pComputerHand))
{
Console.WriteLine("\nThe computer has a full house!");
return false;
}
#endregion
#region Flush
// If there is a flush in the player hand and the computer hand, the player lost.
if (PokerHands.Flush(pPlayerHand) && PokerHands.Flush(pComputerHand))
{
Console.WriteLine("\nBoth players have a flush!");
return false;
}
// If there is a flush in the player hand, the player won.
if (PokerHands.Flush(pPlayerHand))
{
Console.WriteLine("\nYou have a flush!");
return true;
}
// If there is a flush in the computer hand, the player lost.
if (PokerHands.Flush(pComputerHand))
{
Console.WriteLine("\nThe computer has a flush!");
return false;
}
#endregion
#region Straight
// If there is a straight in the computer's hand and the player's hand, the player lost.
if (PokerHands.Straight(pPlayerHand) & PokerHands.Straight(pComputerHand))
{
Console.WriteLine("\nBoth players have a straight!");
return false;
}
// If there is a straight in the player's hand, the player won.
if (PokerHands.Straight(pPlayerHand))
{
Console.WriteLine("\nYou have a straight!");
return true;
}
// If there is a straight in the computer's hand, the player lost.
if (PokerHands.Straight(pComputerHand))
{
Console.WriteLine("\nThe computer has a straight!");
return false;
}
#endregion
#region Three Of A Kind
// If there is a three of a kind in the computer's hand and the player's hand, the player lost.
if (PokerHands.ThreeOfAKind(pPlayerHand) & PokerHands.ThreeOfAKind(pComputerHand))
{
Console.WriteLine("\nBoth players have a three of a kind!");
return false;
}
// If there is a three of a kind in the player's hand, the player won.
if (PokerHands.ThreeOfAKind(pPlayerHand))
{
Console.WriteLine("\nYou have a three of a kind!");
return true;
}
// If there is a three of a kind in the computer's hand, the player lost.
if (PokerHands.ThreeOfAKind(pComputerHand))
{
Console.WriteLine("\nThe computer has a three of a kind!");
return false;
}
#endregion
#region Two Pair
// If there is a two pair in the computer's hand and the player's hand, the player lost.
if (PokerHands.TwoPair(pPlayerHand) & PokerHands.TwoPair(pComputerHand))
{
Console.WriteLine("\nBoth players have a two pair!");
return false;
}
// If there is a two pair in the player's hand, the player won.
if (PokerHands.TwoPair(pPlayerHand))
{
Console.WriteLine("\nYou have a two pair!");
return true;
}
// If there is a two pair in the computer's hand, the player lost.
if (PokerHands.TwoPair(pComputerHand))
{
Console.WriteLine("\nThe computer has a two pair!");
return false;
}
#endregion
#region One Pair
// If there is a one pair in the computer's hand and the player's hand, the player lost.
if (PokerHands.OnePair(pPlayerHand) & PokerHands.OnePair(pComputerHand))
{
Console.WriteLine("\nBoth players have a one pair!");
return false;
}
// If there is a one pair in the player's hand, the player won.
if (PokerHands.OnePair(pPlayerHand))
{
Console.WriteLine("\nYou have a one pair!");
return true;
}
// If there is a one pair in the computer's hand, the player lost.
if (PokerHands.OnePair(pComputerHand))
{
Console.WriteLine("\nThe computer has a one pair!");
return false;
}
#endregion
// If the player's hand value is greater than the computer's hand value, the player won.
if (playerHandValue > computerHandValue)
{
return true;
}
// If the player's hand value is less than or equal to the computer's hand value, the player lost.
if (playerHandValue <= computerHandValue)
{
return false;
}
// Satisfies all code paths must return a value error.
else
{
return false;
}
} // end of CompareHands()
</code></pre>
<p>This is what the class diagram for the project looks like:
<a href="https://i.stack.imgur.com/Aw4jg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Aw4jg.png" alt="Poker Class Diagram"></a> </p>
<p>This is what the console output looks like:
<a href="https://i.stack.imgur.com/Rn6xm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Rn6xm.png" alt="Console output"></a></p>
<p>My question is whether its possible to extract a method (or several) out of these if statements, and provided that it is possible, how would I go about doing so? I also appreciate any other advice that you can offer like the regions being bad, for example.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T12:31:28.417",
"Id": "443108",
"Score": "3",
"body": "Being [discussed meta](https://codereview.meta.stackexchange.com/questions/9320/was-this-rollback-justified)"
}
] | [
{
"body": "<h2>Addressing the immediate question</h2>\n\n<p>I cannot comment on the coding itself, not being fluent in C#. </p>\n\n<p>The old code makes it difficult to directly extract suitable method because the value of the hand is intrinsically tied into the class <code>PokerHands</code> (for which we cannot see the code). Note that I said \"... the value ...\" instead of \"... the calculation of the value ...\" - this is an important distinction.</p>\n\n<p>To do what you want (and to make it easier to maintain later in life), the PokerHands class should be restructured to return a value instead of a Boolean. In other words, it should, as currently used in your diagram, be an enum. But, running with the concept of a class:</p>\n\n<p>e.g <code>playerHandValue = PokerHands.HandValue(pPlayerHand)</code> where <code>HandValue</code> returns an enum that is ordered in the order of outcomes (e.g. pair, triple ... royal flush).</p>\n\n<p>This small change will mean the above code only checks if <code>playerHandValue</code> > <code>computerHandValue</code> or similar. If the two values are the same, then you can have some other method that checks ranking (e.g. doubles base don pair value, or flushes based on suit etc.)</p>\n\n<p>This line of thinking leads to a stronger restructure - that is a <code>Hand</code> Class that encapsulates the above thinking, where the properties returned are:</p>\n\n<ul>\n<li>Combination value</li>\n<li>High card value for a given combination</li>\n<li>High suit value for a given combination</li>\n</ul>\n\n<p>Your <code>CompareHands</code> method then doesn't have to worry about calculating any of the values, it only has to compare them - falling more in line with the SOLID OOP principles.</p>\n\n<h2>Addressing the underlying concern</h2>\n\n<p>Now that I have had a closer look at your class diagram, I can see that you will have continued problems trying to re-work this program. </p>\n\n<ul>\n<li>The breakdown of cards into different classes by suit will create\nproblem of repetition (DRY) and cross checking.</li>\n<li>The lack of a \"Hand\" as an object to me worked with is creating the\nproblem you are trying to address above.</li>\n<li>The lack of a \"Deck\" (card set is the closest) as an object will\ncreate further problems.</li>\n</ul>\n\n<p>I recommend that any early work focusses on the structure, this may help prevent any other problems as you work your way through.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T07:05:04.003",
"Id": "418127",
"Score": "0",
"body": "I should mention that this program was initially created under some assignment constraints which is why it lacks the Hand object and PokerHand enum (the original assignment only checked for flushes). That said, I do appreciate your advice and I might rework the structure for practice. How would I go about consolidating the card classes that are separated by suit? I'm fairly new to C# myself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T18:33:44.553",
"Id": "418171",
"Score": "0",
"body": "Suit is already an enum in the diagram. Suit is a property of a card, just as the face value is. A card class basically needs those two properties. Depending on the semantics of the coding language, this means the card class could simply be a structure as the methods in handling cards should be in the game logic and the methods for managing which cards are in play should be in the deck logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T18:44:37.453",
"Id": "418173",
"Score": "0",
"body": "Thanks for the clarification. I've decided to accept your answer over Volkmar's as you pointed out the structural concerns."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T06:19:03.713",
"Id": "216096",
"ParentId": "216088",
"Score": "5"
}
},
{
"body": "<p>One simple refactoring for this method could be to simplify the following code block, that is used 9 times in the Method.</p>\n\n<pre><code> // If there is a royal flush in the computer's hand and the player's hand, the player lost.\n if (PokerHands.RoyalFlush(pPlayerHand) & PokerHands.RoyalFlush(pComputerHand))\n {\n Console.WriteLine(\"\\nBoth players have a royal flush!\");\n return false;\n }\n\n // If there is a royal flush in the player's hand, the player won.\n if (PokerHands.RoyalFlush(pPlayerHand))\n {\n Console.WriteLine(\"\\nYou have a royal flush!\");\n return true;\n }\n\n // If there is a royal flush in the computer's hand, the player lost.\n if (PokerHands.RoyalFlush(pComputerHand))\n {\n Console.WriteLine(\"\\nThe computer has a royal flush!\");\n return false;\n }\n</code></pre>\n\n<p>To simplify this code block, you could add the following enum and methods:</p>\n\n<pre><code>private enum Winner{ None, Both, Player, Computer }\n\nprivate static Winner GetWinnerForHand(bool computerHandCheckResult, bool playerHandCheckResult)\n{\n if (computerHandCheckResult && playerHandCheckResult)\n return Winner.Both;\n\n if (playerHandCheckResult)\n return Winner.Player;\n\n if (computerHandCheckResult)\n return Winner.Computer;\n\n return Winner.None;\n}\n\nprivate static void OutputWinnerToConsole(Winner winner, string handText)\n{\n if (winner == Winner.Both)\n Console.WriteLine(String.Format(\"\\nBoth players have a {0}!\", handText));\n\n if (winner == Winner.Player)\n Console.WriteLine(String.Format(\"\\nYou have a {0}!\", handText));\n\n if (winner == Winner.Computer)\n Console.WriteLine(String.Format(\"\\nThe computer has a {0}!\", handText));\n}\n</code></pre>\n\n<p>Then you can refactor the code block to:</p>\n\n<pre><code> // Check for royal flush\n var winner = GetWinnerForHand(PokerHands.RoyalFlush(pComputerHand), PokerHands.RoyalFlush(pPlayerHand));\n if (winner != Winner.None)\n {\n OutputWinnerToConsole(winner, \"royal flush\");\n return winner == Winner.Player;\n }\n</code></pre>\n\n<p>You can get rid of most of the comments because the methods explain, what is happening. You can go further by modifing the GetWinnerForHand to</p>\n\n<pre><code>private static Winner GetWinnerForHand(Func<SuperCard[], bool> check, SuperCard[] computerHand, SuperCard[] playerHand)\n{\n var computerHandCheckResult = check(computerHand);\n var playerHandCheckResult = check(playerHand);\n if (computerHandCheckResult && playerHandCheckResult)\n return Winner.Both;\n\n if (playerHandCheckResult)\n return Winner.Player;\n\n if (computerHandCheckResult )\n return Winner.Computer;\n\n return Winner.None;\n}\n</code></pre>\n\n<p>Then you can refactor the code block to:</p>\n\n<pre><code> // Check for royal flush\n var winner = GetWinnerForHand((hand) => PokerHands.RoyalFlush(hand), pComputerHand, pPlayerHand);\n if (winner != Winner.None)\n {\n OutputWinnerToConsole(winner, \"royal flush\");\n return winner == Winner.Player;\n }\n</code></pre>\n\n<p>With this change, you can even move the checks in a foreach loop, if you put the expression and handText to a list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T12:02:30.480",
"Id": "216108",
"ParentId": "216088",
"Score": "4"
}
},
{
"body": "<h2>Review</h2>\n\n<p>The other answers already provide proper ways to refactor the design and split the method up into smaller methods. I would like to address some <em>minor</em> concerns I have with this method.</p>\n\n<ul>\n<li>The method name <code>CompareHands</code> suggests a comparison, which in C# has a built-in pattern <code>IComparable<SuperCard></code> yielding an <code>integer</code> containing the comparison result, rather than a <code>bool</code>.</li>\n<li>Its description <em>\"Evaluates the value of the player hand and computer hand.\"</em> doesn't match its name (evaluation vs comparison).</li>\n<li>The documentation of the return value is verbose, but doesn't inform us how a tie is treated <em>\"Returns true if the player won and false if the player lost. This value is stored in the the bool won variable.\"</em>.</li>\n<li>I believe the names <code>pComputerHand</code> and <code>pPlayerHand</code> are some sort of variant of Hungarian Notation (p stands for parameter?), which is not the default naming convention in C#. Prefer using <code>computerHand</code> and <code>playerHand</code>.</li>\n<li><code>playerHandValue</code> and <code>computerHandValue</code> are calculated upfront, but their values are only used at the end of the method. In many cases, early exit prevents their usability. Avoid performing logic that may or may not be required. Moving this code to the end of the method is a better option.</li>\n<li>Inline documentation should yield additional information about the code. In general, I would avoid using too much inline documentation. You'd no longer be able to differentiate between obvious and important comments. Also, code should be self-explaining so most of your comments are redundant: for instance <code>// Stores the value of the player and computer hands.</code> -> yes, we can see that the next line :)</li>\n<li>I believe you missed a region <code>#region RoyalFlush</code>. However, when you require many regions inside a method (even one might be too many), you might need to think about refactoring the method and split it up into multiple methods, or even classes using some design pattern. The other answers already talk about how to split up your method and use reusable helper methods. One other way you could go about business is to use the <em>Chain of Responsibility Pattern</em> to go through hand types and yielding early when no tie is found: royal flush -> next: straight flush -> next: four of a kind -> and so on.. Each node in this chain could be a class with a pointer to the next node.</li>\n<li>This method does 3 separate things: (1) returns the winner (2) evaluates which hand the winner holds (3) renders output to the console. I would split up these 3 concerns in 3 different methods to have <em>Separation of Concerns</em>.</li>\n<li>If performance is important, you could create and reuse sub-routines. For instance, why would you calculate a Flush naively, if you've already checked for Royal Flush? The latter could store whether either Flush or Straight are found.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:14:21.197",
"Id": "443222",
"Score": "1",
"body": "Is the `pParameterName` notation that bad? It has helped me distinguish parameters from other local variables. After taking AJD's suggestion to heart, I refactored the structure, introducing a Dealer class, Player classes, a Hand class. and a PokerHand enum. I made the Player class and Hand class implement `IComparable` (as you pointed out) and then it was much easier to determine the winner."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-07T08:18:06.713",
"Id": "443225",
"Score": "0",
"body": "It's not \"that\" bad. It's just not common in C# (https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-parameters). Good to hear you found a proper way of refactoring that method."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-06T19:24:56.773",
"Id": "227597",
"ParentId": "216088",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216096",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T01:34:05.707",
"Id": "216088",
"Score": "4",
"Tags": [
"c#",
".net",
"cyclomatic-complexity"
],
"Title": "Poker Game: Refactor method to evaluate poker hands"
} | 216088 |
<pre><code>library(tidyr)
d = seq(as.Date("2018-01-01"),Sys.Date()+365,by='day')
saturdayList = d[weekdays(d)=='Saturday']
altSaturdayList = data.frame(lapply(split(saturdayList, format(saturdayList, "%Y-%m")), function(x)
na.omit(x[c(2,4)])))
altSaturdayList = subset(gather(altSaturdayList),select = c(value))
HolidayList = rbind(HolidayList, setNames(altSaturdayList, "Holidays"))
HolidayList = rbind(HolidayList, setNames(as.data.frame(as.Date("2018-11-06")), "Holidays"))
HolidayList = arrange(unique(HolidayList),Holidays)
rm(d)
rm(saturdayList)
rm(altSaturdayList)
</code></pre>
<p>The above code generates a list of dates which contain 2nd and 4th saturday of every month within that date range.</p>
<p>As you can tell I have generated and deleted intermediate variables like <code>d</code>, <code>saturdayList</code> and <code>altSaturdayList</code>. I was wondering how I can make this code better and efficient?</p>
<p>I learned about <code>%>%</code> operator but I don't know how I can do it with no input.</p>
<p>Any tips to improve the code is welcomed. Thanks</p>
| [] | [
{
"body": "<p>A pipe (<code>%>%</code>) solution is the following. I also use the <code>dplyr</code>-package, which you are probably already using as you have the <code>arrange</code>-function in your code. First I create a <code>tibble</code> with the days as input and then we can pipe ahead ;)</p>\n\n<pre><code>library(tidyr)\nlibrary(dplyr)\n\ndates <- tibble(days = seq(as.Date(\"2018-01-01\"), Sys.Date() + 365, by = 'day'))\n\nHolidayList <- dates %>% \n # Only keep Saturdays\n filter(weekdays(days) == 'Saturday') %>% \n # Create a group variable (year_month) within we want to select the 2nd and 4th value\n group_by(year_month = format(days, \"%Y-%m\")) %>% \n # Only keep the 2nd and 4th value in each year_month\n slice(c(2, 4)) %>% \n # Get rid of the grouping \n ungroup() %>% \n # Only select the days column and rename it to Holidays\n select(Holidays = days) %>% \n # Add the extra holiday 2018-11-06\n add_row(Holidays = as.Date(\"2018-11-06\")) %>% \n # similar to unique.data.frame(), but considerably faster:\n distinct() %>% \n # Arrange ascending by Holidays\n arrange(Holidays)\n\nHolidayList\n# A tibble: 54 x 1\n# Holidays \n# <date> \n# 1 2018-01-13\n# 2 2018-01-27\n# 3 2018-02-10\n# 4 2018-02-24\n# 5 2018-03-10\n# 6 2018-03-24\n# 7 2018-04-14\n# 8 2018-04-28\n# 9 2018-05-12\n# 10 2018-05-26\n# ... with 44 more rows\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T08:04:37.820",
"Id": "216098",
"ParentId": "216092",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216098",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T03:36:17.093",
"Id": "216092",
"Score": "2",
"Tags": [
"datetime",
"memory-management",
"r"
],
"Title": "Generate alternate saturday dates list within range in R"
} | 216092 |
<p>This is a tic-tac-toe game that I made in C. It works the way that I want it to but I feel like I could have done it better or shorter. Any input as to how I did would be appreciated.</p>
<p><strong>Include Statements and Prototypes</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Creating the prototypes
int init(char ttt1[3][3]);
int display_board(char ttt2[3][3]);
int turn(int *player_turns);
int get_move(char ttt3[3][3], int player_turns2, int *move, char player1[], char player2[]);
int validate_move(int move);
int check_win(char ttt[3][3], int turns);
int update_board(char ttt[3][3], const int * move, int turn);
int menu();
</code></pre>
<p><strong>Main Function</strong></p>
<pre><code>int main(void) {
int play_again = 1; //set up the loop
if(menu() == 1){ //calling the menu
while(play_again == 1) { //as long as the player wants to play again, loop
int player_turn = 1;
int move = 0;
int turns = 1;
char player1[20];
char player2[20];
char ttt[3][3]; //create the array
init(ttt); //initialize the board
printf("Enter Player 1 name(without using spaces): ");
scanf(" %s", player1);
printf("%s, you are 'X'\n", player1);
printf("Enter Player 2 name(without using spaces): ");
scanf(" %s", player2);
printf("%s, you are 'O'\n", player2);
while (check_win(ttt, turns) == 0) {
get_move(ttt, player_turn, &move, player1, player2); //receive the moves from the player
validate_move(move); //call the function to validate the moves
update_board(ttt, &move, player_turn); //call the function which updates the board based on the players move
display_board(ttt); //redisplay the board
turn(&player_turn); //call the function to change whose turn it is
turns++; //increment turns
}
printf("Would you like to play again?(1 for yes, 2 for no) ");
scanf(" %d", &play_again);
}
}
return 0;
}
</code></pre>
<p><strong>Board Initializer</strong></p>
<pre><code>//set up the board for use in the game
int init(char ttt1[3][3]){
ttt1[0][0] = '1';
ttt1[0][1] = '2';
ttt1[0][2] = '3';
ttt1[1][0] = '4';
ttt1[1][1] = '5';
ttt1[1][2] = '6';
ttt1[2][0] = '7';
ttt1[2][1] = '8';
ttt1[2][2] = '9';
return 0;
}
</code></pre>
<p><strong>Board Display</strong></p>
<p>This does display the board the way it should but I need a way to clear the screen. I have tried a few ways that I found online but since I am on Mac OS none of it worked. What is a good way to clear the screen that is portable?</p>
<pre><code>//showing the board on the screen
int display_board(char ttt2[3][3]){
printf("%c | %c | %c\n", ttt2[0][0], ttt2[0][1], ttt2[0][2]); //displays the top row
printf("----------\n");
printf("%c | %c | %c\n", ttt2[1][0], ttt2[1][1], ttt2[1][2]); //displays the middle row
printf("----------\n");
printf("%c | %c | %c\n", ttt2[2][0], ttt2[2][1], ttt2[2][2]); //displays the bottom row
return 0;
}
</code></pre>
<p><strong>Which Turn</strong></p>
<pre><code>int turn(int *player_turns1){
if(*player_turns1 == 1){ //if it is player one's turn
*player_turns1 = 2; //change it to player two's turn
}
else if(*player_turns1 == 2){ //if it is player two's turn
*player_turns1 = 1; // change it to player one's turn
}
return 0;
}
</code></pre>
<p><strong>Move Retrieval</strong></p>
<pre><code>//get the move from the player depending on whose turn it is
int get_move(char ttt3[3][3], int player_turns2, int *move, char player1_1[], char player2_1[]){
if(player_turns2 == 1){ //if it is player one's turn
display_board(ttt3); //display the board
printf("%s, please enter where you would like to move: ", player1_1); //ask for the move
scanf(" %d", move);//get the move from the player
}
else if(player_turns2 == 2){ //if it is player two's turn
display_board(ttt3); //display the board
printf("%s, please enter where you would like to move: ", player2_1); //ask for the move
scanf(" %d", move); //get the move from the player
}
return *move;
}
</code></pre>
<p><strong>Move Validator</strong></p>
<pre><code>int validate_move(int move1){
if (move1 < 1 || move1 > 9) { //if the move is on the board
return 0;
}
else //if the move does not fall on the board
return 1;
}
</code></pre>
<p><strong>Update the Board</strong></p>
<pre><code> //function that updates the board with the user's move
int update_board(char ttt[3][3], const int *move, int turn){
if(*move == 1 && turn == 1) //top left is chosen by player one
ttt[0][0] = 'X'; //set the square to x
else if(*move == 1 && turn == 2) //top left is chosen by player two
ttt[0][0] = 'O'; //set the square to o
else if(*move == 2 && turn == 1) //top middle is chosen by player one
ttt[0][1] = 'X'; //set the square to x
else if(*move == 2 && turn == 2) //top middle is chosen by player two
ttt[0][1] = 'O'; //set the square to o
else if(*move == 3 && turn == 1) //top right is chosen by player one
ttt[0][2] = 'X'; //set the square to x
else if(*move == 3 && turn == 2) //top right is chosen by player two
ttt[0][2] = 'O'; //set the square to o
else if(*move == 4 && turn == 1) //middle left is chosen by player one
ttt[1][0] = 'X'; //set the square to x
else if(*move == 4 && turn == 2) //middle left is chosen by player two
ttt[1][0] = 'O'; //set the square to o
else if(*move == 5 && turn == 1) //middle is chosen by player one
ttt[1][1] = 'X'; //set the square to x
else if(*move == 5 && turn == 2) //middle is chosen by player two
ttt[1][1] = 'O'; //set the square to o
else if(*move == 6 && turn == 1) //middle right is chosen by player one
ttt[1][2] = 'X'; //set the square to x
else if(*move == 6 && turn == 2) //middle right is chosen by player two
ttt[1][2] = 'O'; //set the square to o
else if(*move == 7 && turn == 1) //bottom right is chosen by player one
ttt[2][0] = 'X'; //set the square to x
else if(*move == 7 && turn == 2) //bottom right is chosen by player two
ttt[2][0] = 'O'; //set the square to o
else if(*move == 8 && turn == 1) //bottom middle is chosen by player one
ttt[2][1] = 'X'; //set the square to x
else if(*move == 8 && turn == 2) //bottom middle is chosen by player two
ttt[2][1] = 'O';//set the square to o
else if(*move == 9 && turn == 1) //bottom right is chosen by player one
ttt[2][2] = 'X'; //set the square to x
else if(*move == 9 && turn == 2) //bottom right is chosen by player two
ttt[2][2] = 'O'; //set the square to o
return 0;
}
</code></pre>
<p><strong>Victory/Tie Check</strong></p>
<pre><code>//check the board to see if there is a winner
int check_win(char ttt[3][3], int turns1){
if(ttt[0][0] == ttt[0][1] && ttt[0][1] == ttt[0][2]) { //top row horizontal check
printf("Congratulations, You Won!\n");
return 1;
}
else if(ttt[1][0] == ttt[1][1] && ttt[1][1] == ttt[1][2]) { //middle row horizontal check
printf("Congratulations, You Won!\n");
return 1;
}
else if(ttt[2][0] == ttt[2][1] && ttt[2][1] == ttt[2][2]) { //bottom row horizontal check
printf("Congratulations, You Won!\n");
return 1;
}
else if(ttt[0][0] == ttt[1][0] && ttt[1][0] == ttt[2][0]) { //left column vertical check
printf("Congratulations, You Won!\n");
return 1;
}
else if(ttt[0][1] == ttt[1][1] && ttt[1][1] == ttt[2][1]) { //middle column vertical check
printf("Congratulations, You Won!\n");
return 1;
}
else if(ttt[0][2] == ttt[1][2] && ttt[1][2] == ttt[2][2]) { //right column vertical check
printf("Congratulations, You Won!\n");
return 1;
}
else if(ttt[0][0] == ttt[1][1] && ttt[1][1] == ttt[2][2]) { //top left to bottom right diagonal check
printf("Congratulations, You Won!\n");
return 1;
}
else if(ttt[2][0] == ttt[1][1] && ttt[1][1] == ttt[0][2]) { //top right to bottom left diagonal check
printf("Congratulations, You Won!\n");
return 1;
}
else if(turns1 >= 10) //checks to see if the game ends in a tie
printf("The game ends in a draw, no one wins.\n");
else
return 0;
}
</code></pre>
<p><strong>Menu Function</strong></p>
<p>Switch/Case seemed to be the best way that I could think of to do a menu. Options 2-4 are my next projects to be working on.</p>
<pre><code>//the function that controls the menu
int menu(){
int state = 0; //establish the state variable
printf("Welcome to my Tic Tac Toe Game!\n");
printf("How would you like to play?\n");
printf("1. 2D Player vs. Player\n");
printf("2. 2D Player vs. Computer(Not ready yet)\n");
printf("3. 3D Player vs. Player(Not ready yet)\n");
printf("3. 3D Player vs. Computer(Not ready yet)\n");
printf("Enter your choice: ");
scanf(" %d", &state); //get the user's choice for the menu
switch(state){
case 1: //option 1 in the menu
return 1;
case 2: //option 2 in the menu
return 2;
case 3: //option 3 in the menu
return 3;
case 4: //option 4 in the menu
return 4;
default: //if an invalid option is chosen
printf("There was an error. Please try again.");
}
}
</code></pre>
<p>I know that this code works as I want it to but I feel like it's too long or that there are easier ways to achieve some of the tasks. Again, any help or input is much appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T04:33:26.837",
"Id": "418125",
"Score": "1",
"body": "This would be easier to review if all the code was in one block, enabling reviewers to copy and paste the code into their own environments if desired."
}
] | [
{
"body": "<h1>1.</h1> \n\n<p>In the function <code>int menu()</code><br>\nyou can reduce the switch with this statement</p>\n\n<pre><code>return ((state>0 && state<5)?state:printf(\"There was an error. Please try again.\"),0); \n</code></pre>\n\n<p>With this your <code>menu()</code> will return 0 whenever illegal input is received and hence you can put the <code>menu()</code> call inside main in a loop and <strong>handle wrong input better way.</strong> </p>\n\n<p>This piece of code </p>\n\n<pre><code>int main(void) {\n int play_again = 1; //set up the loop\n if(menu() == 1){ //calling the menu \n</code></pre>\n\n<p>can be written like this </p>\n\n<pre><code>int main(void) {\n int choice;\n while(!(choice = menu()));\n int play_again = 1; //set up the loop\n if(choice == 1){ //calling the menu \n</code></pre>\n\n<h1>2.</h1> \n\n<p>in the function <code>int update_board(char ttt[3][3], const int *move, int turn)</code> </p>\n\n<p><code>move</code> variable provides with enough information to find out the coordinate of the character in the 2D-array <code>ttt</code> which needs to be changed </p>\n\n<pre><code>int update_board(char ttt[3][3], const int *move, int turn){\n char ch = (turn==1)?'X':'O';\n int x = (*move-1)/3, y=(*move-1)-(x*3);\n ttt[x][y]=ch;\n return 0; // return statement does not make any sense right now\n} \n</code></pre>\n\n<p>The overall code can become slightly simpler and shorter if you treat <code>turn</code> variable as a bool and use 0 and 1 to know which players are having turns.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T02:11:11.187",
"Id": "418196",
"Score": "0",
"body": "@grabbailoutrun, you can show appreciation by putting an upvote. Also remember to avoid saying hi,hello,thank you like statements here (statements which are not constructive). Also check out the rules one should follow while posting here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T08:48:03.760",
"Id": "216100",
"ParentId": "216094",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T04:20:41.630",
"Id": "216094",
"Score": "1",
"Tags": [
"c",
"tic-tac-toe"
],
"Title": "Function-based Tic-Tac-Toe game in C"
} | 216094 |
<p>I am trying to implement a simple raw queue in C++. This is what I have come up with</p>
<pre><code>#include <queue>
#include <cstdint>
#include <array>
#include <cstring>
class simple_queue
{
private:
static constexpr uint32_t max_msg_size = 4096;
using char_msg = std::array<char, max_msg_size>;
std::queue<char_msg> char_queue;
public:
simple_queue() = default;
~simple_queue() = default;
simple_queue(simple_queue&&) = default;
simple_queue& operator=(simple_queue&&) = default;
uint32_t write(const char* const buff, const uint32_t size) noexcept
{
const uint32_t size_to_copy = std::min(max_msg_size, size);
char_msg tmp_msg;
std::memcpy(&tmp_msg, buff, size_to_copy);
char_queue.push(std::move(tmp_msg));
return size_to_copy;
}
uint32_t read(char* const buff, const uint32_t size) noexcept
{
if (char_queue.empty())
{
return 0;
}
const uint32_t size_to_copy = std::min(max_msg_size, size);
std::memcpy(buff, &char_queue.front(), size_to_copy);
char_queue.pop();
return size_to_copy;
}
};
</code></pre>
<p>Note that I am trying to implement this queue just to store raw char buffers. As far as I understand making it a template does not make sense in this case. </p>
<p>I have played with it a bit and it seems to work as I expect. </p>
<ul>
<li>What can I change with this implementation?</li>
<li>Does it make sense to use a custom allocator in here? I am allocating memory every time I write to the queue; how can I use a custom allocator to allocate some default chunk of memory when the queue is constructed?</li>
</ul>
| [] | [
{
"body": "<p>You are <em>not</em> allocating per se when when writing to the queue. <code>std::array</code> is backed by a plain <code>C</code>-array on the stack, that gets moved. </p>\n\n<p>So you only ever allocate depending on the underlying container the <code>std::queue</code> is based on. By default this is a <code>std::deque</code>.</p>\n\n<p>I do not really understand the need for the <code>std::array</code> in the type though. Why not just use a <code>std::string</code> and limit the size of it to 4096? There is even a constructor that does explicitely that <code>string (const char* s, size_t n)</code></p>\n\n<p>Before I get to the Code there are some other things I would like to mention:</p>\n\n<ol>\n<li><p>why are you not useing std::copy instead of memcpy. The former works better with C++ and will in the end almost always end up as memcpy?</p></li>\n<li><p>You do not need to define the special member functions. In fact you have forgotten 2 of then, aka copy assignment and copy constructor. Why do I say forgotten? Because there is no way to tell. So If you want your queue to be move only then you should actually <code>delete</code> those special member functions you dont want.</p></li>\n<li><p>In your read function you never check whether the size you want to read is actually valid. Is that intendend? If so why? A <code>std::array</code> is not initialized so the memory in it that is not written by you will be random. You are not writing to it but you are copying it around. So you should actually take the minimum out of <code>size</code> and <code>queue.front().size()</code></p></li>\n<li><p><code>std::string</code> has a member function <code>std::string::copy</code> that copyies a certain amount of chars to a buffer (<a href=\"http://www.cplusplus.com/reference/string/string/copy/\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/string/string/copy/</a>). I would suggest to use that for writing back to the buffer </p></li>\n</ol>\n\n<p>That leads me to the following:</p>\n\n<pre><code>#include <string>\n#include <queue>\n#include <vector>\n\nclass simple_queue\n{\nprivate:\n static constexpr uint32_t max_msg_size = 4096;\n std::queue<std::string, std::vector<std::string>> char_queue;\n\npublic: \n simple_queue(const simple_queue&) = delete;\n simple_queue& operator=(const simple_queue&) = delete;\n\n uint32_t write(const char* const buff, const uint32_t size) noexcept\n {\n const uint32_t size_to_copy = std::min(max_msg_size, size);\n char_queue.emplace(buff, size_to_copy);\n return size_to_copy;\n }\n\n uint32_t read(char* const buff, const uint32_t size) noexcept\n {\n if (char_queue.empty())\n {\n return 0;\n }\n std::string& msg = char_queue.front();\n const uint32_t size_to_copy = std::min(msg, size);\n msg.copy(buff, size_to_copy, 0);\n\n char_queue.pop();\n return size_to_copy;\n }\n};\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>I forgot to mention, that now you should use a <code>std::vector</code> as backing of the queue as your are not storing a gargantuan array but rather a mall <code>std::string</code>. </p>\n\n<p>Note that it actually ends up being the same. The <code>std::deque</code> based <code>std::array</code> implementation is backed by a linked list, so each array ends up in a node of a linked list, which is kind of similar to the separate allocation of the <code>std::string</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T12:46:16.183",
"Id": "418146",
"Score": "2",
"body": "You should not use \"EDIT tags\"; they are only confusing and distracting for people who come to the question or answer for the first time. Edits happen all the time, and anyone interested can just click to see the whole post history."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T17:34:07.153",
"Id": "418163",
"Score": "0",
"body": "Thanks, all of your points are valid. I have updated the implementation and after running benchmarks it is performing much better. However there is still something I would like to improve. With every `.emplace(buff, size_to_copy)` the allocator for `std::string` is called, I would like to get rid of allocation and have it use a pre allocated chunk of memory. I was under the impression it might be easier to do so with `std::array` and that's why I opted to use that instead of `std::string`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T17:40:09.533",
"Id": "418164",
"Score": "0",
"body": "@miscco\nBTW, I did not get why you've mentioned to use `std::vector`, you mean I should use a vector of `char`s?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T21:16:55.763",
"Id": "418179",
"Score": "1",
"body": "@Ali `std::queue` is a container-adaptor. The second template argument it takes is the underlying container. Consequently, in the example i replaced the default container `std::deque` with `std::vector`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T21:19:05.483",
"Id": "418180",
"Score": "0",
"body": "@Ali Regarding your first comment, you will most likely never get rid of all allocations, as the std array is allocated into a container node anyway. In fact it even better to allocate a potentially smaller string than always putting a gargantuan array into `std::deque` node"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T21:45:32.463",
"Id": "418181",
"Score": "0",
"body": "@miscco, I see. Very interesting. Using the `std::vector` as the underlying container is actually faster compared to the default(`std::dequeu`?). Why is that?\nI do not control the size of the strings and almost all of them are 4KB, the perfect solution to me would be to have some custom allocator so that all `std::string`s can use that pre-allocated space"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T22:10:57.290",
"Id": "418186",
"Score": "0",
"body": "@miscco I have been only benchmarking the `write` method. After trying to benchmark `read()` it appears I cannot use `std::vector` as it does not provide `pop_front()` as described [here](https://en.cppreference.com/w/cpp/container/queue). But `std::list` seems to be working really good. I am still wondering why changing the the underlying container can have such a big impact on performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T11:11:33.283",
"Id": "418235",
"Score": "0",
"body": "@Ali Std::vector in to always faster. It depends on the use case. Chandler Carruth hat an amathing talk about that topic (https://www.youtube.com/watch?v=fHNmRkzxHWs). For example std::deque is a container that has to fulfill various requirements. A std::list does not. If you only need those properties a list fulfills, then the list is a better container as it is simpler. Finally, you do not save allocations of the string with the std::array, because that array is allocated into a node of the queue. You cannot avoid that."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T12:13:42.657",
"Id": "216109",
"ParentId": "216097",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T07:16:08.763",
"Id": "216097",
"Score": "2",
"Tags": [
"c++",
"performance",
"queue"
],
"Title": "Simple raw buffer queue implementation"
} | 216097 |
<p>I'm trying to embed YouTube video's on a website in a privacy-friendly way.</p>
<blockquote>
<p>The code doesn't load the iframes by default but shows a preview
thumbnail overlayed with an info message instead. The user can load a
single video by clicking the button in the info message. The overlay
also contains a checkbox that, if checked, unblocks all YouTube
iframes and remembers the user's preference by setting a cookie.</p>
</blockquote>
<p>Some points of attention:</p>
<ul>
<li>Embeds need to be responsive</li>
<li>In trying to minimize network request I don't hardcode the preview image in the html.</li>
<li>Loaded video is autoplayed, to avoid second click.</li>
<li>Code needs to support ie10.</li>
</ul>
<p>Is the code indeed supported by ie10? Any input or thoughts on best practices or ways to organize my JS code are greatly appreciated. </p>
<p><strong>HTML</strong>:</p>
<pre class="lang-html prettyprint-override"><code><div class="youtube-embed" data-id="-XB5y26XRSk">
<div class="youtube-embed__notice">
<p>Info and link to YouTube's privacy policy</p>
<label><input type="checkbox" name="acceptall"> Accept YouTube content in the future.</label>
<button>Load video</button>
</div>
<iframe class="youtube-embed__iframe" frameborder="0" allowfullscreen allow="autoplay"></iframe>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre class="lang-css prettyprint-override"><code>.youtube-embed {
position: relative;
overflow-y: auto;
height: 0;
padding-bottom: 56.25%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
.youtube-embed__notice {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
}
.youtube-embed__iframe {
display: none;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.youtube-embed--active .youtube-embed__notice {
display: none;
}
.youtube-embed--active .youtube-embed__iframe {
display: block;
}
</code></pre>
<p><strong>JS</strong></p>
<pre class="lang-js prettyprint-override"><code>var cookie = {
name: 'cookie-consent',
get: function() {
var match = document.cookie.match(new RegExp('(?:^|;)\\s*' + this.name + '\\s*\\=\\s*([^;]*)'));
return match ? match[1] : null;
},
set: function(value) {
var expiryDate = new Date();
expiryDate.setDate(expiryDate.getDate() + 365);
document.cookie =
this.name + '=' + value + '; expires=' + expiryDate.toUTCString() + '; path=/';
}
};
function customEvent(name, detail) {
var event;
if (window.CustomEvent) {
event = new CustomEvent(name, { detail: detail });
} else {
event = document.createEvent('CustomEvent');
event.initCustomEvent(name, true, true, detail);
}
return event;
}
function YoutubeEmbed(container, state) {
this.container = container;
this.state = state;
this.id = this.container.getAttribute('data-id');
this.autoplay = false;
this.notice = this.container.querySelector('.youtube-embed__notice');
this.iframe = this.container.querySelector('.youtube-embed__iframe');
this.acceptButton = this.container.querySelector('button');
this.acceptAllCheckbox = this.container.querySelector('input[type=checkbox]');
this.attachEvents();
this.render();
}
YoutubeEmbed.prototype.setState = function(state) {
this.state = state;
this.render();
};
YoutubeEmbed.prototype.saveConsent = function(){
cookie.set('youtube');
}
YoutubeEmbed.prototype.attachEvents = function() {
var _this = this;
this.acceptButton.addEventListener('click', function() {
if (_this.acceptAllCheckbox.checked) {
_this.saveConsent();
var event = customEvent('consentchanged');
document.dispatchEvent(event);
}
_this.autoplay = true;
_this.setState(false);
});
};
YoutubeEmbed.prototype.showNotice = function() {
this.iframe.removeAttribute('src');
var imageSrc = 'https://i.ytimg.com/vi/' + this.id + '/hqdefault.jpg';
this.container.style.backgroundImage = 'url(' + imageSrc + ')';
this.container.classList.remove('youtube-embed--active');
};
YoutubeEmbed.prototype.showIframe = function() {
var iframeSrc = 'https://www.youtube-nocookie.com/embed/' + this.id;
if (this.autoplay) {
iframeSrc += '?autoplay=1';
}
this.iframe.src = iframeSrc;
this.container.style.backgroundImage = 'none';
this.container.classList.add('youtube-embed--active');
};
YoutubeEmbed.prototype.render = function() {
if (this.state === 'blocked') {
this.showNotice();
} else {
this.showIframe();
}
};
function getState(){
var consentCookie = cookie.get();
var youtubeConsent = consentCookie && consentCookie.indexOf('youtube') !== -1;
return youtubeConsent ? 'unblocked' : 'blocked';
}
var initialState = getState();
var youtubeEmbeds = document.querySelectorAll('.youtube-embed');
var youtubeEmbedObjects = [];
youtubeEmbeds.forEach(function(embed) {
youtubeEmbedObjects.push(new YoutubeEmbed(embed, initialState));
});
document.addEventListener('consentchanged', function() {
youtubeEmbedObjects.forEach(function(embedObject) {
var newState = getState();
embedObject.setState(newState);
});
});
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T12:50:14.813",
"Id": "418148",
"Score": "0",
"body": "Adaptations made."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T13:03:42.333",
"Id": "418152",
"Score": "0",
"body": "Thank you I have retracted the close vote and will remove previous comments."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T09:51:07.830",
"Id": "216103",
"Score": "3",
"Tags": [
"javascript",
"html",
"css",
"automation"
],
"Title": "Block YouTube iframes until user consents with cookies"
} | 216103 |
<p>This is the latest version of my Blackjack game and I did a quite big update to it. Now you can make an account that is saved in the MySQL database and you can bet money that are also saved in the database.</p>
<pre><code>from random import shuffle
import os
import cymysql
from getpass import getpass
import sys
def shuffled_shoe():
shoe = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'A', 'J', 'Q', 'K']*4
shuffle(shoe)
return shoe
def deal_card(shoe, person, number):
for _ in range(number):
person.append(shoe.pop())
def deal_hand(shoe, player, dealer):
deal_card(shoe, player, 2)
deal_card(shoe, dealer, 2)
def score(person):
non_aces = [c for c in person if c != 'A']
aces = [c for c in person if c == 'A']
total = 0
for card in non_aces:
if card in 'JQK':
total += 10
else:
total += int(card)
for card in aces:
if total <= 10:
total += 11
else:
total += 1
return total
def display_info(still_playing, player, dealer, money, money_bet, player_stands):
os.system('cls' if os.name == 'nt' else 'clear')
print(f"Money: ${money}")
print(f"Money bet: ${money_bet}")
print("Your cards: [{}] ({})".format("][".join(player), score(player)))
if player_stands:
print("Dealer cards: [{}] ({})".format("][".join(dealer), score(dealer)))
else:
print("Dealer cards: [{}][?]".format(dealer[0]))
first_hand = len(dealer) == 2
if score(player) == 21:
print("Blackjack! You won")
still_playing = False
money += money_bet * 2
elif first_hand and score(dealer) == 21:
print("Dealer got a blackjack. You lost!")
still_playing = False
elif score(player) > 21:
print("Busted! You lost!")
still_playing = False
if player_stands:
if score(dealer) > 21:
print("Dealer busted! You won")
money += money_bet * 2
elif score(player) > score(dealer):
print("You beat the dealer! You won!")
money += money_bet * 2
elif score(player) < score(dealer):
print("Dealer has beaten you. You lost!")
else:
print("Push. Nobody wins or losses.")
money += money_bet
still_playing = False
return still_playing, money
def hit_or_stand():
while True:
print("What do you choose?")
print("[1] Hit")
print("[2] Stand")
ans = input("> ")
if ans in '12':
return ans
def bet():
print("How much money do you want to bet?")
money = int(input("> "))
return money
def player_play(shoe, player, dealer, money, money_bet, player_plays, player_stands):
while not player_stands:
if hit_or_stand() == '2':
player_stands = True
player_plays = False
elif not player_stands:
deal_card(shoe, player, 1)
display_info(True, player, dealer, money, money_bet, player_stands)
if score(player) >= 21:
player_plays = False
break
return player_plays, player_stands
def dealer_play(shoe, dealer, DEALER_MINIMUM_SCORE):
while score(dealer) <= DEALER_MINIMUM_SCORE:
deal_card(shoe, dealer, 1)
return False
def play_again(cur, money, email):
while True:
print("\nDo you want to play again?")
print("[1] Yes")
print("[2] No")
ans = input("> ")
if ans == '1':
return True
elif ans == '2':
cur.execute("UPDATE `users` SET `money`=%s WHERE `email`=%s", (money, email))
cur.close()
return False
def get_user_info():
while True:
email = input("Email address (max. 255 chars.): ")
password = getpass("Password (max. 255 chars.): ")
if len(email) < 255 and len(password) < 255:
return email, password
def register(cur, email, password):
cur.execute("INSERT INTO `users` (`Email`, `Password`) VALUES (%s, %s)", (email, password))
def login(cur, email, password):
cur.execute("SELECT * FROM `users` WHERE `Email`=%s AND `Password`=%s LIMIT 1", (email, password))
return bool(cur.fetchall())
def check_account(cur, email):
cur.execute("SELECT * FROM `users` WHERE `Email`=%s LIMIT 1", (email,))
return bool(cur.fetchone())
def start():
print("Do you want to start playing? (Y)es/(N)o")
ans = input("> ").lower()
if ans == 'y':
return True
elif ans == 'n':
return False
def main():
conn = cymysql.connect(
host='127.0.0.1',
user='root',
passwd='',
db='blackjack'
)
with conn:
cur = conn.cursor()
email, password = get_user_info()
checked = check_account(cur, email)
if checked:
loggedin = login(cur, email, password)
if loggedin:
print("You've succesfully logged-in!")
else:
print("You failed logging-in!")
sys.exit()
else:
register(cur, email, password)
print("You've succesfully registered and recieved $1000!")
cur.execute("SELECT `money` FROM `users` WHERE `email`=%s", (email,))
money = cur.fetchone()
cash = money[0]
keeps_playing = start()
while keeps_playing:
shoe = shuffled_shoe()
player = []
dealer = []
still_playing = True
player_plays = True
player_stands = False
money_bet = bet()
cash -= money_bet
deal_hand(shoe, player, dealer)
still_playing, cash = display_info(still_playing, player, dealer, cash, money_bet, player_stands)
while still_playing:
while player_plays:
player_plays, player_stands = player_play(shoe, player, dealer, cash, money_bet, player_plays, player_stands)
still_playing = dealer_play(shoe, dealer, 17)
still_playing, cash = display_info(still_playing, player, dealer, cash, money_bet, player_stands)
keeps_playing = play_again(cur, cash, email)
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>A couple possible bugs:</p>\n\n<ul>\n<li>When a user registers, there's text saying that they get $1000 to start. I don't see where this money comes from in the code.</li>\n<li>In <code>display_info()</code>, if <code>player_stands</code> is <code>True</code>, I think it could be possible to display both \"Busted! You lost!\" and \"\"Dealer busted! You won\"</li>\n</ul>\n\n<p>I don't see the point of passing <code>still_playing</code> to <code>display_info</code>. If we don't pass it, set <code>still_playing</code> to <code>True</code> at the start of the function, the overall behavior doesn't change.</p>\n\n<p>I think <code>display_info()</code> is doing an awful lot. It:</p>\n\n<ul>\n<li>shows the current state</li>\n<li>determines the winner</li>\n<li>changes the player's money, and</li>\n<li>Tells you who won/lost</li>\n</ul>\n\n<p>I would try to separate these out.</p>\n\n<p><code>hit_or_stand()</code> returns a number, so the caller has to remember what it means. Consider using a constant or an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a> instead.</p>\n\n<p>The user's password gets stored in plaintext. Consider encrypting it.</p>\n\n<p>It seems unconventional to have a function parameter be in all caps. Per PEP 8: </p>\n\n<blockquote>\n <p>Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.\"</p>\n</blockquote>\n\n<p>So it would look more natural to do, e.g.</p>\n\n<pre><code>import sys\n\nDEALER_MINIMUM_SCORE = 17\n\n[...]\n\ndef dealer_play(shoe, dealer):\n while score(dealer) <= DEALER_MINIMUM_SCORE:\n deal_card(shoe, dealer, 1)\n return False\n</code></pre>\n\n<p>or maybe</p>\n\n<pre><code>def dealer_play(shoe, dealer, dealer_minimum_score):\n while score(dealer) <= dealer_minimum_score:\n deal_card(shoe, dealer, 1)\n return False\n\n[...]\n\nstill_playing = dealer_play(shoe, dealer, DEALER_MINIMUM_SCORE)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T12:16:06.320",
"Id": "418142",
"Score": "0",
"body": "First bug won't happen because in the database I chose 'money' to have a default value of 1000. Second bug won't happen either. If I set still_playing as True and I don't pass it to display_info, then if I get a Blackjack, I will have to play the entire game to see that. I will try to split display_info a bit."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T11:59:16.267",
"Id": "216107",
"ParentId": "216105",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216107",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T10:28:26.173",
"Id": "216105",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"sql",
"mysql",
"playing-cards"
],
"Title": "Blackjack game with database"
} | 216105 |
<p>I'm trying to solve <em>ECOO 2018 round 2(regionals) question 2</em> to prepare for the upcoming contest. Basically, in the question <em>George</em> has to achieve the maximum possible grade by completing the right assignments. Each assignment has a deadline and a weight value. I've came up with two solutions yet both only work for 7 of the cases and are extremely slow for the other 3. Here is the problem statement: </p>
<blockquote>
<h2>Problem 2: Homework</h2>
<hr>
<p>George has procrastinated too much on his <strong>N</strong> homework assignments,
and now he is running out of time to finish them all.<br>
Each of George’s <strong>N</strong> assignments has a weight that it contributes
to his grade and a deadline in days from today.
George will need one day to finish any of the assignments and he must
complete an assignment before it’s deadline in order to submit it
(he can’t complete it the day an assignment is due).<br>
Help George figure out
the order in which he should complete his assignments
such that the total weight of the assignments he completes is maximized.</p>
<p><strong>Input Specifications</strong><br>
DATA21.txt (DATA22.txt for the second try) will contain 10 datasets.
Each dataset begins with an integer <strong>N</strong> (1 ≤ <strong>N</strong> ≤ 1,000,000).</p>
<p>The next <strong>N</strong> lines contain an integer <strong>D</strong> and decimal <strong>W</strong>
(1 ≤ <strong>D</strong> ≤ 1,000,000; 0 < <strong>W</strong> ≤ 100), representing
an assignment that has a deadline that is <strong>D</strong> days from today
and a weight of <strong>W</strong>. </p>
<p>For the first seven cases, <strong>N</strong> ≤ 1000.</p>
<p><strong>Output Specifications</strong><br>
For each dataset, output the maximum total weight of
the assignments that George can complete, rounded to 4 decimal places
(George is very meticulous about his grade).</p>
<p><strong><code>Sample Input (Two Datasets Shown) Sample Output</code></strong> </p>
<pre><code>3 3.0000
1 1.0 17.0000
2 1.0
3 1.0
5
1 2.0
1 1.0
3 3.0
7 10.0
3 2.0
</code></pre>
</blockquote>
<p>(pixel raster of <a href="https://i.stack.imgur.com/wXSKL.png" rel="nofollow noreferrer">original Problem Statement</a> (including <code>it’s</code>))</p>
<p><strong>Solution #1</strong>:
In this solution I adopted the elimination approach.<br>
I store the deadline along with the assignments due in this day in a dictionary.<br>
Then I sort all the assignments (keys) and iterate sequentially, each time picking the highest <em>d</em> assignments where <em>d</em> is the deadline (because you cannot complete more than 1 assignment in a day, 3 in 3 days and so on).<br>
I estimated the complexity to be <em>O(dlogd + dwlogw)</em>. </p>
<pre><code>def main():
from collections import defaultdict
with open("DATA21.txt") as all_data:
my_lines = iter(all_data.readlines())
number_of_assignments = int(next(my_lines))
homework_dict = defaultdict(list)
for _ in range(number_of_assignments):
d, w = [float(i) for i in next(my_lines).split()]
d = int(d)
# Setting up the dictionary
homework_dict[d].append(w)
all_deadlines = list(homework_dict.keys())
all_deadlines.sort()
# Algorithm starts here
selected_assignments = []
for deadline in all_deadlines:
deadline_assignments = homework_dict[deadline]
deadline_assignments.extend(selected_assignments)
deadline_assignments.sort()
difference = len(deadline_assignments) - deadline
if difference < 0:
selected_assignments = deadline_assignments
else:
selected_assignments = deadline_assignments[difference::]
tot = sum(selected_assignments)
new = format(tot, ".4f")
print(new)
main()
</code></pre>
<p><strong>Solution 2</strong>: In this solution I work directly,<br>
I create a 2-dimensional list and sort in reverse order so that the weights are first.<br>
Then I iterate through this list and look if it's possible to complete the current assignment by the deadline. I do this by creating a list of all the days and removing each deadline I already completed.<br>
I estimate the complexity to be around <em>O(nlogn + nd)</em>.</p>
<pre><code>def main():
with open("DATA21.txt") as all_data:
my_lines = iter(all_data.readlines())
n = int(next(my_lines))
def take_second(elem):
return elem[1]
biggest = 0
deadlines_weights_list = []
for i in range(n):
d, w = [float(x) for x in next(my_lines).split()]
d = int(d)
if d > biggest:
biggest = d
deadlines_weights_list.append([d, w])
deadlines_weights_list.sort(key=take_second, reverse=True)
possible_days = [day+1 for day in range(biggest)]
total = 0
for deadline, weight in deadlines_weights_list:
# If there are no days left the code should be terminated
if len(possible_days) == 0:
break
while deadline not in possible_days:
deadline -= 1
# This means the only days left are really high, with much more time.
if deadline < possible_days[0]:
break
if deadline in possible_days:
# One day cannot be used twice
possible_days.remove(deadline)
total += weight
total = format(total, ".4f")
print(total)
main()
</code></pre>
<p>I apologize for posting two codes in one review, I'm more concerned about finding an algorithm that is fast enough for all of test cases rather than comparing this codes. Both solutions work for 7 test cases out of 10 but exceed the time limit for the other 3. Would appreciate any suggestions to optimize this solutions or a completely new way to solve this challenge. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T17:52:56.180",
"Id": "418165",
"Score": "0",
"body": "Please include the problem description as text not an image."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T19:14:11.590",
"Id": "418176",
"Score": "0",
"body": "Okay I edited it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T21:58:14.063",
"Id": "418184",
"Score": "0",
"body": "Welcome to Code Review! `two codes in one review` *if* you want a Comparative Review, please tag [tag:comparative-review] (doesn't hurt to explicitly ask for one in the question, too)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T08:00:40.303",
"Id": "418208",
"Score": "0",
"body": "Do both solutions correctly solve the problem? If not, this would be off-topic, see our [help/dont-ask]. If they merely exceed the time limits that is OK, we even have a tag for that: [tag:time-limit-exceeded]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:18:41.870",
"Id": "418244",
"Score": "0",
"body": "yes they both solve the problem correctly with 7 out of 10 test cases it's just that for the other 3 test cases they are not efficient enough (takes a couple minutes to execute in compare to 1 second for all the first 7)"
}
] | [
{
"body": "<h2>Approach 1</h2>\n\n<blockquote>\n<pre><code>def main():\n ... monolithic method ...\n\nmain()\n</code></pre>\n</blockquote>\n\n<p>Either this is a throwaway program, in which case you don't need to define <code>main</code> at all, or it isn't, in which case you should only call <code>main()</code> if <code>__name__ == \"__main__\"</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> from collections import defaultdict\n\n with open(\"DATA21.txt\") as all_data:\n my_lines = iter(all_data.readlines())\n\n number_of_assignments = int(next(my_lines))\n\n homework_dict = defaultdict(list)\n\n for _ in range(number_of_assignments):\n d, w = [float(i) for i in next(my_lines).split()]\n d = int(d)\n # Setting up the dictionary\n\n homework_dict[d].append(w)\n</code></pre>\n</blockquote>\n\n<p>This looks to me like a method which should be factored out, so that there is clear isolation between the I/O and the processing.</p>\n\n<p>I don't understand the use of <code>float</code> and <code>int</code>. Would it not be clearer to avoid the double-coercion with something like this?</p>\n\n<pre><code> d, w = next(my_lines).split()\n homework_dict[int(d)].append(float(w))\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> all_deadlines = list(homework_dict.keys())\n\n all_deadlines.sort()\n</code></pre>\n</blockquote>\n\n<p>I'm not sure what <code>all_</code> adds to the name. <code>deadlines</code> works for me, or <code>distinct_deadlines</code> to be more explicit.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> # Algorithm starts here\n</code></pre>\n</blockquote>\n\n<p>See my previous point about factoring out methods.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> selected_assignments = []\n for deadline in all_deadlines:\n deadline_assignments = homework_dict[deadline]\n deadline_assignments.extend(selected_assignments)\n deadline_assignments.sort()\n</code></pre>\n</blockquote>\n\n<p>This is going to be doing a lot of sorts of already sorted data. That seems like a plausible bottleneck. I see at least three obviously better approaches:</p>\n\n<ol>\n<li>Sort <code>homework_dict[deadline]</code> and then merge two sorted lists in linear time.</li>\n<li>Use a priority queue of some kind for <code>selected_assignments</code>. Add <code>homework_dict[deadline]</code> to the queue and then pop it down to the desired length.</li>\n<li>The asymptotically best option that I can see, although possibly not the fastest in practice, would be to append the new assignments and then use a linear time median finder to slice the merged list.</li>\n</ol>\n\n<blockquote>\n<pre><code> difference = len(deadline_assignments) - deadline\n if difference < 0:\n selected_assignments = deadline_assignments\n else:\n selected_assignments = deadline_assignments[difference::]\n</code></pre>\n</blockquote>\n\n<p><code>difference</code> is not an informative name. What does the difference actually <em>mean</em>? It's something like \"<em>number of assignments to discard</em>\". I might use <code>excess</code> as a name, or <code>num_excess_assignments</code> if I wanted to be more explicit.</p>\n\n<hr>\n\n<p>It would be nice to see some comments in the code explaining why it's correct. I would say that having read it carefully a few times I find its correctness plausible, but I wouldn't be willing to guarantee it.</p>\n\n<hr>\n\n<h2>Approach 2</h2>\n\n<p>A lot of the comments (about structure, names, proof of correctness, ...) on approach 1 apply here too.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> possible_days = [day+1 for day in range(biggest)]\n</code></pre>\n</blockquote>\n\n<p>What is <code>possible_days</code> used for? <code>in possible_days</code> and <code>possible_days.remove</code>. This is a classic performance blunder (so don't feel bad, because you're far from the first person to stumble into it: clearly there are popular learning resources which should address this and don't). In general, the appropriate data structure for this use case is <code>set</code>, not <code>list</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> while deadline not in possible_days:\n deadline -= 1\n # This means the only days left are really high, with much more time. \n if deadline < possible_days[0]:\n break\n</code></pre>\n</blockquote>\n\n<p>However, it turns out that the use of <code>possible_days</code> is even more specialised than it seemed at first. Even if you replace the list with a <code>set</code>, this would still be a linear scan, and it doesn't need to be. You want the largest value smaller than a given one: if you keep the values in order then a binary chop will get there in logarithmic time rather than linear.</p>\n\n<blockquote>\n<pre><code> if deadline in possible_days:\n # One day cannot be used twice \n possible_days.remove(deadline)\n total += weight\n</code></pre>\n</blockquote>\n\n<p>However, updating the array needed for binary chop would not be logarithmic time. What you need is some kind of tree which allows searches and removals in logarithmic time. The access pattern is not going to be random, so to guarantee logarithmic time it probably needs to be a self-balancing tree, or some kind of self-pruning trie. I'm not aware of a suitable implementation in the standard library: I think you would have to write it yourself.</p>\n\n<p>Actually, thinking about it some more, I reckon you could use an augmented union-find data structure to get amortised linear time. Initially each index (and -1 as a sentinel) is in a singleton set with associated data equal to the index. The search and delete becomes (pseudocode):</p>\n\n<pre><code>available = find(deadline).data\nif available >= 0:\n total += weight\n union(available, available - 1)\n</code></pre>\n\n<p>ensuring that <code>union</code> chooses the smaller of the two associated data items.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:05:24.277",
"Id": "216172",
"ParentId": "216115",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T15:33:14.393",
"Id": "216115",
"Score": "2",
"Tags": [
"python",
"sorting",
"time-limit-exceeded",
"dynamic-programming"
],
"Title": "Finding maximum homework grade ECOO 2018"
} | 216115 |
<p>I was trying to solve a problem which stated: </p>
<blockquote>
<p>Calculate the first 10 digit prime found in consecutive digits of e.</p>
</blockquote>
<p>I was able to solve the problem but I did it by using some 10k digits of e available online. So I tried to write a program which calculates digits of e. The problem is that it simply gives the incorrect answer. </p>
<p>The code and the formula I used are:</p>
<p><span class="math-container">$$e = \sum\limits_{n=0}^{\infty}\frac{1}{n!} = \frac{1}{1} + \frac{1}{1} + \frac{1}{1 \cdot 2} + \frac{1}{1\cdot 2 \cdot 3} + \cdots$$</span></p>
<pre><code>import math
e=0
x=int(input()) #larger this number, more will be the digits of e
for i in range(x):
e+=(1/(math.factorial(i)))
print(e)
</code></pre>
<p>When the user inputs 10, the digits returned are 2.7182815255731922 which is not correct. </p>
<p>Can someone explain why my code does not produce the correct result?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T03:49:45.193",
"Id": "418197",
"Score": "3",
"body": "If you want a really good aproximation of e, you could always use the beautiful `(1+9^-(4^6*7))^3^2^85` which yields 18457734525360901453873570 digits of e (if you calculate with enough precision), and is a pan-digital formula to boot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T11:04:02.167",
"Id": "418233",
"Score": "2",
"body": "[This is being discussed on meta](https://codereview.meta.stackexchange.com/q/9126), [twice](https://codereview.meta.stackexchange.com/q/9129)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T19:43:18.937",
"Id": "418727",
"Score": "0",
"body": "What if the user inputs a bigger number, say 100, is the correct result produced then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T05:02:31.787",
"Id": "418945",
"Score": "0",
"body": "@SimonForsberg: this question seems like it would be a better fit for Stack Overflow, I think with tags `[floating-point]` and `[numerical-methods]`. The existing answer would still fit the question on SO with those tags."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T13:24:33.743",
"Id": "418965",
"Score": "1",
"body": "@PeterCordes I just tried to migrate the question but unfortunately I was not able to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T16:16:19.790",
"Id": "418981",
"Score": "0",
"body": "@SimonForsberg Is this the default message you get if the question failed to migrate? (Confused why the banner's wording went from 'broken' -> generic)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T16:24:20.500",
"Id": "418982",
"Score": "0",
"body": "@Peilonrayz Yes, this is the default message."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T03:47:44.293",
"Id": "419026",
"Score": "0",
"body": "@SimonForsberg Is it ok to delete this question? I am tired of getting downvotes for no apparent reason? Going to the help center is useless. That's not how a beginner should be treated."
}
] | [
{
"body": "<p>First of all, don't panic. 10 is just not enough (indeed, it only gives you <a href=\"https://en.wikipedia.org/wiki/Taylor%27s_theorem#Example\" rel=\"noreferrer\">5 decimal places</a>. Try 20, and obtain</p>\n\n<pre><code>2.71828182846\n</code></pre>\n\n<p>which is much closer.</p>\n\n<p>Now, Python uses a native floating point, which may only give you that many digits of precision (say, 30). To get more, you need to work with another representations; <code>fractions.Fraction</code> looks like a good candidate.</p>\n\n<p>Finally, calls to <code>math.factorial</code> waste too much computing power. It is better to compute factorials as you go, e.g.</p>\n\n<pre><code> denom = 1\n for i in range(1, x):\n e += 1 / denom\n denom *= i\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T06:29:28.373",
"Id": "418344",
"Score": "0",
"body": "So is that the case with every module? For example, while calculating the square root of a number, is it better to use `math.sqrt(x)` or should we manually define a function to calculate it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T06:30:48.967",
"Id": "418345",
"Score": "0",
"body": "Also, when is it preferable to use `math.factorial(x)` instead of the way which you provided?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T19:58:36.663",
"Id": "418729",
"Score": "1",
"body": "@AaryanDewan Think of it this way, `math.factorial(x)` computes *one* factorial, but if you want *many consecutive* factorials it is much slower to compute them one-by-one than computing them all, consecutively. If you have a use-case where you need just one or a few specific arbitrary factorials, then `math.factorial(x)` already does what you need to do so then it is preferable."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T16:28:14.810",
"Id": "216117",
"ParentId": "216116",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "216117",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T15:37:02.540",
"Id": "216116",
"Score": "-4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Python: Computing \\$e\\$"
} | 216116 |
<p>Please see the code below, which I have taken and adapted from <a href="https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html" rel="nofollow noreferrer">here</a> and <a href="https://github.com/rabbitmq/rabbitmq-tutorials/tree/master/dotnet" rel="nofollow noreferrer">here</a> (<code>RPCServer</code> and <code>RPCClient</code>):</p>
<pre><code>public RpcClient()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
connection = factory.CreateConnection();
channel = connection.CreateModel();
replyQueueName = channel.QueueDeclare().QueueName;
consumer = new EventingBasicConsumer(channel);
List<String> responses = new List<string>();
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var response = Encoding.UTF8.GetString(body);
responses.Add(response);
if (responses.Count == 2)
{
if (!callbackMapper.TryRemove(ea.BasicProperties.CorrelationId, out TaskCompletionSource<List<string>> tcs))
return;
tcs.TrySetResult(responses);
}
else
return;
};
}
</code></pre>
<p>This is a <a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/BroadcastAggregate.html" rel="nofollow noreferrer">Scatter Gather</a>. Notice that the list of responses is defined outside of <code>consumer.Received</code>. Are there any pitfalls doing this that I have not considered?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T18:57:15.330",
"Id": "418174",
"Score": "0",
"body": "could you tell us what pitfalls you already considered? Also, some details could be helpfull, like what kind of problems do you have in mind? Bugs? Performance? Memory-Consumption? Readability?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T19:08:17.883",
"Id": "418175",
"Score": "0",
"body": "@d_hippo, I cannot think of any pitfalls whatsoever. I am thinking more about bugs, but would also like to hear about performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T08:01:17.527",
"Id": "418209",
"Score": "0",
"body": "What does it mean you have adapted the code? What is this code for? You have share more details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T08:12:25.020",
"Id": "418212",
"Score": "0",
"body": "@t3chb0t, I am trying to implement the scatter gather pattern (it is more of a learning exercise). The full code can be found in the links of my question."
}
] | [
{
"body": "<p>What you are doing is called a 'closure', the C# Language Specification speaks of 'Captured outer variables' in §7.15.5.1.</p>\n\n<p>Since I don't know how familiar you are with them, nor what you intend to actually do with them, I'll try to list some points that you should be aware off (this list will not be exhaustive and is not meant to).</p>\n\n<ul>\n<li>Closures can both greatly enhance and reduce the readability and understandability of your code, depending on how you use it and your/your teammates preferences. Introducing a new language feature into day-to-day use should be discussed beforehand with all relevant team members; sometimes someone has a hard time getting something and using it in a productive manner. It's important to establish a certain minimal required knowledge about new language features before they are used in production code, otherwise you might end up with avoidable problems (like: the only dev who fully understands feature X leaves and now you get a critical bug in code that makes extensive use of this feature). </li>\n<li>Performance in general is a tricky question that I'm not going to try to answer here, since there are a bazillion factors contributing. What I can say from my experience as a C#-Dev is that closures never turned out to be the reason for a performance problem for me. If you're generally writing sane code performance-wise (i.e. code that avoids doing outright stupid things, not code that is micro-optimized), you'll most likely not end up with any closure-related performance problems, and worrying about potential problems that you're not going to have is pointless. If you encounter performance problems, follow the usual procedure before jumping to any hasty conclusions about closures.</li>\n<li>In my experience, closures do not lead to more bugs, if everyone understands how they work they might lead to fewer. They are mostly syntactic sugar, a syntactically more convenient way to do what you would be doing anyways (in this case: make a variable, whose lifetime is not tied to the scope of a method, an instance-variable of some class and expose it to those who need to know) - which is better tested then what you would be doing on your own, and often more precise. The 'if everyone understands how they work'-part is critical, but thats a no-brainer anyway, any dev using a tool he does not understand will produce problems.</li>\n</ul>\n\n<p>Some information about clorsure-related problems I've run into:</p>\n\n<ul>\n<li>Closures are implemented via compiler-generated classes that hold the captured variables. At maximum, one such class per Method is generated, no matter how many closures you use in that Method, <a href=\"https://www.jetbrains.com/help/resharper/ImplicitlyCapturedClosure.html\" rel=\"nofollow noreferrer\">which might lead to the unexpected prolonging of an objects lifetime</a>. </li>\n<li><a href=\"https://blogs.msdn.microsoft.com/ericlippert/2009/11/12/closing-over-the-loop-variable-considered-harmful/\" rel=\"nofollow noreferrer\">The foreach-loop underwent a breaking change in respect to how it handles closures in C# 5</a>, which might be a Problem if you try to use the same Code with different Versions of C# (for example, upgrade a C#4-Project to a later language version). Note that this can lead to very subtle problems, like an anonymous method being thread-safe in C#5, bus not in C# 4 (with the Code unchanged). If you're using only C# 5 or greater, you should be safe, if you're using C# 4 or below and are planning an upgrade I would not introduce closures right now.</li>\n</ul>\n\n<p>In your posted code I don't see any reasons not to use the closure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T21:03:16.783",
"Id": "418178",
"Score": "0",
"body": "Thanks for the reference to closure. +1 for that. Can you see any problems using a scatter gather scenario like this?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T20:25:30.837",
"Id": "216122",
"ParentId": "216118",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T17:53:54.013",
"Id": "216118",
"Score": "-1",
"Tags": [
"c#",
"rabbitmq"
],
"Title": "Anonymous function uses variable declared outside the function"
} | 216118 |
<p>The <a href="https://en.wikipedia.org/wiki/C_standard_library" rel="nofollow noreferrer">Standard C Library</a> consists of various headers files. Often only a few select ones are needed for given code.</p>
<p>Other times it is simply convenient coding to include them all in a .c file, even if that make the compilation time a bit slower.</p>
<p>Including all standard <code><*.h></code> is useful to help detect naming collisions of a <code>.c</code> file with an existing standard function, object, type, macro, etc.</p>
<p><strong>Review Goal</strong></p>
<p>How well does <code>std.h</code> accomplish the goal of including all standard header files via one <code>.h</code> file given that the set varies amongst C versions and implementations?</p>
<pre><code>/*
* std.h
* Created on: Mar 16, 2019, Author: chux
*/
#ifndef STD_H_
#define STD_H_
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <float.h>
#include <limits.h>
#include <locale.h>
#include <math.h>
#include <setjmp.h>
#include <signal.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#if defined __STDC__ && defined __STDC_VERSION__
#if __STDC_VERSION__ >= 199409
#include <iso646.h>
#include <wchar.h>
#include <wctype.h>
#endif
#if __STDC_VERSION__ >= 199901
#ifndef __STDC_NO_COMPLEX__
#include <complex.h>
#endif
#include <fenv.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <tgmath.h>
#endif
#if __STDC_VERSION__ >= 201112
#include <stdalign.h>
#ifndef __STDC_NO_ATOMICS__
#include <stdatomic.h>
#endif
#include <stdnoreturn.h>
#ifndef __STDC_NO_THREADS__
#include <threads.h>
#endif
#include <uchar.h>
#endif
#if __STDC_VERSION__ >= 201710
/* None added */
#endif
#endif
#endif /* STD_H_ */
</code></pre>
<hr>
<p>In making a set of functions and types called say <code>foo</code>, I do not recommend including all header files in a <code>foo.h</code>, yet perhaps in <code>foo.c</code>.</p>
<p>Sample usage</p>
<pre><code>// foo.h (no std.h here)
#ifndef FOO_H_
#define FOO_H_
#include <stdint.h>
#include <time.h>
typedef struct {
time_t t;
uint32_t u32;
} foo;
void foo_this(foo *f);
void foo_that(foo *f);
#endif /* FOO_H_ */
</code></pre>
<p><code>foo.c</code> or <code>main.c</code></p>
<pre><code>#include "foo.h"
#include "std.h"
int main(void) {
foo f;
foo_this(&f);
foo_that(&f);
printf("Hello World!\n");
return 0;
}
</code></pre>
<hr>
<p>The alternative spellings afforded in <code><iso646.h></code> seem to be a solution to a regional character set problem of years ago. I reluctantly included <code><iso646.h></code> here but do see that a good candidate to exclude. It defines macros for <code>and</code>, <code>or</code>, <code>xor</code> and others. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T11:58:29.947",
"Id": "418241",
"Score": "0",
"body": "When I read the title, I thought \"*but why*?\" Having read the description, I see what you're doing. However, beware that that if you contravene the naming rules - which I'm sure you don't - then finding no collisions using *this* compiler, *today* doesn't guarantee anything about other builds. Past success is no guarantee of future performance!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:23:51.470",
"Id": "418246",
"Score": "0",
"body": "@TobySpeight Agree the including all `<*.h>` will not certainly detect all name collision and future ones, yet is a reasonable test today to potential discern them."
}
] | [
{
"body": "<p>With this suggested usage:</p>\n\n<blockquote>\n<pre><code>#include \"foo.h\"\n#include \"std.h\"\n</code></pre>\n</blockquote>\n\n<p>then any macros defined in <code>\"std.h\"</code> (and not used in the rest of the <code>main</code>) won't break the program. Swapping these round:</p>\n\n<pre><code>#include \"std.h\"\n#include \"foo.h\"\n</code></pre>\n\n<p>solves that problem, but then fails to diagnose missing includes in <code>\"foo.h\"</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:04:51.627",
"Id": "216154",
"ParentId": "216119",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>Your code doesn't cover \"freestanding implementations\" (embedded systems or OS). You could check for <code>#if __STDC_HOSTED__ == 0</code> and reduce the headers. Freestanding implementations need not provide all headers except a minimal subset, see C11 4/6:</p>\n\n<blockquote>\n <p><em>A conforming freestanding implementation</em> shall accept any strictly conforming program in which the\n use of the features specified in the library clause (clause 7) is confined to the contents of the standard headers <code><float.h>, <iso646.h>, <limits.h>, <stdalign.h>, <stdarg.h>, <stdbool.h>, <stddef.h>, <stdint.h>,</code> and\n <code><stdnoreturn.h></code></p>\n</blockquote>\n\n<p>Though of course freestanding implementations may provide other headers too, making this hard to fulfil without a specific implementation in mind.</p></li>\n<li><p>Style issue: you should indent everything within <code>#if</code>... <code>#endif</code> just as you would for regular <code>if</code> statements. It is also good practice to leave a comment /* */ after each <code>#endif</code> to document which <code>#if</code> is belongs to.</p></li>\n</ul>\n\n<p>EDIT: proposed indention fix</p>\n\n<pre><code>#ifndef STD_H_\n#define STD_H_\n\n#include <assert.h>\n#include <ctype.h>\n#include <errno.h>\n#include <float.h>\n#include <limits.h>\n#include <locale.h>\n#include <math.h>\n#include <setjmp.h>\n#include <signal.h>\n#include <stdarg.h>\n#include <stddef.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\n#if defined __STDC__ && defined __STDC_VERSION__\n\n #if __STDC_VERSION__ >= 199409\n #include <iso646.h>\n #include <wchar.h>\n #include <wctype.h>\n #endif\n\n #if __STDC_VERSION__ >= 199901\n #ifndef __STDC_NO_COMPLEX__\n #include <complex.h>\n #endif\n #include <fenv.h>\n #include <inttypes.h>\n #include <stdbool.h>\n #include <stdint.h>\n #include <tgmath.h>\n #endif\n\n #if __STDC_VERSION__ >= 201112\n #include <stdalign.h>\n #ifndef __STDC_NO_ATOMICS__\n #include <stdatomic.h>\n #endif\n #include <stdnoreturn.h>\n #ifndef __STDC_NO_THREADS__\n #include <threads.h>\n #endif\n #include <uchar.h>\n #endif\n\n #if __STDC_VERSION__ >= 201710\n /* None added */\n #endif\n\n#endif /* #if defined __STDC__ && defined __STDC_VERSION__ */\n\n#endif /* STD_H_ */\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T13:29:17.403",
"Id": "418260",
"Score": "0",
"body": "Please post a sample `#` indent. I have tried various styles, ` #if bar` (my auto formatter (Eclipse) keeps shifting them left ) and `# if bar` which looks _odd_. Perhaps you have another?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T14:10:08.157",
"Id": "418265",
"Score": "1",
"body": "@chux Posted. After trying some 30+ different, magic IDEs including GNU indent, I'm convinced that mankind will never develop intelligent AI. So I tend to fall back to good ole spacebar :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-03T15:11:53.363",
"Id": "437813",
"Score": "0",
"body": "Thanks for the `__STDC_HOSTED__` idea. I'll need to dig deeper into that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:59:46.490",
"Id": "216160",
"ParentId": "216119",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216160",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T18:40:06.763",
"Id": "216119",
"Score": "3",
"Tags": [
"c",
"portability"
],
"Title": "Header file that includes all standard C library headers"
} | 216119 |
<p>I am working with closures and want to confirm that I do not have any memory leaks in my code. Below is my current code:</p>
<pre><code>// in ImageGalleryController.swift
class ImageGalleryCollectionViewController: UICollectionViewController {
var images = [Image]()
func dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {
// assignment of closure
var cellImage = Image() { [weak self](image) in
self?.images.append(image)
self?.collectionView.reloadData()
}
// asynchronous
session.loadObjects(ofClass: NSURL.self) { urls in
if let url = urls.first as? URL {
cellImage.url = url
}
}
// asynchronous
session.loadObjects(ofClass: UIImage.self) { images in
if let image = images.first as? UIImage {
cellImage.aspectRatio = Double(image.size.height / image.size.width)
}
}
}
}
// in ImageGallery.swift
struct Image {
var url: URL? = nil {
didSet {
if propertiesAreSet() { handler(self) }
}
}
var aspectRatio: Double? = nil {
didSet {
if propertiesAreSet() { handler(self) }
}
}
init(handler: @escaping (Image) -> Void) {
self.handler = handler
}
var handler: (Image) -> Void
private func propertiesAreSet() -> Bool {
let bool = (url != nil && aspectRatio != nil) ? true : false
return bool
}
}
</code></pre>
<p>Basically my logic is that when two separate asynchronous requests get and set two separate properties on the Image struct, then I want to append that Image struct to the images array.</p>
<p>Which brings me to my related questions:</p>
<ul>
<li>Since I am fairly new to Swift, am I properly handling memory leaks by declaring [weak self] when I create a new Image instance?</li>
<li>Should I set the closure handler to nil after it executes?</li>
<li>Is what I am doing ok or am I violating any Swift principles?</li>
</ul>
| [] | [
{
"body": "<p>You asked:</p>\n\n<blockquote>\n <p>... am I properly handling memory leaks by declaring <code>[weak self]</code> when I create a new <code>Image</code> instance?</p>\n</blockquote>\n\n<p>By using <code>[weak self]</code>, yes, you are preventing a strong reference cycle.</p>\n\n<p>By the way, you can always use the “Debug memory graph” feature to confirm whether you have any strong reference cycles. See <a href=\"https://stackoverflow.com/questions/30992338/how-to-debug-memory-leaks-when-leaks-instrument-does-not-show-them/30993476#30993476\">this answer</a> for information about this feature.</p>\n\n<blockquote>\n <p>Should I set the closure handler to <code>nil</code> after it executes?</p>\n</blockquote>\n\n<p>As a general rule, yes, </p>\n\n<ol>\n<li><p>You should make the <code>handler</code> an optional:</p>\n\n<pre><code>var handler: ((Image) -> Void)?\n</code></pre>\n\n<p>and<br /> </p></li>\n<li><p>Set it to <code>nil</code> after calling it:</p>\n\n<pre><code>if propertiesAreSet() { \n handler?(self) \n handler = nil\n}\n</code></pre></li>\n</ol>\n\n<p>The idea is, just in case the caller neglected to use the <code>[weak self]</code> pattern, this will resolve any accidental strong reference cycles. It is a defensive programming approach that minimizes the chances of unresolved strong reference cycles (and also minimizes the chance of introducing a bug that will call the closure multiple times). But this is not used in lieu of <code>[weak self]</code>, but rather in conjunction with it.</p>\n\n<blockquote>\n <p>Is what I am doing ok or am I violating any Swift principles?</p>\n</blockquote>\n\n<p>Your code works, but is brittle. (This isn’t a “Swift principle” but rather a generally programming one.) For example, these two types are too tightly coupled: What if <code>Image</code> is extended at some future date to have some additional property that can’t be <code>nil</code>? You have to remember to go back to the other types that instantiate <code>Image</code> and make sure you update them accordingly, too, or else you might not see images loaded into your UI at all.</p>\n\n<p>Setting that aside, I’d also suggest that the fact that the handler is called when those two properties are set isn’t very obvious. You really have to carefully read the code of both types to reason about what’s going on.</p>\n\n<p>I’d refactor this, simplifying your model object, the <code>Image</code>, and putting the retrieval logic in the controller. </p>\n\n<p>E.g.</p>\n\n<pre><code>var images = [Image]()\n\nfunc dropInteraction(_ interaction: UIDropInteraction, performDrop session: UIDropSession) {\n // assignment of closure\n var cellImage = Image()\n let group = DispatchGroup()\n\n group.enter()\n session.loadObjects(ofClass: NSURL.self) { urls in\n cellImage.url = urls.first as? URL\n group.leave()\n }\n\n group.enter()\n session.loadObjects(ofClass: UIImage.self) { images in\n if let image = images.first as? UIImage {\n cellImage.aspectRatio = Double(image.size.height / image.size.width)\n }\n group.leave()\n }\n\n group.notify(queue: .main) { [weak self] in\n guard\n let self = self,\n cellImage.url != nil,\n cellImage.aspectRatio != nil else { return }\n\n self.images.append(cellImage)\n self.collectionView.insertItems(at: [IndexPath(item: self.images.count - 1, section: 0)])\n }\n}\n\n// in ImageGallery.swift\nstruct Image {\n var url: URL? = nil\n var aspectRatio: Double? = nil\n}\n</code></pre>\n\n<hr>\n\n<p>A few other observations:</p>\n\n<ol>\n<li><p>Notice that above, rather than reloading the whole collection view, you can just reload the new cell.</p></li>\n<li><p>The above code snippet begs the question as to whether you really should be creating a <code>Image</code> first and retrieving its properties later, or whether you should retrieve the necessary data, and when you have what you need, only then instantiate and return the <code>Image</code> object. It’s hard to get too specific here without more information about this <code>loadObjects</code> method, why it’s taking multiple calls to retrieve the image details, etc. I don’t think we want to get into that level of detail here, but I only mention this as something you should think about as you work on the broader design of your app.</p></li>\n<li><p>If your reaction to my code snippet above is “gee, I really don’t like adding all of this code to the view controller”, that’s a good intuition. Often, as apps scale, we like to pull this sort of logic out of the view controller and put it in some other object (perhaps a “view model”, perhaps a “presenter”, perhaps “network controller” ... there are lots of ways to skin the cat). But the goal is to limit our view controllers to configuring and responding to views, in the spirit of the “single responsibility principle”. This will make it easier for us to reason about our code and improve its testability (e.g. we want to test our business logic without worrying about collection view behaviors).</p>\n\n<p>This is a pretty complicated topic and is beyond the scope of this question but the stretch objective is to keep view controllers as minimal as possible. But I might refer you to these sources to get you thinking about these concepts:</p>\n\n<ul>\n<li>Dave DeLong is an advocate for not giving up on MVC, but being more prudent in its use. See <a href=\"https://davedelong.com/blog/2017/11/06/a-better-mvc-part-1-the-problems/\" rel=\"nofollow noreferrer\">A Better MVC</a>.</li>\n<li>Medium has an old survey of some of the MVC alternatives that you’ll see bandied about including MVP, MVVM, VIPER, etc. See <a href=\"https://medium.com/ios-os-x-development/ios-architecture-patterns-ecba4c38de52\" rel=\"nofollow noreferrer\">iOS Architecture Patterns</a>.</li>\n</ul></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T15:01:00.857",
"Id": "419468",
"Score": "1",
"body": "Thanks Rob. Your insight is very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T17:42:50.067",
"Id": "216802",
"ParentId": "216120",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216802",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T18:52:18.920",
"Id": "216120",
"Score": "2",
"Tags": [
"swift"
],
"Title": "Swift Memory Cycle From Closure"
} | 216120 |
<p>I'm trying to teach myself Clojure by reading the <a href="https://www.braveclojure.com/read-and-eval/#Exercises" rel="nofollow noreferrer">Brave Clojure</a> book online, and at the end of Chapter 7 there is an exercise to parse a mathematical expression written as a list in infix notation to s-expressions, following operator precedence rules.</p>
<p>To do this I implemented the <a href="https://en.wikipedia.org/wiki/Shunting-yard_algorithm" rel="nofollow noreferrer">shunting-yard algorithm</a> in Clojure. However I am not sure if I am doing this in a functional way, as I am used to programming in languages like C++ and Python. In particular, I am uncertain whether the use of the <code>loop</code> operator is valid, as I'm coding this in basically the same way I would as in C++, just using <code>recur</code> on every loop iteration instead of mutating variables. This makes it seem a little repetitive.</p>
<p>Below is the code. It would be greatly appreciated someone takes a look and offers advice about how to do this in a more idiomatic functional way, or about anything else.</p>
<pre class="lang-clj prettyprint-override"><code>(def operator-precedence {'= 1, '+ 5, '- 5, '* 6, '/ 6})
(defn infix-parse
"Converts an infix expression to s-expressions in linear time with the
shunting-yard algorithm."
[expr]
(if (list? expr)
(loop [val-stack ()
op-stack ()
remaining expr
next-op false]
(if next-op
(let [prec (if (empty? remaining)
##-Inf
(operator-precedence (first remaining)))
popped (take-while #(>= (operator-precedence %) prec) op-stack)
result (reduce
(fn [[a b & vals] op]
(cons (list op b a) vals))
val-stack
popped)]
(if (empty? remaining)
(first result)
(recur result
(cons (first remaining)
(drop (count popped) op-stack))
(rest remaining)
false)))
(recur (cons (infix-parse (first remaining)) val-stack)
op-stack
(rest remaining)
true)))
expr))
(defmacro infix
[form]
(infix-parse form))
</code></pre>
<pre class="lang-clj prettyprint-override"><code>(infix (1 + 3 * (4 - 5) * 10 / 2))
=> -14
(infix-parse '(1 + 3 * (4 - 5) * 10 / 2))
=> (+ 1 (/ (* (* 3 (- 4 5)) 10) 2))
</code></pre>
| [] | [
{
"body": "<p>First, yes, this is functional, and yes, this is how to use <code>loop</code> properly.</p>\n\n<blockquote>\n <p>. . . using recur on every loop iteration instead of mutating variables.</p>\n</blockquote>\n\n<p>This is the intent of <code>loop</code>. Instead of mutating a variable, you just pass the \"altered data\" to the next iteration via <code>recur</code>.</p>\n\n<p>You also aren't abusing side effects by misusing <code>def</code> or <code>atom</code>s, so that's good.</p>\n\n<hr>\n\n<p>My main concern with this code is how it's really just one giant function. There's no function names indicating what certain code is doing, and no comments noting the significance of any lines. Now, I'm personally a stickler for breaking code down into functions, but it's generally regard as best practice as well. As <a href=\"https://softwareengineering.stackexchange.com/a/210374/139925\">this</a> answer notes (ignoring the mention of \"imperative\"):</p>\n\n<blockquote>\n <p>Having a large imperative function that conveys many ideas is hard to digest and reuse.</p>\n</blockquote>\n\n<p>I think the size of this function <em>does</em> make it hard to digest.</p>\n\n<p>Just as an extreme counter example, <a href=\"https://codereview.stackexchange.com/questions/181183/infix-to-rpn-converter-using-the-shunting-yard-algorithm\">here's the same algorithm that I wrote a year ago</a><code>*</code>. It's almost 4x longer as yours, but it's also much clearer what each bit of code is doing (and has ~10 lines dedicated to documentation). Code like</p>\n\n<pre><code>(-> equation\n (tokenize-equation)\n (infix->RPN-tokens op-attr-map)\n (tokens-to-string)) ; Should arguably be called token->string\n</code></pre>\n\n<p>makes it fairly clear what it's responsible for, even without taking into consideration the function name that it's in.</p>\n\n<p>I'm won't try to break your code down (mostly because I burned my hand pretty bad, and typing this is hard enough), but if you take a look at my example, you may be able to find some inspiration and strike a middle ground for granularity.</p>\n\n<p>Good luck</p>\n\n<hr>\n\n<p><code>*</code> Although my version doesn't evaluate the expression since I'm translating it into a String and in my example, the data isn't available at compile-time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T22:30:44.813",
"Id": "216130",
"ParentId": "216123",
"Score": "1"
}
},
{
"body": "<p>I like what you have done and much enjoyed getting to grips with it. Let's take a look. </p>\n\n<p>The Clojure reader provides a syntax tree of sequences, which your algorithm traverses</p>\n\n<ul>\n<li>vertically, by recursive descent and</li>\n<li>horizontally by double shunting an operator stack and a value stack.</li>\n</ul>\n\n<p>Let's look at the role of <code>next-op</code> - the last binding in the <code>loop</code>.</p>\n\n<ul>\n<li>It's a boolean flag - <code>true</code> or <code>false</code>.</li>\n<li>It alternates between these two values: the <code>true</code> handler recurs it\nto <code>false</code> and vice versa.</li>\n</ul>\n\n<p>We can</p>\n\n<ul>\n<li>transform this phase change into mutual tail recursion, then </li>\n<li>flatten it by using <a href=\"https://clojuredocs.org/clojure.core/trampoline\" rel=\"nofollow noreferrer\"><code>trampoline</code></a>.</li>\n</ul>\n\n<p>Donald Knuth discusses similar transformations in <a href=\"http://www.cs.sjsu.edu/~mak/CS185C/KnuthStructuredProgrammingGoTo.pdf\" rel=\"nofollow noreferrer\"><em>Structured Programming with Goto Statements</em></a>. Look at example 4 on page 11/271. </p>\n\n<p><em>Mutual tail-recursion</em></p>\n\n<p>We lose the <code>next-op</code> local, replacing it with two mutually recursive functions:</p>\n\n<ul>\n<li><code>next-op</code> - the <code>true</code> phase, expecting an operator;</li>\n<li><code>next-val</code> - the <code>false</code> phase, expecting a value.</li>\n</ul>\n\n<p>Minor changes:</p>\n\n<ul>\n<li>I've used <a href=\"https://clojuredocs.org/clojure.core/split-with\" rel=\"nofollow noreferrer\"><code>split-with</code></a> to pop the operator stack. This is just\nan abbreviation of what you did.</li>\n<li>I test <code>expr</code> with <code>seq?</code> rather than <code>list?</code>, just in case we want\nto supply a lazy sequence or such. No need for this, as it happens.</li>\n</ul>\n\n<p>We get</p>\n\n<pre><code>(defn infix-parse [expr]\n (if (seq? expr)\n (letfn [(next-op [val-stack op-stack remaining]\n (if next-op\n (let [prec (if (empty? remaining)\n ##-Inf\n (operator-precedence (first remaining)))\n [popped left] (split-with #(>= (operator-precedence %) prec) op-stack)\n result (reduce\n (fn [[a b & vals] op]\n (cons (list op b a) vals))\n val-stack\n popped)]\n (if (empty? remaining)\n (first result)\n (next-val result\n (cons (first remaining) left)\n (rest remaining))))))\n (next-val [val-stack op-stack remaining]\n (next-op (cons (infix-parse (first remaining)) val-stack)\n op-stack\n (rest remaining)))]\n (next-val () () expr))\n expr))\n</code></pre>\n\n<p><em>Flattening the Tail Recursions</em></p>\n\n<p>The above recurses on every token. Ouch! But these are tail recursions - hardly surprising since they derive from <code>recur</code>s. So we can flatten them using <code>trampoline</code>. </p>\n\n<p>The procedure is as follows:</p>\n\n<ul>\n<li>Wrap each recursive call as a parmeterless function - prefixing <code>#</code>\ndoes that.</li>\n<li>Insert <code>trampoline</code> into the initial call</li>\n</ul>\n\n<p>This produces ... </p>\n\n<pre><code>(defn infix-parse [expr]\n (if (seq? expr)\n (letfn [(next-op [val-stack op-stack remaining]\n ...\n #(next-val result\n (cons (first remaining) left)\n (rest remaining))))))\n (next-val [val-stack op-stack remaining]\n #(next-op (cons (infix-parse (first remaining)) val-stack)\n op-stack\n (rest remaining)))]\n (trampoline next-val () () expr))\n expr))\n</code></pre>\n\n<p>Is it worth it? I don't know. It certainly helped me understand the algorithm. However, there is a simpler approach. </p>\n\n<p><em>Amalgamating the alternating phases</em></p>\n\n<p>The phase alternation represents the alternation of operators and operands in any (horizontal) expression. So we can unroll the two phases of the operator-operand pair into one pass of the loop. This is easy because we are dealing with only binary operators. </p>\n\n<p>Modifying your code along these lines, I came up with the following: </p>\n\n<pre><code>(defn infix-parse [expr]\n (if-not (seq? expr)\n expr\n (loop [val-stack ()\n op-stack ()\n [opd op & expr] expr]\n (let [priority (if op (operator-precedence op) ##-Inf)\n [popped-ops unpopped-ops] (split-with\n #(>= (operator-precedence %) priority)\n op-stack)\n val-stack (reduce\n (fn [[right left & vals] op]\n (cons (list op left right) vals))\n (cons (infix-parse opd) val-stack)\n popped-ops)]\n (if-not op\n (first val-stack)\n (recur val-stack (cons op unpopped-ops) expr))))))\n</code></pre>\n\n<p>I've changed some of the names and inverted some <code>if</code>s to make the code easier to follow. I've also assumed that the expression is not allowed to be empty, and used destructuring to detect this case. </p>\n\n<p>I've also rebound the same names in <code>loop</code> and <code>let</code> where the new expression takes over the role of the old - yes, it's like assignment. I like doing so. Many don't.</p>\n\n<p>Finally, I rewrote your macro ...</p>\n\n<pre><code>(defmacro infix [& form]\n (infix-parse form))\n</code></pre>\n\n<p>... so that it accepts expressions inline:</p>\n\n<pre><code>user=> (infix 1 + 3 * (4 - 5) * 10 / 2)\n -14\n</code></pre>\n\n<p>Again, trivial stuff. </p>\n\n<p><strong>Appendix</strong></p>\n\n<p><em>Why your algorithm isn't quite the Dijkstra <a href=\"https://en.wikipedia.org/wiki/Shunting-yard_algorithm\" rel=\"nofollow noreferrer\">Shunting Yard Algorithm</a> (SYA) you refer to.</em></p>\n\n<ul>\n<li>You take in a Clojure form that is an <a href=\"https://en.wikipedia.org/wiki/Tree_(graph_theory)#Ordered_tree\" rel=\"nofollow noreferrer\">ordered tree</a> of tokens, where parentheses have disappeared into the structure of the tree. The SYA takes in a flat sequence of tokens that includes parentheses.</li>\n<li>You put out a tree of Clojure operator invocations, where operator scope/arity is resolved by the tree structure (which presents as parentheses). The SYA puts out a flat postfix (reverse Polish) token stream of operator invocations without parentheses, where the scope of each operator is resolved by its fixed arity. </li>\n<li>Your algorithm is explicitly recursive (in the last <code>recur</code>). The SYA\nis entirely iterative. </li>\n</ul>\n\n<p>To show that your algorithm is properly recursive, define</p>\n\n<pre><code>(defn nest [thing depth]\n (if (pos? depth)\n (recur (list thing) (dec depth))\n thing))\n</code></pre>\n\n<p>... , a function that wraps its first argument in as many lists as its second argument prescribes. For example, </p>\n\n<pre><code>user=> (nest :a 6)\n((((((:a))))))\n</code></pre>\n\n<p>Now ask <code>infix-parse</code> to handle a deeply parenthesised/nested expression:</p>\n\n<pre><code>user=> (do (infix-parse (nest -36 1E6)) :b)\nExecution error (StackOverflowError) at infix/infix-parse (infix.clj:34).\n</code></pre>\n\n<p>It runs out of stack space. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:00:50.960",
"Id": "419080",
"Score": "0",
"body": "You’re right that parentheses are handled by the compiler in this case; the core principle of the algorithm (maintaining monotonic stacks of ops and values) is the same though. My goal is to convert an infix expression to s-expressions - as the wikipedia article you linked says, shunting yard can also output ASTs, which is what I’m trying to do here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T23:14:20.610",
"Id": "419284",
"Score": "0",
"body": "@EricZhang SYA proper operates in two dimensions on the syntax tree: along and down. You are doing SYA *along* but *down* you are doing recursive descent. Whether you choose to call your hybrid algorithm SYA is of little consequence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T00:05:20.817",
"Id": "419391",
"Score": "0",
"body": "I agree with you, I am simply trying to solve the problem being posed, not an implementation of the \"proper\" shunting yard algorithm which as typically stated solves a slightly different task :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T14:19:28.643",
"Id": "419574",
"Score": "0",
"body": "I can now offer some constructive advice, instead of merely carping."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T12:53:37.500",
"Id": "216583",
"ParentId": "216123",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216130",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T20:34:32.063",
"Id": "216123",
"Score": "4",
"Tags": [
"algorithm",
"functional-programming",
"clojure",
"lisp",
"math-expression-eval"
],
"Title": "Parsing infix expressions in Clojure"
} | 216123 |
<p>The task:</p>
<blockquote>
<p>Given a list of numbers L, implement a method sum(i, j) which returns
the sum from the sublist L[i:j] (including i, excluding j).</p>
<p>For example, given L = [1, 2, 3, 4, 5], sum(1, 3) should return
sum([2, 3]), which is 5.</p>
<p>You can assume that you can do some pre-processing. sum() should be
optimized over the pre-processing step.</p>
</blockquote>
<pre><code>const lst = [1, 2, 3, 4, 5];
</code></pre>
<p>My functional solution:</p>
<pre><code>const sum = (i,j) => lst
.slice(i,j)
.reduce((acc, x) => acc + x, 0);
console.log(sum(1,3));
</code></pre>
<p>My imperative solution:</p>
<pre><code>function sum2(i,j) {
let sum = 0;
for(let k = i; k <j; k++) {
sum += lst[k];
}
return sum;
}
console.log(sum2(1,3));
</code></pre>
<p>I didn't understand the last part of the task, why pre-processing and optimizing is needed for a simple task like summing up sub elements of a list.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T21:49:58.013",
"Id": "418183",
"Score": "2",
"body": "Pre processing is done when you perform the same function many times on the same dataset. Eg Given `[0,1,2,3,4,5,6]` do `sum(0,3)`, `sum(2,4)`, `sum(3,6)`. The example shows a small datasets, but in real world apps datasets can be huge, millions, billions and more. This is when complexity makes the difference between seconds to compete or hours to complete. Pre processing can reduce the overall complexity"
}
] | [
{
"body": "<p>If they're asking for optimization I would generally understand that they want you to improve performance over multiple calls, they also talk about pre-processing so in this case I would consider caching or pre-calculating results. </p>\n\n<p>The trivial way would be to pre-calculate all the possible results.</p>\n\n<pre><code>let sums = []; \nfor (let i = 0; i<lst.length; i++) {\n sums[i] = [];\n for (let j = i; j < lst.length; j++) {\n sums[i][j] = lst\n .slice(i,j)\n .reduce((acc, x) => acc + x, 0);\n }\n}\n\nconst sum = (i,j) => sums[i][j];\n\nconsole.log(sum(1,3)); \n</code></pre>\n\n<p>This is fine for a 5 element array. You are doing 5 pre-calculations. If the array had a thousand elements that would be about 500,000 calculations (and 500,000). The trick to understand here is that <code>sum(i, j)</code> is equal to <code>sum2(i) - sum2(j)</code> where <code>sum2(x)</code> is the sum of all elements starting at <code>x</code>. So you could rewrite this as:</p>\n\n<pre><code>const sums = lst.map( (v,i) => lst.slice(i).reduce((acc, x) => acc + x) );\n\nconst sum = (i,j) => sums[i] - sums[j];\n\nconsole.log(sum(1,3)); \n</code></pre>\n\n<p>Although it is a personal preference, I would calculate the values on demand, something like this:</p>\n\n<pre><code>let sums = []; \n\nconst sum = (i,j) => sum2(i) - sum2(j);\n\nconst sum2 = (k) => {\n if (!sums[k] ) {\n console.log(`calculating _sum(${k})`);\n sums[k] =\n lst\n .slice(k)\n .reduce((acc, x) => acc + x, 0);\n }\n return sums[k];\n}\n\nconsole.log(sum(1,3)); \nconsole.log(sum(2,3)); \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T16:54:45.133",
"Id": "216180",
"ParentId": "216124",
"Score": "3"
}
},
{
"body": "<p>The problem as a single call is trivial at best with the optimal solution being</p>\n\n<pre><code>const values = [1,2,3,4,5,6,7,8,9];\nfunction sum(i,j) {\n var sum = 0;\n while(i < j) { sum += values[i++] }\n return sum;\n}\n</code></pre>\n\n<h2>Caching is impractical</h2>\n\n<p>The answer by <a href=\"https://codereview.stackexchange.com/a/216180/120556\">Marc Rohloff</a> suggests that caching the results is one way to do this. It has some flaws. <span class=\"math-container\">\\$O(n^2)\\$</span> storage <span class=\"math-container\">\\$O(n^3)\\$</span> complexity to get all possible solutions and make have sum perform at <span class=\"math-container\">\\$O(1)\\$</span></p>\n\n<h2>Much in little, MIP maps</h2>\n\n<p>This problem is very similar to a CG problem regarding the rendering of images. To avoid small versions of a larger image looking pixelated each rendered pixel is the mean of the many pixels it represented. In other words a rendered pixel is <code>sumPixels(a,b) / (b-a)</code> (pixels from <code>a</code> to <code>b</code>) which is identical to this problem.</p>\n\n<p>The solution was called MIP mapping (MIP is for the Latin \"multum in parvo\", meaning \"much in little\") (now more often called mipmaps)</p>\n\n<p>Mipmaps work by pre processing the image, creating multiple copies, each copy is half the size of the previous image. So for a square 256pixel image you would have to create a 8 more images of 128, 64, 32, 16, 8, 4, 2, and 1 pixels (normally the maps would be limited to only a few steps)</p>\n\n<p>The storage thus becomes <span class=\"math-container\">\\$O(2n)\\$</span> and the same for the pre-processing complexity. In other words a pre-processing <span class=\"math-container\">\\$O(n)\\$</span> storage and processing solution to the problem of summing continuous sets from a larger set. </p>\n\n<p>The rendering per pixel was typically <span class=\"math-container\">\\$O(2)\\$</span> or <span class=\"math-container\">\\$O(1)\\$</span> </p>\n\n<h2>Applying the MIP</h2>\n\n<p>In javascript we can create a function that will return a function. That means we can use closure to encapsulate the pre-processed data.</p>\n\n<p>As we need the precise value for each set we can not use the CG mipmap method as it calculates a near enough approximation. To get the precise value we need a little more complexity. Its something near <span class=\"math-container\">\\$O(log(log(n))\\$</span> per sum</p>\n\n<h2>First the pre-processing</h2>\n\n<p>We create multiple maps each half the size of the previous map. We use the results of the previous map to calculate the new map. As some map sizes can not be divided by two we need to tack on some zeros</p>\n\n<pre><code>function createSumFunction(array) {\n const mipMaps = [array];\n (function () {\n var from = array;\n while(from.length > 2) {\n let i = 0;\n const to = [];\n while(i < from.length) {\n to.push(from[i++] + (from[i] !== undefined ? from[i] : 0));\n i++;\n }\n mipMaps.push(to)\n from = to;\n } \n mipMaps.push([from[0] + from[1]]);\n })();\n\n // more code to follow\n</code></pre>\n\n<h2>Getting the sum</h2>\n\n<p>The inputs are <code>i</code> and <code>j</code>. (left and right)</p>\n\n<p>First thing is reduce <code>j</code> by 1</p>\n\n<p>To get the sum we start at the first map, from the left if we are at an odd position get the value to the left and add that value to a sum for the left side. For the right side we do the same but rather if we are at an even location get the value to the right and add it to the sum for the right side.</p>\n\n<p>The half and round the values for i, and j and step to the next map up (half sized). If <code>i === j</code> get the value at i and subtract the left sum and right sum. The result is the value we are after.</p>\n\n<p>The max number of steps will be <span class=\"math-container\">\\$O(log(n))\\$</span> and the min will be <span class=\"math-container\">\\$O(1)\\$</span></p>\n\n<p>The second half of the solution returning the sum function. Note, it is missing some argument vetting, see snippet at bottom for better argument vetting.</p>\n\n<pre><code>return function(i,j) {\n j--;\n var k = 0, subL = 0, subR = 0;\n while(k < mipMaps.length) { // could also be while(true)\n const m = mipMaps[k ++];\n subL += i % 2 ? m[i - 1] : 0;\n subR += j % 2 ? 0 : m[j + 1];\n i >>= 1;\n j >>= 1;\n if (i === j) { return mipMaps[k][i] - subL - subR }\n }\n}\n</code></pre>\n\n<h2>Solution pre <span class=\"math-container\">\\$O(n)\\$</span> RAM/CPU and <code>sum</code> <span class=\"math-container\">\\$O(1)\\$</span> RAM <span class=\"math-container\">\\$O(log(n))\\$</span> CPU</h2>\n\n<p>As one function that does the pre process and returns the sum function. Add some checks to the sum input to ensure that the values i,j are not in conflict. It is assumed that they are in range. It is also assumed that the input array is more than 1 item long (or what would the point be?)</p>\n\n<p>I have only tested positive values (but assume it will work for all numbers) and I have only tested for power of two array sizes, I leave that for you to work out (hint the right side may not end at an odd index)</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function createSumFunction(array) {\n const mipMaps = [array];\n (()=>{ // to keep closure clean\n var from = array;\n while (from.length > 2) {\n let i = 0;\n const to = [];\n while(i < from.length) {\n to.push(from[i++] + (from[i] !== undefined ? from[i] : 0));\n i++;\n }\n mipMaps.push(to)\n from = to;\n }\n mipMaps.push([from[0] + from[1]]);\n })();\n return function(i, j) {\n var k = 0, subL = 0, subR = 0;\n if (i === j) { return NaN }\n if (j < i) { [j, i] = [i, j] }\n j--;\n if (i === j) { return mipMaps[0][i] }\n while (k < mipMaps.length) { // could also be while(true)\n const m = mipMaps[k ++];\n subL += i % 2 ? m[i - 1] : 0;\n subR += j % 2 ? 0 : m[j + 1]; // << hint fix\n i >>= 1;\n j >>= 1;\n if (i === j) { return mipMaps[k][i] - subL - subR }\n }\n }\n}\nconst sum = createSumFunction([1,2,3,4,5,6,7,8,1,2,3,4,5,6,7,8]);\nconsole.log(sum(0,16));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T22:19:29.107",
"Id": "216195",
"ParentId": "216124",
"Score": "2"
}
},
{
"body": "<p>You may always chose an imperative way for efficiency and use a <code>for</code> or <code>while</code> loop but if you would like to remain in functional abstraction an O(n) efficient way could be;</p>\n\n<pre><code>var sum = (ar,si,ei) => ar.reduce((p,c,i) => i >= si && i < ei ? p + c : p, 0);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T22:20:25.160",
"Id": "216378",
"ParentId": "216124",
"Score": "2"
}
},
{
"body": "<p>The simplest thing that comes into my mind is have a hashmap to cache sum of all the elements from position i to the end</p>\n\n<p>for L = [1, 2, 3, 4, 5] the map would look like</p>\n\n<pre><code>Index | sum till end\n 0 | 15\n 1 | 14\n 2 | 12\n 3 | 9\n 4 | 5\n</code></pre>\n\n<p>once you have this you can do something like this</p>\n\n<pre><code>public int sum(int i, int j) {\n return map.get(i) - map.get(j);\n}\n</code></pre>\n\n<p>for example sum(1,3) is</p>\n\n<pre><code>map.get(1) = 14\nmap.get(3) = 9\nresult = 5;\n</code></pre>\n\n<p>Here preprocessing reduces the runtime complexity to O(1)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-09T22:12:30.017",
"Id": "236946",
"ParentId": "216124",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216195",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T20:47:43.633",
"Id": "216124",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming"
],
"Title": "Sum of a sublist"
} | 216124 |
<p>I am building a calculator and I'm aware of what these functions do.</p>
<p>What I basically want feedback on is: Do I need to comment this or is there sufficient information to ascertain its purpose:</p>
<pre><code>function percentOfValue(percentage, of) {
return (percentage / 100) * of;
}
function whatPercentOfValue(small, large) {
return (small / large) * 100
}
</code></pre>
| [] | [
{
"body": "<p>Code level comments usually lose their context if not properly maintained. Using self descriptive variable names is a good choice. Appreciate your efforts in keeping the code highly readable.</p>\n\n<ul>\n<li><p>First method, is trying to get the Percentage value, I would update the method definition to <code>getPercentOfValue(from, percentage)</code>.</p></li>\n<li><p>Second method, is trying to calculate percent rate, I would update the method definition to <code>getPercentRate(newValue, originalValue)</code> to follow the terminology in formula.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T08:11:57.460",
"Id": "418211",
"Score": "0",
"body": "A couple of small changes that give absolute clarity, thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T10:35:34.927",
"Id": "418230",
"Score": "0",
"body": "I'd suggest not to use the prefix `get` as these are not \"getters\" as customarily used in Java. Instead use, for example, `calc(ulate)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T23:12:27.650",
"Id": "418329",
"Score": "0",
"body": "Thankyou @RoToRa that does make sense if it would change the perceived use. Other than that change, I think its fairly self explanitory, to be fair it may never see the light of day after I close up this development session but you never know so i would rather not be beating myself up down the road for not making commenting it or making it readable. I am of the principle that a comment should only be used when there is no way to make it obvious. I hope ive managed that here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T00:55:18.760",
"Id": "216132",
"ParentId": "216126",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216132",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T21:26:06.220",
"Id": "216126",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "JavaScript percentage calculation functions"
} | 216126 |
<p>I wanted to write a commandline scipt to generate diceware passwords based on the <a href="https://www.eff.org/de/deeplinks/2016/07/new-wordlists-random-passphrases" rel="nofollow noreferrer">EFF diceware list</a>.</p>
<p>The script (<code>diceware_password.py</code>) can be found below. It was originally developed for Python 2, but I want it to be compatible with Python 3 as well (both versions have been tested on my machine).
Running it with no arguments will generate a 6 word password as recommended by the EFF. Additionally, you may also input dice throws made in the "real world".<br/>
<strong>Note:</strong> You need to download the EFF's <a href="https://www.eff.org/files/2016/07/18/eff_large_wordlist.txt" rel="nofollow noreferrer">large wordlist</a> for the script to work. It assumes the default filename, but you can pass other filenames using the <code>--wordlist</code> flag.</p>
<p>Any feedback is very welcome, especially on the clarity of the code, as well as Python 2/3 compatibility best practices.</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import random
import codecs
import argparse
import six.moves
def large_wordlist_from_file(fname, sep="\t"):
"""Read an EFF compatible large wordlist from file"""
word_dict = {}
with codecs.open(fname, encoding="utf-8", mode="rb") as file_:
while True:
line = file_.readline()
if line:
key, word = line.strip().split(sep)
word_dict[tuple(int(i) for i in key)] = word
else:
break
return word_dict
def roll_dices(nrolls, ndices=5):
"""Rolls a number of dices (default: 5) n times"""
rng = random.SystemRandom()
return tuple(
tuple(rng.randrange(1, 7) for _ in six.moves.range(ndices)) for _ in six.moves.range(nrolls)
)
def validate_dice_rolls(roll_sequences):
"""Validate dice sequences from user input"""
rolls = []
for roll_sequence in roll_sequences:
roll = []
for throw in roll_sequence:
if not (1 <= int(throw) <= 6):
raise ValueError("Each throw must be between 1 and 6.")
roll.append(int(throw))
if len(roll) != 5:
raise ValueError("Each roll sequence has to be of length 5 "
"to work with the EFF wordlist!")
rolls.append(tuple(roll))
return rolls
def get_interactive_dice_rolls():
"""Enter your dice throws on the command line"""
rolls = []
while True:
user_input = six.moves.input("Please enter your dice sequences: ")
roll_sequence = user_input.strip().split(" ")
try:
rolls = validate_dice_rolls(roll_sequence)
break
except ValueError as ex:
print("Failed to parse your input for the following reason: "+ex.message)
user_input = six.moves.input("Do you want to try again? (y/n) ")
user_input = user_input.strip().lower()
if user_input.startswith("n"):
break
return rolls
def main():
"""Commandline script to generate diceware passwords"""
parser = argparse.ArgumentParser(
description="Generate diceware passwords with N words. "
"EFF recommendation is N >= 6."
)
parser.add_argument(
"n", metavar="N", type=int, nargs="?", default=6,
help="number of diceware words (default: 6)",
)
parser.add_argument(
"--real-dice", type=str, nargs="*", metavar="DICE_SEQUENCE",
help="instead of using PRNG, use your given dice throws. "
"Please group them in N DICE_SEQUENCEs of length 5 seperated "
"by a space"
)
parser.add_argument(
"--wordlist", type=str, nargs="?", default="eff_large_wordlist.txt",
help="The diceware wordlist to use. This script assumes the list to "
"contain one word per line where each word is preceeded by its "
"'dice' index. Index and word are separated by a single tab. "
"(default: \"eff_large_wordlist.txt\")"
)
parser.add_argument(
"--interactive", action="store_true", default=False,
help="Interactive mode allows you to enter your dice sequences via "
"command prompt in order to avoid traces in your bash history"
)
args = parser.parse_args()
words = large_wordlist_from_file(args.wordlist, "\t")
rolls = []
if args.real_dice is not None:
rolls = validate_dice_rolls(args.real_dice)
elif args.interactive:
rolls = get_interactive_dice_rolls()
else:
rolls = roll_dices(args.n, 5)
if rolls:
# print the result
try:
print(" ".join(words[roll] for roll in rolls))
except KeyError:
print(list(words.keys()))
if __name__ == "__main__":
main()
</code></pre>
| [] | [
{
"body": "<p>Overall this looks pretty good. One very important problem: you are using <code>random</code> to generate the random numbers. Python documetation has the important warning:</p>\n<blockquote>\n<p>Warning</p>\n<p>The pseudo-random generators of this module should not be used for security purposes. For security or cryptographic uses, see the secrets module.</p>\n</blockquote>\n<p>To fix this, you should use <code>secrets</code> which provides a <code>randbelow</code> function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T08:44:20.410",
"Id": "418215",
"Score": "3",
"body": "I used `SystemRandom` which was, if I correctly understood the [doc](https://docs.python.org/2/library/random.html), the way to go in Python 2. `secrets` seems to be new in Python 3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:02:37.643",
"Id": "418273",
"Score": "0",
"body": "Hmm, then you should probably have an if else for python2 vs 3 there. Secrets is almost certainly better than SystemRandom."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:46:02.993",
"Id": "418285",
"Score": "1",
"body": "Seems like the secret module's [implementation](https://github.com/python/cpython/blob/3.7/Lib/secrets.py#L25) also just uses `random.SystemRandom` in Python 3.7."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:46:20.890",
"Id": "418286",
"Score": "7",
"body": "@OscarSmith Nope, `secrets` _is_ `SystemRandom`. Ones of the first few lines in `secrets` are `from random import SystemRandom; _sysrand = SystemRandom()`…"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T03:39:07.517",
"Id": "216136",
"ParentId": "216128",
"Score": "2"
}
},
{
"body": "<p>What threw me off for a short while is your usage of <code>six.moves.range</code>, but I see now that it is for compatibility. However, you can make this usage more transparent by importing it like this:</p>\n\n<pre><code>from six.moves import range\n</code></pre>\n\n<p>I would also use <code>random.SystemRandom().randint</code> instead of <code>randrange</code> because it is inclusive and makes it that slight bit more readable. Note \"dice\" is already the plural of \"die\", \"dices\" is not an English word.</p>\n\n<pre><code>RNG = random.SystemRandom()\n\ndef roll_dice(nrolls, ndice=5):\n \"\"\"Rolls a number of dice (default: 5) n times\"\"\"\n return [[RNG.randint(1, 6) for _ in range(ndice)] for _ in range(nrolls)]\n</code></pre>\n\n<p>I also made the random number generator a global constant, no need to redefine that every time you roll the dice and made it list comprehensions instead of tuples on generator expressions, mostly so it fits into one line.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T09:22:23.547",
"Id": "216226",
"ParentId": "216128",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216226",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T21:38:45.233",
"Id": "216128",
"Score": "6",
"Tags": [
"python",
"dice"
],
"Title": "Generate EFF diceware passwords with Python"
} | 216128 |
<p>what I am loading a yaml file and updating it with argparse. what is your feedback on how to update yaml parameters automatically without checking if a argparse parameter is None.
There are almost 20 configuration parameters that with this current version I have to put 20 <code>if</code> conditions.</p>
<p>the output of yaml.save_load is:</p>
<pre><code>import os
import argparse
import yaml
import functools
import datetime
parser = argparse.ArgumentParser()
parser.add_argument(
"--config",
nargs="?",
type=str,
default="p.yml",
help="Configuration file to use",
)
parser.add_argument('--learning_rate', type=float, default=0.001, help='learning rate amount')
args = parser.parse_args()
def yaml_dump(file_path, data):
"""
Write data into yaml file in file_path
:param file_path:
:param data:
:return: void
"""
with open(file_path, 'w') as file_descriptor:
yaml.safe_dump(data, file_descriptor)
def yaml_loader(file_path):
"""
Load yaml file
:param file_path:
:return: yaml file configuration
"""
with open(file_path, "r") as file_descriptor:
return yaml.safe_load(file_descriptor)
cfg = yaml_loader(args.config)
if args.learning_rate is not None:
cfg['training']['optimizer']['lr'] = args.learning_rate
ts = str(datetime.datetime.now()).split(".")[0].replace(" ", "_")
ts = ts.replace(":", "_").replace("-", "_")
logdir = os.path.join("runs", os.path.basename(args.config)[:-4], ts)
yaml_dump(os.path.join(logdir, args.config.split('/')[-1]), cfg)
</code></pre>
<p>here is the content of <code>p.yaml</code> file:</p>
<pre><code>model:
arch: fcn8s
data:
dataset: pascal
train_split: train
val_split: val
img_rows: 'same'
img_cols: 'same'
path: VOC/
sbd_path: VOC/benchmark_RELEASE/
training:
train_iters: 300000
batch_size: 1
val_interval: 1000
n_workers: 16
print_interval: 50
optimizer:
name: 'sgd'
lr: 1.0e-10
weight_decay: 0.0005
momentum: 0.99
loss:
name: 'cross_entropy'
size_average: False
lr_schedule:
resume: fcn8s_pascal_best_model.pkl
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T22:19:17.000",
"Id": "418187",
"Score": "2",
"body": "Welcome to Code Review! Code Review is a platform where you can get feedback from other users on *working* code. Questions on how to fix certain errors are better suited for Stack Overflow. See also [How to ask](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T22:29:18.263",
"Id": "418188",
"Score": "0",
"body": "@Alex I have updated the code with a working code. now I am asking other users about their feedback on how to make it more efficient. Is it still not suited for StackExchange?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T22:32:55.037",
"Id": "418189",
"Score": "2",
"body": "There's a space before `def yaml_dump` please ensure that this code does run :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T22:42:14.683",
"Id": "418190",
"Score": "0",
"body": "@Peilonrayz it has been corrected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T23:30:23.557",
"Id": "418191",
"Score": "1",
"body": "Depending on how the file is used, PyYAML is not really suited for this kind of updating. If the file needs to stay as much the same as possible, e.g. when it is checked into a revision control system, you'll run into spurious changes, like the key order of mappings, loss of superfluous quotes, and if there had been comments those are lost as well. You also have to adhere to YAML 1.1 (replaced in 2009 by YAML 1.2, which PyYAML hasn't been updated to)."
}
] | [
{
"body": "<p>While you cannot iterate over a <code>Namespace</code> directly, you can parse it into a dictionary using <code>vars</code> and iterate over that, if you have a mapping from the argparse name to the path in the config file. The hardest part is using this path to get to the right level in the dictionary:</p>\n\n<pre><code>from argparse import Namespace\n\n# Hard-code command line arguments instead of parsing them\nargs = Namespace(learning_rate=0.001)\n# fake having read the config file\ncfg = {\"training\": {\"optimizer\": {\"lr\": 0}}}\n# mapping from argparse name to path in config file\ncfg_path = {\"learning_rate\": ('training', 'optimizer', 'lr')}\n\nfor name, value in vars(args).items():\n if value is None:\n continue\n # go down to right level\n d = cfg\n keys = cfg_path[name]\n for key in keys[:-1]:\n d = d[key]\n # assign value, using the fact that dictionaries are mutable\n d[keys[-1]] = value\n</code></pre>\n\n<p>This will override values where you have a default value in argparse that is not <code>None</code>, which may for example change the order in which elements appear in your dictionaries.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T13:11:07.113",
"Id": "216164",
"ParentId": "216129",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T21:59:24.363",
"Id": "216129",
"Score": "-1",
"Tags": [
"python",
"yaml"
],
"Title": "PyYaml - overwrite yaml file automatically with inserted argparse parameters"
} | 216129 |
<p>As part of a personal project, I wanted to make a stopwatch with Python. I wish to show my friend but at the moment it is a little messy and long. Is there any way to make it more compact or easier to read?</p>
<pre><code> #stopwatch
from tkinter import*
import time
root=Tk()
root.configure(background=("black"))
root.title("stopwatch")
root.geometry("1000x800")
time_elapsed1=0
time_elapsed2=0
time_elapsed3=0
i=0
j=0
time1=0
def create_label(text,_x,_y):
label = Label(root, text=text,fg='white', bg="black",font=("default",10,"bold"))
label.place(x=_x,y=_y,width=100,height=45)
def start():
start_button.place_forget()
stop_button.place(x = 20, y = 300, width=300, height=100)
global time_elapsed1,time_elapsed2,time_elapsed3,time1,self_job,time2
time2=int(time.time())
if time2!=time1:
time1=time2
if time_elapsed1<59:
time_elapsed1+=1
clock_frame.config(text=str(time_elapsed3) + ":" + str(time_elapsed2)+ ":" + str(time_elapsed1))
else:
time_elapsed1=0
if time_elapsed2<59:
time_elapsed2+=1
clock_frame.config(text=(str(time_elapsed3) + ":" + str(time_elapsed2)+ ":" + str(time_elapsed1)))
else:
time_elapsed2=0
if time_elapsed3<23:
time_elapsed3+=1
clock_frame.config(text=(str(time_elapsed3) + ":" + str(time_elapsed2)+ ":" + str(time_elapsed1)))
else:
print("you left it on for too long")
self_job=root.after(1000,start)
def stop():
global self_job
if self_job is not None:
root.after_cancel(self_job)
self_job = None
stop_button.place_forget()
start_button.place(x = 20, y = 300, width=300, height=100)
def clear():
global time_elapsed1,time_elapsed2,time_elapsed3,time1,self_job,time2,label,i,j
try:
stop()
except:
start()
stop()
clock_frame.config(text="0:0:0")
time_elapsed1=0
time_elapsed2=0
time_elapsed3=0
time_1=0
time_2=0
i=0
j=0
wig=root.winfo_children()
for b in wig:
b.place_forget()
start_button.place(x = 20, y = 300, width=300, height=100)
lap_button.place(x = 660, y = 300, width=300, height=100)
reset_button.place(x = 340, y = 300, width=300, height=100)
clock_frame.place(x = 200, y = 50, width=600, height=200)
def lap():
global time_elapsed1,time_elapsed2,time_elapsed3,time1,self_job,time2,i,j
if i<9:
create_label((str(time_elapsed3)+":"+str(time_elapsed2)+ ":" + str(time_elapsed1)),20+(110*i),400+(j*50))
else:
j+=1
i=0
create_label((str(time_elapsed3)+":"+str(time_elapsed2)+ ":" + str(time_elapsed1)),20+(110*i),400+(j*50))
i+=1
clock_frame=Label(text="0:0:0",bg="black",fg="blue",font=("default",100,"bold"))
start_button=Button(text="START",bg="green",fg="black",command=start,font=("default",50,"bold"))
stop_button=Button(text="STOP",bg="red",fg="black",command=stop,font=("default",50,"bold"))
lap_button=Button(text="LAP",bg="#4286f4",fg="black",command=lap,font=("default",50,"bold"))
reset_button=Button(text="RESET",bg="orange",fg="black",command=clear,font=("default",50,"bold"))
start_button.place(x = 20, y = 300, width=300, height=100)
lap_button.place(x = 660, y = 300, width=300, height=100)
reset_button.place(x = 340, y = 300, width=300, height=100)
clock_frame.place(x = 200, y = 50, width=600, height=200)
root.mainloop()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T07:23:39.467",
"Id": "418205",
"Score": "0",
"body": "Welcome to Code Review! [Self answers](https://codereview.stackexchange.com/help/self-answer) are welcome here, too: things to consider include the [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/#documentation-strings)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T14:15:43.550",
"Id": "418266",
"Score": "0",
"body": "Thanks, greybeard-will look into it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T16:58:17.333",
"Id": "418295",
"Score": "0",
"body": "Can you add comments to the code you posted? It is a little hard to understand what each function or if/else block is doing. You will be more likely to get answers if you make it easy to understand what you need."
}
] | [
{
"body": "<p>Have you learned how to make objects in Python? Typically when you have a GUI, you want to have a class in charge of displaying all the GUI pieces, and it has reference to an object such as a <code>Stopwatch</code> that takes care of all of the logic. Stopwatch class would look something like this:</p>\n\n<pre><code>import time\n\nclass Stopwatch:\n def __init__(self):\n self.start_time = 0\n self.laps = []\n\n def start(self):\n # Implement your starting of the timer code here\n self.start_time = time.time()\n\n def lap(self):\n # Implement your lapping logic\n lap = time.time()\n self.laps.appen(lap)\n\n def stop(self):\n # Implement your stop timer logic\n elapsed = time.time() - self.start_time\n\n def reset(self):\n # Implement your watch reset logic here\n self.start_time = 0\n\n def display_time(self):\n # Return the time to display on the GUI\n elapsed = time.time() - self.start_time\n # Figure out how to break the time into hour:minute:second\n # The time class might even have convenience functions for this sort of thing, look up the documentation\n display = elapsed # after you made it look nice\n return display\n\n</code></pre>\n\n<p>Then in the GUI code you can make a Stopwatch object and let it take care of the messy work of saving times and doing math with them. The GUI class is just concerned with showing stuff the right way. Might look something like (minus positioning all the GUI components):</p>\n\n<pre><code># GUI\nroot = Tk()\nroot.configure(background=(\"black\"))\nroot.title(\"stopwatch\")\nroot.geometry(\"1000x800\")\n\nstopwatch = Stopwatch()\n\ndef create_label(text,_x,_y):\n label = Label(root, text=text,fg='white', bg=\"black\",font=(\"default\",10,\"bold\"))\n label.place(x=_x,y=_y,width=100,height=45)\n\ndef setup():\n pass\n # Create all of the GUI components and build all the visuals\n\ndef start():\n stopwatch.start() # let it do the logical work\n # do your GUI updates\n create_label(stopwatch.display_time())\n stop_button.place() \n\ndef stop():\n stopwatch.stop() # Logic and math here\n # Do GUI updates for stop\n create_label(stopwatch.display_time())\n\ndef clear():\n stopwatch.reset() # Logic again handled in the Stopwatch class\n # Clean up GUI components\n\ndef lap():\n # The Stopwatch class can keep a list of all lap times and make your life easier\n stopwatch.lap() \n # Next update the GUI\n create_label(stopwatch.display_time())\n\n# Good form to have all the logic run inside functions \n#instead of hanging around to be accidentally executed\nif __name__ == \"__main__\":\n setup()\n root.mainloop()\n</code></pre>\n\n<p>It will clean up your code and make it easier for you to make changes. The sooner you can learn how to use Objects, the easier your life will become, no matter the language! I leave it up to you to Google the best tutorials on Python objects.</p>\n\n<p>Finally, if you are confused on where Stopwatch class should go, best practice would be to create a file called \"stopwatch.py\" and paste the Stopwatch class in that file. Then in your main file that is running the code, import that stopwatch by calling <code>from stopwatch import Stopwatch</code>. As long as the stopwatch.py file is right next to your main file, it should be able to import it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T17:26:33.953",
"Id": "216181",
"ParentId": "216131",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-24T22:47:43.660",
"Id": "216131",
"Score": "3",
"Tags": [
"python",
"timer",
"tkinter"
],
"Title": "Tkinter stopwatch"
} | 216131 |
<p>I have been reading about passwords and hashing algorithms and what not and decided to write a program.</p>
<p>Overview: The user should be prompted to create a password the first time the program is executed. They should enter a key and confirm it. If they have executed the program previously, then they should just enter the password to gain access.</p>
<p>I determine if the user has run the program by checking if key.txt exists. Is there a more preferred method?</p>
<p>I tried to streamline some code with the two bool functions. Any other suggestions for cleaner or more concise code?</p>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
#include "sha256.h"
using namespace std;
bool keyExists() {
bool keyExists = false;
ifstream inFile("key.txt");
if (inFile) {
keyExists = true;
}
return keyExists;
}
bool isMatch(string key, string confirmKey) {
bool match = false;
if (key == confirmKey) {
match = true;
}
return match;
}
int main() {
if (keyExists()) {
string key;
string storedKey;
cout << "Please enter key: ";
getline(cin, key);
SHA256 sha256;
ifstream inFile("key.txt");
getline(inFile, storedKey);
if (isMatch(sha256(key), storedKey)) {
cout << "Acces Granted!\n";
}
else {
cout << "Access Denied!\n";
}
}
else {
string key;
string confirmKey;
cout << "Please create a key: ";
getline(cin, key);
cout << "Confirm key: ";
getline(cin, confirmKey);
if (isMatch(key, confirmKey)) {
SHA256 sha256;
ofstream outFile("key.txt");
outFile << sha256(key);
}
else {
cout << "Keys do not match!\n";
}
}
return 0;
}
</code></pre>
<p>Many thanks to Stephan Brumme for the awesome <a href="https://create.stephan-brumme.com/hash-library/" rel="noreferrer">hashing algorithm code</a>! This was very easy to implement. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T07:18:27.317",
"Id": "418203",
"Score": "2",
"body": "I realize that this is just a test program to play with cryptography, hashing, and security. As a further exercise, could you think of ways this can be hacked and their mitigation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T16:17:55.343",
"Id": "418291",
"Score": "0",
"body": "Well, I guess it could be brute forced. To mitigate that I should set a max number of attempts before lockout. There is also a possibility of a collision. However, from my understanding sha256 is fairly robust in this regard. Salting the hash could mitigate many factors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T18:17:06.087",
"Id": "418312",
"Score": "0",
"body": "how about if I swap out the key.txt with I file of my own?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T18:21:55.857",
"Id": "418313",
"Score": "0",
"body": "@TomG Wow. Good point. I wouldn't know what to do in that scenario.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:22:59.347",
"Id": "418426",
"Score": "0",
"body": "Salting the hash is necessary. There are plenty of rainbow tables of millions of pre-hashed passwords. searching these for passwords is trivial. Rather than a single password how about multiple users each with their own password and random generated salt."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:24:41.277",
"Id": "418428",
"Score": "1",
"body": "How about adding a increasing delay after each failed attempt. Say 0.25 seconds 0.5 seconds 1 second 2 seconds (double each time). This kind of delay will not affect a human user who knows the password but will severely affect a machine trying to brute force an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T16:07:22.253",
"Id": "418457",
"Score": "0",
"body": "@MartinYork That is a great idea. Time to research how to implement a delay! :)"
}
] | [
{
"body": "<h1>1.</h1> \n\n<p><strong>Do not use</strong> </p>\n\n<pre><code>using namespace std; \n</code></pre>\n\n<p>Instead you can use </p>\n\n<pre><code>using std::cout; \nusing std::getline();\nusing std::ifstream;\nusing std::ofstream;\nusing std::cin;\nusing std::string; \n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Here</a> is a link to why we should avoid <code>using namespace <name>;</code> type of statements</p>\n\n<h1>2.</h1> \n\n<p>In the function <code>bool keyExists();</code> your <strong>bool variable</strong> is not necessary you can directly return the output of expression inside <strong>if condition</strong>. Same can be done in the other bool function, if you worry about readability then you <strong>may add a comment line</strong> after the return statement stating the intent behind the return value. </p>\n\n<p>Also you can define both bool functions as <strong>inline</strong>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T09:40:15.023",
"Id": "418223",
"Score": "1",
"body": "You missed `std::getline()`, `std::ifstream`, `std::ofstream`, `std::cin` and `std::string`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T11:33:54.840",
"Id": "418238",
"Score": "0",
"body": "@TobySpeight I am sorry for that, I will edit my answer. I tried to answer using my phone and so there were some restrictions with format and the amount of content I could put in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:12:36.857",
"Id": "418415",
"Score": "0",
"body": "Don't use the `using` clause at all. `std::` is not that hard to type."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T06:32:09.593",
"Id": "216140",
"ParentId": "216133",
"Score": "0"
}
},
{
"body": "<ol>\n<li><p><code>Using namespace std</code> isn't a good practice in header files, where your program should at least partially reside, because you introduce potential name conflicts. So don't do that, and prefix the names you're importing with <code>std::</code>, you'll get used to it in no time.</p></li>\n<li><p>Your function <code>keyExists</code> can be improved upon. First, its name is not the best you could have found, because it suggests you're looking for the existence of a particular key, whereas what you really want to know if the program has been launched before. So <code>is_first_use</code>, or <code>is_first_visit</code> as an analogy to a website, would tell more. Besides, it doesn't have to be that verbose:</p></li>\n</ol>\n\n<p><strong>Original version</strong></p>\n\n<pre><code>bool keyExists() {\n bool keyExists = false; // the homonymy is a bad idea\n ifstream inFile(\"key.txt\");\n\n if (inFile) { \n keyExists = true; // \n }\n\n return keyExists;\n}\n</code></pre>\n\n<p><strong>first trimming</strong></p>\n\n<pre><code>bool keyExists() {\n bool keyExists = false;\n ifstream inFile(\"key.txt\");\n\n keyExists = inFile; // because streams can be converted to bool as you know\n\n return keyExists;\n}\n</code></pre>\n\n<p><strong>second trimming</strong></p>\n\n<pre><code>bool keyExists() {\n ifstream inFile(\"key.txt\");\n return inFile; // you specified the return type, so the conversion will occur\n}\n</code></pre>\n\n<p><strong>third trimming</strong></p>\n\n<pre><code>bool keyExists() {\n return ifstream(\"key.txt\"); // no need for a named object\n}\n</code></pre>\n\n<p>So do you really need a function? It depends. If you want to let your program evolve from here, it's a good idea to keep the function, and implement a more viable test at a later point without disturbing the rest of your code. Otherwise it isn't worth the burden of finding a name for it.</p>\n\n<ol start=\"3\">\n<li>Your function <code>isMatch</code> suffers from the same issue. </li>\n</ol>\n\n<p><strong>original version</strong></p>\n\n<pre><code>bool isMatch(string key, string confirmKey) {\n\n bool match = false;\n if (key == confirmKey) {\n match = true;\n }\n\n return match;\n}\n</code></pre>\n\n<p><strong>suggested implementation</strong></p>\n\n<pre><code>bool isMatch(const string& key, const string& confirmKey) { // pass it by reference to avoid a potentially costly copy\n return key == confirmKey; // no need to store that in a `bool` before returning it\n}\n</code></pre>\n\n<p>Then again I'm not sure it needs a function of its own... </p>\n\n<ol start=\"4\">\n<li>What's a valid key?</li>\n</ol>\n\n<p>It might be a design choice, but it's very rare to allow for tabs, spaces and such inside a password. Is this really what you want? Is it compatible with every way to store passwords that you can think of? How would you constrain the choice of a password?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:54:06.210",
"Id": "418253",
"Score": "0",
"body": "I'd say it's very rare to *prohibit* tabs, spaces or any other characters within passwords; did you mistype something there?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T13:02:43.267",
"Id": "418258",
"Score": "0",
"body": "@TobySpeight: not at all, just a honest mistake"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T17:52:00.680",
"Id": "418302",
"Score": "0",
"body": "@papagaga Thanks you for your input! However, I get the following error when when trying to implement you suggestions: \"No suitable conversion function from std::ifstream to bool.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T11:17:58.830",
"Id": "418388",
"Score": "0",
"body": "@okkv1747vm: the conversion to `bool` is standard since C++11... If your compiler / standard library version is older, you should consider an upgrade if possible"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:51:47.317",
"Id": "216159",
"ParentId": "216133",
"Score": "6"
}
},
{
"body": "<p>Another thing to keep in mind when doing security focused applications is <a href=\"https://en.wikipedia.org/wiki/Reverse_engineering#Reverse_engineering_of_software\" rel=\"nofollow noreferrer\">reverse engineering</a>.<br>\nUsing that, a potential attacker can simply analyze your compiled program and then binary patch it to circumvent any security measures you have put in place.\nOf course in your case this is rather trivial because the source code is available. However even without the original source it can be possible to do so for example by looking for certain tell-tale strings.</p>\n\n<p>Running your program gives some great hints about program flow via the strings <code>Access Denied!</code> and <code>Access Granted!</code> respectively. If one were to analyze your program it would be easy to find references to above strings to pinpoint the location in your code that needs to be patched.<br>\nUltimately your program comes down to this part:</p>\n\n<pre><code>if (isMatch(sha256(key), storedKey)) {\n cout << \"Acces Granted!\\n\";\n}\nelse {\n cout << \"Access Denied!\\n\";\n}\n</code></pre>\n\n<p>Which when <a href=\"https://en.wikipedia.org/wiki/Disassembler\" rel=\"nofollow noreferrer\">disassembled</a> could look something like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/soYvV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/soYvV.png\" alt=\"access denied\"></a></p>\n\n<p>Notice how you can see part of your <code>if</code> statement, namely the condition test and then a jump (JNZ) as well as the message <code>Access Denied!</code>. if you follow the jump you will get to this part:</p>\n\n<p><a href=\"https://i.stack.imgur.com/3NXW8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3NXW8.png\" alt=\"access granted\"></a></p>\n\n<p>Which just happens to be the \"protected\" part of your program. The attacker now only has to \"patch\" the jump to always jump to the right location of your program regardless of user input.</p>\n\n<p>In order to protect against this you can read up on obfuscating programs and making them harder to <a href=\"https://en.wikipedia.org/wiki/Software_cracking\" rel=\"nofollow noreferrer\">\"crack\"</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:16:19.430",
"Id": "418417",
"Score": "0",
"body": "Using `obfuscating` is simply `security via obscurity` which is a know fallacy for security. It provides absolutely no protection and as such is simply bad advice. It will also make your application harder to read understand and maintain and thus more likely to have security issues in it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T21:34:50.210",
"Id": "216192",
"ParentId": "216133",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216159",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T01:09:36.703",
"Id": "216133",
"Score": "6",
"Tags": [
"c++",
"authentication"
],
"Title": "C++ simple password-protected console app"
} | 216133 |
<pre><code>public class Model extends TicTacToe
{
public static boolean hasWon( int [][] matrix )
{
boolean retVal = false;
//Check for horizontal win
for( int row = 0; row < matrix.length; row++ ){
int sum = 0;
for( int col = 0; col < matrix[0].length; col++ ){
sum += matrix[row][col];
}
if( sum == 5 ){
System.out.println("X wins.");
retVal = true;
} else if ( sum == -5 ) {
System.out.println("O wins.");
retVal = true;
}
}
//Check for vertical win
for( int col = 0; col < matrix[0].length; col++ ){
int sum = 0;
for( int row = 0; row < matrix.length; row++ ){
sum += matrix[row][col];
}
if( sum == 5 ){
System.out.println("X wins.");
retVal = true;
} else if ( sum == -5 ) {
System.out.println("O wins.");
retVal = true;
}
}
if( (matrix[0][0] + matrix[1][1] + matrix[2][2]+matrix[3][3]+matrix[4][4]) == 5 ){
System.out.println("X wins.");
retVal = true;
} else if ( (matrix[0][4] + matrix[1][3] + matrix[2][2]+matrix[3][1]+matrix[4][0]) == -5 ) {
System.out.println("O wins.");
retVal = true;
}
if( (matrix[0][4] + matrix[1][3] + matrix[2][2]+matrix[3][1]+matrix[4][0]) == 5){
System.out.println("X wins.");
retVal = true;
} else if ( (matrix[0][4] + matrix[1][3] + matrix[2][2]+matrix[3][1]+matrix[4][0]) == -5 ) {
System.out.println("O wins.");
retVal = true;
}
//Check for cat game
boolean foundSpace = false;
for( int row = 0; row < matrix.length; row++ ){
for( int col = 0; col < matrix[0].length; col++ ){
if( matrix[row][col] == 0 )
foundSpace = true;
}
}
if( foundSpace == false ){
System.out.println("Ends in tie.");
retVal = true;
}
return retVal;
}
}
public class View extends TicTacToe
{ public static void printBoard( int [][] matrix ){
for( int row = 0; row < matrix.length; row++ ){
for( int col = 0; col < matrix[row].length; col++ ){
if( matrix[row][col] == X )
System.out.print("X ");
else if(matrix[row][col] == O )
System.out.print("O ");
else
System.out.print(". ");
}
System.out.println("");
}
}
}
import java.util.Scanner;
public class Controller extends TicTacToe
{
Model model;
View view;
public Controller (Model model, View view) {
this.model= model;
this.view= view;
}
public static void main (String [] args)
{
Model model= new Model();
View view= new View();
Scanner input = new Scanner(System.in);
int [][] board = new int[5][5];
while( model.hasWon(board) == false){
//Get the X player input and make the change if not taken.
System.out.print("X, enter row: ");
int row = input.nextInt();
System.out.print("X, enter column: ");
int col = input.nextInt();
if(col<=4 && col>= 0)
{
if( board[row][col] == 0 )
board[row][col] = X;
view.printBoard(board);
}
else
System.out.println("Invalid Input");
//Check to see if X's move won the game. If so, break out of game loop
if( model.hasWon(board) == true )
break;
//Get the O player input and make the change if not taken.
System.out.print("O, enter row: ");
row = input.nextInt();
System.out.print("O, enter column: ");
col = input.nextInt();
if(col<=4 && col>= 0)
{
if( board[row][col] == 0 )
board[row][col] = O;
view.printBoard(board);
}
else
System.out.println("Invalid Input");
}
System.out.println("Game over.");
}
}
public class TicTacToe
{
static final int X =1;
static final int O = -1;
}
</code></pre>
<p>This is what I have so far to make a Java console MVC-based tic-tac-toe can anyone help me to see if I am right? Any help appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T08:50:47.610",
"Id": "418216",
"Score": "3",
"body": "You should learn `interface`s and `enum`s before MVC."
}
] | [
{
"body": "<p>welcome to code review and thanks for sharing your code.</p>\n\n<p>You code reveled some misconceptions about the MVC-pattern:</p>\n\n<h2>Model</h2>\n\n<p>The Model is merely a <em>data store</em>. It provides <em>Data Transfer Objects</em> (DTOs), <em>ValueObjects</em>(VOS), <em>Beans</em> or <em>Entities</em> or alike.\nAny logic in the model is about persistence, integrity and infrastructure to inform the view about changes. \nIn particular the model does <strong>not</strong> contain <em>business logic</em>.</p>\n\n<p>Your model contains business logic (the game end check).</p>\n\n<h2>Controller</h2>\n\n<p>the controller manipulates the model. \nIt applies the <em>business logic</em> to the data stored in the model.\nIn particular it has no knowledge about the <em>view</em>.</p>\n\n<p>In your code the controller interacts with the user by printing lines at the console itself.</p>\n\n<h2>View</h2>\n\n<p>The view displays the models current state and passes the user input to the appropriate method in the controller. \nIt <em>may</em> update data in the model directly, but it should not. \nThe view should delegate changes to the models state to the controller.</p>\n\n<p>In fact <em>User Interface</em> would be a better name instead of <em>View</em> but then we wouldn't have a 3 letter acronym to reflect the 3 layer architecture... </p>\n\n<p>Your <em>view</em> does not handle user input, it only displays the game field.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:28:22.747",
"Id": "216156",
"ParentId": "216134",
"Score": "2"
}
},
{
"body": "<p>I agree with @Timothy Truckle in that you have some issues with the MVC-pattern. I disagree with where they've drawn the line between the model, view and controller.</p>\n\n<p>As they've stated, the model should be a data store, containing the state of the application. In addition, the model may have logic about persistence, integrity and infrastructure; I don't disagree with that. But the model should also have logic which can be used to both update the model and query the state of the model; checking to see if the game is over (a win by either player or a tie game) is a state-query.</p>\n\n<p>Amplifying this a bit. If you were to update your program so that it runs as a GUI, with buttons to click to make moves, the model should not need to be changed. The code to check for a win or a tie doesn't need to change; it would be the same whether the game is uses console input/output or has buttons and windows. It is merely a query of the game state, and certainly is allowed in the model.</p>\n\n<p>Reporting the result of that query to user is the violation. </p>\n\n<hr>\n\n<p>You are mixing symbolic identifiers and integer values. Consider:</p>\n\n<pre><code>static final int X = 1;\nstatic final int O = -1;\n</code></pre>\n\n<p>Using an <code>enum</code> would be better, but using names for the values is an excellent step in the right direction. But consider:</p>\n\n<pre><code> if( board[row][col] == 0 )\n board[row][col] = X;\n</code></pre>\n\n<p>If the board contains a zero, you store the symbol <code>X</code>. Wait. What is that zero? What does it mean? Perhaps you want to create and use another symbol:</p>\n\n<pre><code>static final int EMPTY = 0;\n</code></pre>\n\n<hr>\n\n<p>You are repeating yourself.</p>\n\n<p>In <code>main()</code>, you have a <code>while( model.hasWon(board) == false)</code>, and midway through the function, you have the same test <code>if( model.hasWon(board) == false) break;</code>. Before and after the <code>if</code> statement, you have almost exactly the same lines of code. You could move those lines of code into their own function, with parameters to identify which player's turn is being played. Eg)</p>\n\n<pre><code> while( model.hasWon(board) == false) {\n\n getAndPlayMove(board, \"X\", X);\n\n if (model.hasWon(board) == false)\n break;\n\n getAndPlayMove(board, \"O\", O);\n }\n</code></pre>\n\n<p>Again, that <code>while</code> loop is doing the same operation twice, with the loop condition tested in the middle. It would be better to do twice the number of iterations through the loop, and swap which player is playing each time through. For example:</p>\n\n<pre><code> int player = X; // Starting player\n\n while (model.hasWon(board) == false) {\n\n String player_name = (player == X) ? \"X\" : \"O\";\n\n getAndPlayMove(board, player_name, player);\n\n player = (player == X) ? O : X; // Switch players\n }\n</code></pre>\n\n<p>With a two player game, repeating the same code for each player may not seem like much of a burden, but for a multi-player game, it quickly becomes clear the correct thing to do is write the code once and change the player each pass through the loop.</p>\n\n<hr>\n\n<p><code>hasWon()</code> is a very misleading method name. In a tie-game, nobody has won, but the function still returns <code>true</code>.</p>\n\n<p><code>isOver()</code> would be a better name; you play the game while it is not over.</p>\n\n<hr>\n\n<p>Hard coded numbers are BAD™. Using a hard-coded number once is almost acceptable, but the second time you use that number in the same context is an error waiting to happen. What if you want to change the number? Go from a 5x5 game grid to a 6x6 game grid. Find and replace every instance of a \"5\" with a \"6\"? If I had a nickel for every time find-and-replace replaced the wrong thing ...</p>\n\n<pre><code>public static final int SIZE = 5;\nint [][] board = new int[SIZE][SIZE];\n</code></pre>\n\n<p>Good. Now we won't end up with a 5x6 grid. Change all of the <code>if (sum == 5)</code> to <code>if (sum == SIZE)</code> and all of the <code>if (sum == -5)</code> to <code>if (sum == -SIZE)</code> and we're golden, right? No more 5's!</p>\n\n<p>Except when we play, we can't enter the cell <code>5,5</code>, because you have <code>if(col<=4 && col>=0)</code>. Oh! That wasn't a 4, that was a <code>5-1</code> optimized by hand to read <code>4</code>. I guess we want...</p>\n\n<pre><code>if (col <= SIZE-1 && col >= 0)\n</code></pre>\n\n<p>But <code>col <= SIZE-1</code> is ugly, and takes 3 too many characters. Use the <code><</code> operator instead:</p>\n\n<pre><code>if (col < SIZE && col >= 0)\n</code></pre>\n\n<p><strong>BUG</strong>: You don't validate the <code>row</code> input! If the user enters <code>105</code> and <code>3</code>, the program accepts it as valid input, but will crash with an <code>IndexOutOfRangeException</code>.</p>\n\n<hr>\n\n<p>The game now works for a 6x6 grid with a row or column of 6 in-a-row. The diagonals fail, though.</p>\n\n<pre><code> if( (matrix[0][0] + matrix[1][1] + matrix[2][2]+matrix[3][3]+matrix[4][4]) == SIZE ){\n System.out.println(\"X wins.\");\n retVal = true;\n } else if ( (matrix[0][4] + matrix[1][3] + matrix[2][2]+matrix[3][1]+matrix[4][0]) == -SIZE ) {\n System.out.println(\"O wins.\");\n retVal = true;\n }\n if( (matrix[0][4] + matrix[1][3] + matrix[2][2]+matrix[3][1]+matrix[4][0]) == SIZE){\n System.out.println(\"X wins.\");\n retVal = true;\n } else if ( (matrix[0][4] + matrix[1][3] + matrix[2][2]+matrix[3][1]+matrix[4][0]) == -SIZE ) {\n System.out.println(\"O wins.\");\n retVal = true;\n }\n</code></pre>\n\n<p>Yuk! Lots of hard-coded matrix indices.</p>\n\n<p>You <s>want</s> need to use a loop here:</p>\n\n<pre><code>int diag1 = 0, diag2 = 0;\nfor (int i=0; i<SIZE; i++) {\n diag1 += matrix[i][i];\n diag2 += matrix[i][SIZE-1-i];\n}\n\nif (diag1 == SIZE || diag2 == SIZE) {\n System.out.println(\"X wins.\");\n retval = true;\n} else if (diag1 == -SIZE || diag2 == -SIZE) {\n System.out.println(\"O wins.\");\n retval = true;\n}\n</code></pre>\n\n<p>Shorter code, and it works with any SIZE game grid. Of course, you still want to refactor things to remove the output statements from the model.</p>\n\n<p>Bug: It is possible to print multiple outcomes from the game. Imagine playing 24 moves with neither X nor O completing a row column or diagonal ...</p>\n\n<pre><code>X O X O X\nO X X X O\nO O . O O\nO X X X O\nX O X O X\n</code></pre>\n\n<p>Now play X's last and only move -- the centre cell. With your original code, you'd get this output:</p>\n\n<pre><code>X wins.\nX wins.\nX wins.\nEnds in a tie.\n</code></pre>\n\n<hr>\n\n<p>Your model doesn't store anything. It has no data, and exactly 1 <code>static</code> method. To use your model, you call <code>model.hasWon(board)</code> ... so you are passing the state of the game into the model! If your model actually contained the state, you could simply call <code>model.hasWon()</code>.</p>\n\n<p>A better model might be:</p>\n\n<pre><code>public enum Player { X, O };\n\npublic class Model {\n public final int size;\n private final Player[][] board;\n private int moves_left;\n\n public Model(int size) {\n this.size = size;\n board = new Player[size][size];\n moves_left = size * size;\n }\n\n public boolean valid_cell(int row, int col) {\n return row >= 0 && row < size && col >= 0 && col < size;\n }\n\n public boolean valid_move(int row, int col) {\n if (!valid_cell(row, col) || moves_left == 0)\n return false;\n\n return board[row][col] == null;\n }\n\n public Player get_cell(int row, int col) {\n return board[row][col];\n }\n\n public boolean make_move(int row, int col, Player player) {\n if (!valid_move(row, col))\n throw new IllegalStateException(\"You didn't validate the player's move!\");\n\n board[row][col] = player;\n spaces_left--;\n\n boolean won = ...\n /* Add code to see if player made a winning move */\n\n if (won)\n moves_left = 0;\n\n return won;\n }\n\n public int moves_left() {\n return moves_left;\n }\n}\n</code></pre>\n\n<p>Both <code>board</code> and <code>moves_left</code> are private, to prevent tampering with the game state. The <code>get_cell()</code> method allows a read-only access to the board, so the board can be displayed. <code>moves_left</code> is used to keep track of the available spaces, without needing to search over the entire board for an empty spot.</p>\n\n<p><code>make_move()</code> is used to change the board's state. After ensuring the move is valid, it fills in the player's move, and decrements the <code>moves_left</code> counter. Then, it checks if the move has caused the player to win, and returns that to the caller.</p>\n\n<p>By checking if the <strong>current player</strong> has won, you eliminate the need to check dual conditions (eg, <code>if (sum == 5)</code> or <code>if (sum == -5)</code>). You can additionally optimize the check for win by only checking the row and column the player moved in, instead of every row and every column in the board. (This optimization would be important if you try to build an AI which has to do an exhaustive search of possible moves.)</p>\n\n<p>To use this model, you might write code along the lines of:</p>\n\n<pre><code>Model model = new Model(5);\nPlayer player = Player.X;\n\nwhile (model.moves_left() > 0) {\n\n // Get row, col from player, ensuring model.valid_move(row, col)\n // returns `true` before continuing.\n\n if (model.make_move(row, col, player)) {\n // Record or report the win\n }\n\n // Set player to the other player\n}\n\nSystem.out.println(\"Game over\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:32:28.130",
"Id": "418384",
"Score": "0",
"body": "Thanks for this great detailed review. I disagree with your argument about the model having the *game end detection* because its not changing when changing the view. The controller shouldn't change either so I still believe the *game end detection* belongs to the latter. But I guess we both can live with this disagreement... ;o)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T22:21:06.650",
"Id": "216196",
"ParentId": "216134",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T02:48:11.593",
"Id": "216134",
"Score": "2",
"Tags": [
"java",
"mvc",
"tic-tac-toe"
],
"Title": "MVC Java console tic-tac-toe"
} | 216134 |
<p>I built a web scraper to pull a list of jobs on Facebook and other websites but want to break up the code into functions that I can reuse for other websites. This structure is working but I think it can be more efficient with functions. I'm getting stuck on how to structure the functions. It's only pulling two pages for testing.</p>
<pre><code>from time import time
from requests import get
from time import sleep
from random import randint
from IPython.core.display import clear_output
from warnings import warn
from bs4 import BeautifulSoup
import csv
# Range of only 2 pages
pages = [str(i) for i in range(1, 3)]
cities = ["Menlo%20Park%2C%20CA",
"Fremont%2C%20CA",
"Los%20Angeles%2C%20CA",
"Mountain%20View%2C%20CA",
"Northridge%2CCA",
"Redmond%2C%20WA",
"San%20Francisco%2C%20CA",
"Santa%20Clara%2C%20CA",
"Seattle%2C%20WA",
"Woodland%20Hills%2C%20CA"]
# Preparing the monitoring of the loop
start_time = time()
requests = 0
with open('facebook_job_list.csv', 'w', newline='') as f:
header = csv.writer(f)
header.writerow(["Website", "Title", "Location", "Job URL"])
for page in pages:
for c in cities:
# Requests the html page
response = get("https://www.facebook.com/careers/jobs/?page=" + page +
"&results_per_page=100&locations[0]=" + c)
# Pauses the loop between 8 and 15 seconds
sleep(randint(8, 15))
# Monitor the frequency of requests
requests += 1
elapsed_time = time() - start_time
print("Request:{}; Frequency: {} request/s".format(requests, requests/elapsed_time))
clear_output(wait=True)
# Throw a warning for non-200 status codes
if response.status_code != 200:
warn("Request: {}; Status code: {}".format(requests, response.status_code))
# Break the loop if number of requests is greater than expected
if requests > 2:
warn("Number of requests was greater than expected.")
break
# Parse the content of the request with BeautifulSoup
page_soup = BeautifulSoup(response.text, 'html.parser')
job_containers = page_soup.find_all("a", "_69jm")
# Select all 100 jobs containers from a single page
for container in job_containers:
site = page_soup.find("title").text
title = container.find("div", "_69jo").text
location = container.find("div", "_1n-z _6hy- _21-h").text
link = container.get("href")
job_link = "https://www.facebook.com" + link
with open('facebook_job_list.csv', 'a', newline='') as f:
rows = csv.writer(f)
rows.writerow([site, title, location, job_link])
</code></pre>
| [] | [
{
"body": "<p>Some quick suggestions: </p>\n\n<p>The <code>requests</code> module can urlencode strings for you if you use the <code>params</code> keyword:</p>\n\n<pre><code>import requests\n\ncities = [\"Menlo Park, CA\"]\npages = range(1, 3)\nurl = \"https://www.facebook.com/careers/jobs/\"\n\nfor city in cities:\n for page in pages:\n params = {\"page\": page, \"results_per_page\": 100, \"locations[0]\": city}\n response = requests.get(url, params=params)\n</code></pre>\n\n<p>Organize your code using functions. This allows you to give them a readable name (and even add docstrings).</p>\n\n<pre><code>def get_job_infos(response):\n \"\"\"Parse the content of the request to get all job postings\"\"\"\n page_soup = BeautifulSoup(response.text, 'lxml')\n job_containers = page_soup.find_all(\"a\", \"_69jm\")\n\n # Select all 100 jobs containers from a single page\n for container in job_containers:\n site = page_soup.find(\"title\").text\n title = container.find(\"div\", \"_69jo\").text\n location = container.find(\"div\", \"_1n-z _6hy- _21-h\").text\n job_link = \"https://www.facebook.com\" + container.get(\"href\")\n yield site, title, location, job_link\n</code></pre>\n\n<p>This is a generator over which you can iterate. Using the <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser\" rel=\"nofollow noreferrer\"><code>lxml</code> parser</a> is usually faster.</p>\n\n<p>Note that <code>csv</code> can write multiple rows at once using <a href=\"https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows\" rel=\"nofollow noreferrer\"><code>writer.writerows</code></a>, which takes any iterable of rows:</p>\n\n<pre><code>with open('facebook_job_list.csv', 'a', newline='') as f:\n writer = csv.writer(f)\n writer.writerows(get_job_infos(response))\n</code></pre>\n\n<p>This way you only have to open the file once per page, instead of a hundred times. Even better would be to make the whole thing a generator, so you can write all rows while opening the file only once:</p>\n\n<pre><code>def get_all_jobs(url, cities, pages):\n for city in cities:\n for page in pages:\n params = {\"page\": page, \"results_per_page\": 100, \"locations[0]\": city}\n response = requests.get(url, params=params)\n # check status code\n\n yield from get_job_infos(response)\n\n # rate throttling, etc here\n ...\n\nif __name__ == \"__main__\":\n cities = [\"Menlo Park, CA\", ...]\n pages = range(1, 3)\n url = \"https://www.facebook.com/careers/jobs/\"\n\n with open('facebook_job_list.csv', \"w\") as f:\n writer = csv.writer(f)\n writer.writerow([\"Website\", \"Title\", \"Location\", \"Job URL\"])\n writer.writerows(get_all_jobs(url, pages, cities))\n</code></pre>\n\n<p>This way the <code>get_all_jobs</code> generator will <code>yield</code> jobs as it is being iterated over, getting the next page when needed. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T08:35:31.987",
"Id": "216144",
"ParentId": "216135",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216144",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T02:48:13.453",
"Id": "216135",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"beautifulsoup",
"facebook"
],
"Title": "Web scraping job postings from Facebook"
} | 216135 |
<p><strong>Introduction:</strong></p>
<p>I am working on a javascript plugin <a href="https://github.com/avcs06/AutoSuggest" rel="nofollow noreferrer">AutoSuggest</a>, My aim is to create an IDE like autocomplete experience in web applications using JavaScript.</p>
<p>One of the features I have implemented is focusing a particular portion of inserted snippet after insertion. This is how I am asking input for focus.</p>
<blockquote>
<p><strong>focusText</strong>: <code>[StartIndex, EndIndex]</code></p>
<p><code>StartIndex</code> and <code>EndIndex</code> of the content that should be in focus
after inserting the text. As of now these indexes should be calculated
as (0 - numberOfCharactersFromEnd)</p>
<p><strong>focusHtml</strong>: <code>[StartIndex, EndIndex]</code></p>
<p><code>StartIndex</code> and <code>EndIndex</code> of the content that should be in focus after inserting the HTML. As of now these indexes should be calculated as (0 - numberOfCharactersFromEnd). This should not include the characters from HTML tags</p>
</blockquote>
<p><strong>Example:</strong></p>
<pre><code>{
value: 'script',
insertText: '<script type="text/javascript" src="path/to/jsfile"><\/script>',
focusText: [-25, -11],
insertHtml: `&lt;<span style="color: red">script</span>&nbsp;<span style="color:green">type</span>=<span style="color:darksalmon">"text/javascript"</span>&nbsp;<span style="color:green">src</span>=<span style="color:darksalmon">"path/to/jsfile"</span>&gt;&lt;\/<span style="color: red">script</span>&gt;`,
focusHtml: [-25, -11],
}
// Should focus `path/to/jsfile` after inserting the snippet
</code></pre>
<p><code>insertText</code> and <code>focusText</code> are for inserting snippet as text.</p>
<p><code>insertHtml</code> and <code>focusHtml</code> are for inserting snippet as html elements.</p>
<p>And I am evaluating the focus value as follows:</p>
<pre><code>/* For inserting as text:
* textNode is the text node in which the snippet has been inserted
* selection is the range object of current selection.
* cursorPosition is after the last character in inserted snippet
* */
selection.setStart(textNode, cursorPosition + focusText[0]);
selection.setEnd(textNode, cursorPosition + focusText[1]);
</code></pre>
<pre><code>/* For inserting as HTML:
* textNode is the text node after which the new html element(s) will be inserted
* selection is the range object of current selection.
* insertHtmlAfter returns an Array of newly inserted nodes
* */
const nodes = insertHtmlAfter(textNode, suggestion.insertHtml);
const focus = nodes.length ? suggestion.focusHtml : [0, 0];
function setSelection(focus, nodes, method) {
let lastNode, lastFocus = focus;
if (lastFocus !== 0) {
do {
lastNode = nodes.pop();
lastFocus += lastNode.textContent.length;
} while(nodes.length && lastFocus < 0);
if (!lastNode) {
throw new TypeError(`AutoSuggest: Invalid value provided for Suggestion.focusHtml`);
};
}
if (lastFocus === 0) {
selection[method + 'After'](nodes[nodes.length - 1] || textNode);
} else {
if (lastNode.nodeType === lastNode.TEXT_NODE) {
selection[method](lastNode, lastFocus);
} else {
setSelection(
lastFocus - lastNode.textContent.length,
Array.from(lastNode.childNodes),
method
);
}
}
};
setSelection(focus[1], [...nodes], 'setEnd');
setSelection(focus[0], [...nodes], 'setStart');
</code></pre>
<p><strong>Problem:</strong></p>
<ol>
<li><p>Asking for focus values as negative numbers might be confusing for the users, but it simplifies the logic for <code>focusText</code>, so is there any better way that is both user friendly and requires simpler logic.</p></li>
<li><p>I think the logic for setting the focus for inserting as HTML is a bit over-complicated, is there any better way to achieve this?</p></li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T19:45:54.693",
"Id": "419381",
"Score": "0",
"body": "You stated: \"_it simplifies the logic for `focusText`_\" that makes it sound like `focusText` is a function/method but after [searching the repository](https://github.com/avcs06/AutoSuggest/search?q=focustext&unscoped_q=focustext) that doesn't appear to be the case... what logic is simplified by having negative numbers? Please [edit] your post to include any logic you want reviewed..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T05:37:42.673",
"Id": "419517",
"Score": "0",
"body": "I have included the logic for focusText in the question, the variables are a little different in original repo, you can find it in `setValue` method, line number 214"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T05:43:03.870",
"Id": "419519",
"Score": "0",
"body": "I have posted both the snippets I want reviewed and Also if you can suggest better names for those params, please do. I am also little confused about how to name them :D"
}
] | [
{
"body": "<p>I do feel that negative numbers seems a bit backwards compared to most other libraries I have used. I am not sure what all would be involved with reworking this code to utilize positive numbers but it seems it may be hefty. Though maybe you could accept positive numbers and convert them to negatives by subtracting them from the length of the string. </p>\n\n<hr>\n\n<p>I see one spot that may have a possible performance improvement- in the recursive call to <code>setSelection()</code>: </p>\n\n<blockquote>\n<pre><code>setSelection(\n lastFocus - lastNode.textContent.length,\n Array.from(lastNode.childNodes),\n method\n);\n</code></pre>\n</blockquote>\n\n<p>here <code>Array.from()</code> is called to copy the array of nodes from the <code>childNodes</code> collection from <code>lastNode</code>. The spread operator can also be used to put those child nodes into an array (from the node collection), allowing you to eliminate that extra function call.</p>\n\n<pre><code>setSelection(\n lastFocus - lastNode.textContent.length,\n [...lastNode.childNodes],\n method\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T05:54:02.680",
"Id": "419824",
"Score": "0",
"body": "Hi sam, the variable `nodes` is an actual array and it is reused, I am using spread operator to clone the array, so that original array stays intact. `lastNode.childNodes` is not an array, so I have to convert it into an array but I don't need to clone it as it is not reused."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T06:00:19.907",
"Id": "419826",
"Score": "0",
"body": "Why negative numbers? Conceptually whats happening is the cursor will be at the end of the line after inserting new text and I have to count back to place the cursor at the required point, so negative numbers make the logic simpler as all I have to do is add the number provided by user to current position and I will get the required position. That is simpler logic wise but I am not sure about user experience"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T06:25:17.410",
"Id": "419828",
"Score": "0",
"body": "I understand why you wanted to use negative numbers, and why you want to copy. Please see revised answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T05:40:15.720",
"Id": "217052",
"ParentId": "216138",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T06:09:58.680",
"Id": "216138",
"Score": "4",
"Tags": [
"javascript",
"ecmascript-6",
"dom",
"plugin",
"text-editor"
],
"Title": "AutoSuggest: Better way to implement focus after inserting a snippet"
} | 216138 |
<p>So I just completed this project for my java programming class and was wondering if there was any way I could streamline it to really impress my professor. Here were the instructions, followed by my code.</p>
<blockquote>
<p>The University of Miami's "Band of the Hour" needs a program to organize where the musicians will stand when they play at away games. Each away stadium is different, so when they arrive the conductor gets the following information from the local organizer:</p>
<p>The number of rows they have to stand on. The maximum number of rows is 10. The rows are labelled with capital letters, 'A', 'B', 'C', etc.</p>
<p>For each row, the number of positions in the row. The maximum number of positions is 8. The positions are numbered with integers, 1, 2, 3, etc.</p>
<p>The conductor then starts assigning people to positions, but is constrained by weight limits: Musicians, fully clothed and holding their instruments, weigh from 45kg to 200kg, and the total weight of a row may not exceed 100kg per position (e.g., a row with 5 positions may not have more than 500kg of musicians on it). The conductor wants a program that allows musicians to be added and removed from positions, while ensuring the constraints are all met. At any stage the conductor wants to be able to see the current assignment - the weight in each position (0kg for vacant positions) and the total & average weight for each row.</p>
<p>The program must be menu driven, with options to:</p>
<ul>
<li>Add a musician (by weight) to a vacant position.</li>
<li>Remove a musician from an occupied position.</li>
<li>Print the current assignment.</li>
<li>Exit (so the musicians can start playing)</li>
</ul>
<p>The program must be reasonably idiot proof:</p>
<ul>
<li>Menu options must be accepted in upper and lower case.</li>
<li>Row letters must be accepted in upper and lower case.</li>
<li>All input must be checked to be in range, and if not the user must be asked to input again.</li>
<li>You may assume that numeric input will be syntactically correct.</li>
</ul>
</blockquote>
<pre><code>import java.util.Scanner;
public class Main {
private static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
//values
int positions;
int rowNumber;
char userInput;
char rowLetter;
double musicianWeight = 0;
double tot = 0;
int j;
int i;
System.out.println();
System.out.println("Welcome to the Band of the Hour");
System.out.println("-------------------------------");
//create array
System.out.print("Please enter number of rows\t\t: ");
rowNumber = keyboard.nextInt();
double[][] positionsArray = new double[rowNumber][5];
int[] rowPositions = new int[rowNumber];
while (rowNumber < 1 || rowNumber > 10) {
System.out.print("ERROR: Out of range, try again : ");
rowNumber = keyboard.nextInt();
}
for (int row = 0; row < rowNumber; row++) {
System.out.print("Please enter the number of positions in row " + (char) (row + (int) 'A') + " : ");
positions = keyboard.nextInt();
rowPositions[row] = positions;
while (positions < 0 || positions > 8) {
System.out.print("ERROR: Out of range, try again : ");
positions = keyboard.nextInt();
}
positionsArray = new double[rowNumber][positions];
}
do {
System.out.println();
System.out.print(" (A)dd, (R)emove, (P)rint e(X)it : ");
userInput = keyboard.next().charAt(0);
userInput = Character.toUpperCase(userInput);
//add musician
switch (userInput) {
case 'A': {
System.out.print("Please enter row letter : ");
while (true) {
rowLetter = keyboard.next().charAt(0);
rowLetter = Character.toUpperCase(rowLetter);
if (rowLetter - 'A' < rowNumber)
break;
System.out.print("ERROR: Out of range, try again : ");
}
System.out.print("Please enter position number (1 to " + rowPositions[rowLetter - 'A'] + " ) : ");
positions = keyboard.nextInt();
while (true) {
if (positions >= 0 && positions <= rowPositions[rowLetter - 'A'])
break;
System.out.print("ERROR: Out of range, try again : ");
}
if (positionsArray[rowLetter - 'A'][positions - 1] != 0) {
System.out.println("ERROR: There is already a musician there.");
break;
}
else {
System.out.print("Please enter weight (45.0 to 200.0) : ");
while (true) {
musicianWeight = keyboard.nextDouble();
if (musicianWeight >= 45.0 && musicianWeight <= 200.0)
break;
System.out.print("Error: Out of range, try again : ");
}
}
tot = tot + musicianWeight;
if (tot > 500) {
System.out.println("ERROR: That would exceed the average weight limit.");
}
else {
positionsArray[rowLetter - 'A'][positions - 1] = musicianWeight;
System.out.println("********** Musician added");
}
}
break;
//remove musician
case 'R' : {
System.out.print("Please enter row letter : ");
while (true) {
rowLetter = keyboard.next().charAt(0);
rowLetter = Character.toUpperCase(rowLetter);
if (rowLetter - 'A' < rowNumber)
break;
System.out.print("ERROR: Out of range, try again : ");
}
System.out.print("Please enter position number (1 to " + rowPositions[rowLetter - 'A'] + " ) : ");
while (true) {
positions = keyboard.nextInt();
if (positions >= 0 && positions <= rowPositions[rowLetter - 'A'])
break;
System.out.print("ERROR: Out of range, try again : ");
}
if (positionsArray[rowLetter-'A'][positions-1] == 0)
System.out.println("ERROR: That spot is vacant.");
else {
positionsArray[rowLetter-'A'][positions-1] = 0;
System.out.print("****** Musician removed.");
System.out.println();
}
}
//print layout
break;
case 'P' : {
System.out.println();
for (i = 0; i < rowNumber; i++) {
System.out.print((char) (i + 65) + ": ");
tot = 0;
for (j = 0; j < rowPositions[i]; j++) {
System.out.printf("%3.1f\t", positionsArray[i][j]);
tot += positionsArray[i][j];
}
System.out.printf("\t\t[%6.1f,%6.1f]\n", tot, (tot / rowPositions[i]));
}
break;
}
//end program
case 'X' : {
System.exit(0);
}
default :
System.out.print("ERROR: Invalid option, try again :");
break;
}
} while (userInput != 'X');
}
}
</code></pre>
<p>How can I streamline this code?</p>
| [] | [
{
"body": "<p>Welcome to code review and thanks for sharing your code.</p>\n\n<p>Here are some points to consider:</p>\n\n<ul>\n<li><p>declare variables as close to their usage as possible.</p>\n\n<p>You declared (almost) all your variable at the beginning of your <code>main</code> method which makes it hard to improve your code later on. \nThis applies especially to <code>i</code> and <code>j</code> which are used in for loops and should be declared inside them.</p></li>\n<li><p>avoid short variable names. </p>\n\n<p>Will you remember what <code>tot</code> is in 6 month?</p></li>\n<li><p>do not use the <code>else</code> branch of an <code>if</code> statement as an error handler. Instead of </p>\n\n<blockquote>\n<pre><code> while (true) {\n rowLetter = keyboard.next().charAt(0);\n rowLetter = Character.toUpperCase(rowLetter);\n if (rowLetter - 'A' < rowNumber)\n break;\n System.out.print(\"ERROR: Out of range, try again : \");\n }\n</code></pre>\n</blockquote>\n\n<p>it should be:</p>\n\n<pre><code> boolean isInputValid = false;\n do {\n rowLetter = keyboard.next().charAt(0);\n rowLetter = Character.toUpperCase(rowLetter);\n isInputValid = (rowLetter - 'A' < rowNumber)\n if (!isInputValid)\n System.out.print(\"ERROR: Out of range, try again : \");\n } while (!isInputValid);\n</code></pre></li>\n<li><p>avoid <em>magic numbers</em></p>\n\n<p>your code has some literals that need explanation: what is <code>5</code> in <code>new double[rowNumber][5];</code>? \nThis should be a <em>constant</em> having a meaningful name:</p>\n\n<pre><code> private static final int MAX_POSITION = 5;\n // ...\n public static void main(String[] args){\n // ...\n double[][] positionsArray = new double[rowNumber][MAX_POSITION];\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:04:25.130",
"Id": "216153",
"ParentId": "216145",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T08:47:39.713",
"Id": "216145",
"Score": "3",
"Tags": [
"java"
],
"Title": "Organize musicians into rows, with weight and population restrictions"
} | 216145 |
<p>I have created a simple C# console app to display an Address Book using Dictionary. I would like to present it in a interview but I am not sure if the code is "interview" worthy. Given below is the Main() method that calls the methods as required. </p>
<pre><code>public static void Main(string[] args) {
while (true)
{
Console.WriteLine(
"+++++++++++************+++++++++++++++****************" +
"\n\n This is an application to view list of contacts \n" +
"Choose from the options below to go ahead: \n"+
"1. Create a new contact \n" +
"2. View list of contacts \n" +
"3. Update a contact \n" +
"4. Delete a contact \n" +
"5. Quit the current application \n");
string UserInput = Console.ReadLine();
int ChosenValue;
bool ChosenValueValid = int.TryParse(UserInput, out ChosenValue);
if (ChosenValueValid) {
Console.WriteLine("You have chosen option: {0}", UserInput);
switch (ChosenValue)
{
case 1:
ConsoleAddressBook.CreateContact();
break;
case 2:
ConsoleAddressBook.GetContactList();
break;
case 3:
ConsoleAddressBook.UpdateContact();
break;
case 4:
ConsoleAddressBook.DeleteContact();
break;
case 5:
Console.WriteLine("Application will be exited");
return;
default:
Console.WriteLine("Enter a valid number between 1 and 6");
break;
}
}
else
{
Console.WriteLine("Please enter a number and not a string");
}
}
}
</code></pre>
<p>Below is the code that describes the various methods that are being called from the initial screen: </p>
<pre><code>public class ConsoleAddressBook
{
class Contact
{
string Name { get; set; }
int PhoneNumber { get; set; }
}
static Dictionary<int, string> ContactsList = new Dictionary<int, string>();
public static void GetContactList() {
if (ContactsList.Count > 0)
{
foreach (var contact in ContactsList)
Console.WriteLine("\n Name: " + contact.Value +
" Number: " + contact.Key + " \n ");
}
else
{
Console.WriteLine("\n No contacts found in the ContactList. Add a new contact to proceed further: \n");
}
}
public static void CreateContact() {
while (true) {
bool Valid= false;
Console.WriteLine("Enter the Name of the contact");
string Name = Console.ReadLine();
Valid = IsValueValid(Name, 0);
Console.WriteLine("Enter the contact PhoneNumber");
int PhoneNumber;
bool PhoneNumberValid = int.TryParse(Console.ReadLine(), out PhoneNumber);
Valid = IsValueValid("", PhoneNumber);
if (!Valid)
{
Console.WriteLine("Enter valid string for Name Or integer for PhoneNumber and try again");
return;
}
else if(ContactsList.ContainsKey(PhoneNumber))
{
Console.WriteLine("Phone number already found in the list. \n" +
"Choose option 3 to update the contact name if required");
return;
}
else
{
ContactsList.Add(PhoneNumber, Name);
Console.WriteLine("Contact added. Choose option 2 to view list of contacts");
return;
}
}
}
public static void UpdateContact() {
Console.WriteLine("Enter the phone number of the contact you wish to update");
int PhoneNumber;
bool PhoneNumberValid = int.TryParse(Console.ReadLine(), out PhoneNumber);
bool Valid = IsValueValid("", PhoneNumber);
if (!Valid)
{
Console.WriteLine("Enter a valid phone number to update");
}
else if (!ContactsList.ContainsKey(PhoneNumber))
{
Console.WriteLine("Phone number not found in the list. \n" +
"Choose option 1 to view the list of contacts");
return;
}
else
{
Console.WriteLine("Enter the new name for the contact");
string newName = Console.ReadLine();
ContactsList[PhoneNumber] = newName;
Console.WriteLine("Contact {0} updated", PhoneNumber);
}
}
public static void DeleteContact()
{
Console.WriteLine("Enter the phone number of the contact you wish to delete");
int PhoneNumber;
bool PhoneNumberValid = int.TryParse(Console.ReadLine(), out PhoneNumber);
bool Valid = IsValueValid("", PhoneNumber);
if (!Valid)
{
Console.WriteLine("Enter a valid phone number to delete");
}
else if (!ContactsList.ContainsKey(PhoneNumber))
{
Console.WriteLine("Phone number not found in the list. \n" +
"Choose option 1 to view the list of contacts");
return;
}
else
{
ContactsList.Remove(PhoneNumber);
Console.WriteLine("Contact {0} deleted", PhoneNumber);
}
}
public static bool IsValueValid(string name = "", int phoneNumber = 0)
{
if (!string.IsNullOrWhiteSpace(name))
{
return Regex.IsMatch(name, @"^[a-zA-Z]+$");
}
if (phoneNumber > 0)
{
return Regex.IsMatch(Convert.ToString(phoneNumber), @"^[0-9]+$");
}
return false;
}
}
</code></pre>
<p>I am not sure if this is too wordy or too lengthy and if I can make this more efficient. Looking forward to your inputs.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:57:55.960",
"Id": "418255",
"Score": "0",
"body": "I don't like the many static methods. I get it - you probably designed this thinking you have ONE contact list. But you could be more flexible by allowing different lists, perhaps business and personal. There could be a static method for GetDefaultContactList but it everything else works off an instance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:59:39.010",
"Id": "418256",
"Score": "0",
"body": "In addition to @RickDavin's comment: non static methods easier to test."
}
] | [
{
"body": "<p>Don't use <code>\\n</code>, use <code>Environment.NewLine</code>.</p>\n\n<hr>\n\n<p>Please follow Microsoft's guidelines/conventions, e.g. with regard to <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions\" rel=\"noreferrer\">capitalization</a>,...</p>\n\n<hr>\n\n<p>Be careful when naming things. The \"Console\" part of <code>ConsoleAddressBook</code> is IMHO pointless. <code>ContactsList</code> isn't a <code>List</code> but a <code>Dictionary</code>, and thus the name doesn't correspond with the type -- why not simply name it <code>Contacts</code> or <code>ContactsByPhoneNumber</code>?</p>\n\n<hr>\n\n<p>A phone number isn't an <code>int</code>. See also <a href=\"https://github.com/googlei18n/libphonenumber/blob/master/FALSEHOODS.md\" rel=\"noreferrer\">this list of Falsehoods Programmers Believe About Phone Numbers</a>.</p>\n\n<hr>\n\n<p>Separate your UI from your back-end code. <code>ConsoleAddressBook</code> mixes the two and thus becomes hard to maintain. What would have impressed me is a somewhat mature application where there is such a separation, whereas I'd regard your code as a typical \"whipped this up in an hour\" stopgap solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T13:19:56.947",
"Id": "418259",
"Score": "0",
"body": "I didn't notice that the variables do not have a good names, nice catch. To add to your comment about a new line: [documentation](https://docs.microsoft.com/en-us/dotnet/api/system.environment.newline?view=netframework-4.7.2) states that it is `A string containing \"\\r\\n\" for non-Unix platforms, or a string containing \"\\n\" for Unix platforms.` So the reason for this suggestion is portability."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T13:07:14.467",
"Id": "216162",
"ParentId": "216149",
"Score": "5"
}
},
{
"body": "<p>Note: below is my opinion and should not be taken as a source of truth.</p>\n\n<ol>\n<li><p><code>Main</code> should be clear of any logic except starting the program or parsing the arguments (<code>args</code> not user input). For me this comes from <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">SRP</a>. </p></li>\n<li><p>Try to abstract reading/writing to some injectable read and write classes. This gives you both possibility of further extension (away from console) and testability. </p></li>\n<li><p>As mentioned in comments, drop static methods when they are not absolutely needed advantage of doing that is the fact that your code becomes more testable (without <a href=\"https://docs.microsoft.com/en-us/visualstudio/test/isolating-code-under-test-with-microsoft-fakes?view=vs-2017\" rel=\"nofollow noreferrer\">moles</a>).</p></li>\n<li><p>'Menu' from which user selects the data should be generated dynamically for possible extensions or getting the options from config/db.</p></li>\n<li><p>Phone number should be a string. It's validation should be extracted to some helper class/function because you are repeating yourself. For validation regex see <a href=\"https://stackoverflow.com/a/18091377/3809977\">this link</a> </p></li>\n<li><p>There are many duplicates in the code, maybe you could try to abstract some parts to methods. </p></li>\n<li><p><code>IsValueValid</code> method is not nice, it does not follow SRP. Try to split it into two.</p></li>\n</ol>\n\n<p>Bonus - things that may not be required but would show an effort:</p>\n\n<ol>\n<li>Dictionary storage (some kind of database abstraction would be nice)</li>\n<li>Logging - I haven't seen any production app without logging</li>\n<li>Tests - it's always good to show some test evidence.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T13:16:59.097",
"Id": "216167",
"ParentId": "216149",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216162",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T11:27:04.513",
"Id": "216149",
"Score": "1",
"Tags": [
"c#",
"interview-questions",
"console"
],
"Title": "Simple Console Address Book in C# using Dictionary"
} | 216149 |
<p>How do I find the number of unique digits in a given number. </p>
<p>e.g<br>
if 'input1' is 252 it must return 1, since 5 is the non-repeating digit;<br>
if 'input1' is 25000 it must return 2, since digits 2 and 5 are the only non-repeating ones.</p>
<p>Is there a better way to solve this problem?</p>
<pre><code>// COUNT UNIQUE DIGITS
int nonRepeatDigitsCount(int input1){
int i=0,j,k;
int n=input1;
int count=0,check,c2=0;
// FINDING NUMBER OF DIGITS ON THE GIVEN NUMBER
while(n>0){
n=n/10;
c2++;
}
//CREATING ARRAY OF THE 'c2' SIZE
int arr[c2];
n=input1;
//STORING INDIVIDUAL DIGITS IN THE ARRAY
while(n>0)
{
arr[i]=n%10;
n=n/10;
i++;
}
// CONDITION TO FIND NON REPEATING DIGITS
for(j=0;j<c2;j++)
{
check=0;
for(k=0;k<c2;k++)
{
if(j!=k)
{
if(arr[j]==arr[k])
{
check++;
}
}
}
if(check==0)
{
count++;
}
}
return count;
}
</code></pre>
| [] | [
{
"body": "<p>This is needlessly complicated and inefficient. Rather than making an array of all digits in the array, you should make an array of counted occurrences. Since a digit can have a value 0 to 9, this array size will be 10. For each occurrence, increase the value of the index in the array corresponding to the digit by 1.</p>\n\n<p>This also means that you can count non-repeating characters on the fly while iterating through the number. When the number of occurrences is exactly 1, it should be counted. If more than that, it shouldn't.</p>\n\n<p>This makes the code behave the same no matter the number of digits used as input.</p>\n\n<p>Example:</p>\n\n<pre><code>#include <stdio.h>\n\nint non_repeating (int val)\n{\n if(val == 0) // special case, value 0 gives 1 digit\n {\n return 1;\n }\n\n int digit_count[10]={0};\n int non_rep=0;\n\n for(; val!=0; val/=10)\n {\n int i = val%10;\n digit_count[i]++;\n\n if(digit_count[i]==1)\n {\n non_rep++;\n }\n else if(digit_count[i]==2)\n {\n non_rep--;\n }\n }\n\n return non_rep;\n}\n\nint main (void)\n{\n printf(\"%d %d\\n\", 252, non_repeating(252));\n printf(\"%d %d\\n\", 25000, non_repeating(25000));\n printf(\"%d %d\\n\", 1234567890, non_repeating(1234567890));\n printf(\"%d %d\\n\", 0, non_repeating(0));\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>252 1\n25000 2\n1234567890 10\n0 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:09:00.607",
"Id": "418277",
"Score": "0",
"body": "Yeah, this is far better than what I did. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T17:46:04.973",
"Id": "498484",
"Score": "1",
"body": "Special `if(val == 0)` case not needed if `for()` loop replaced with `do { } while ()` loop."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T11:54:39.997",
"Id": "216152",
"ParentId": "216150",
"Score": "5"
}
},
{
"body": "<p>Can the number be negative? If not, then prefer to use an unsigned type as the parameter; if it can, then C99 specifies that the result of division is rounded toward zero: the result of <code>%</code> may be negative.</p>\n\n<p>Apart from that, the simplest and clearest approach is to maintain an array of counts for each digit, as suggested by Lundin. Or even simply an array of booleans, since we're only interested in presence, rather than quantity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:10:16.950",
"Id": "418278",
"Score": "0",
"body": "The input lies between 1-25000 lets say."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:27:48.880",
"Id": "423007",
"Score": "0",
"body": "As number sign does not affect the number of unique digits an easy way to cover also the negative num case is to `abs()` it before performing the actual processing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:33:24.433",
"Id": "423010",
"Score": "1",
"body": "@NicolaBernini - take care with `abs()` - remember that on 2's-complement machines, `abs(INT_MIN)` is negative..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T17:42:08.510",
"Id": "498481",
"Score": "1",
"body": "On 2's-complement machines, `abs(INT_MIN)` is UB."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T06:37:35.470",
"Id": "498527",
"Score": "1",
"body": "Regarding the boolean array: I don't think you can distinguish (0, 1, other) with that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T10:34:50.570",
"Id": "498554",
"Score": "0",
"body": "Yes @Roland, not sure what I was thinking there. We do need to remember the three states."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:43:58.873",
"Id": "216158",
"ParentId": "216150",
"Score": "1"
}
},
{
"body": "<p>Here is my functional solution with improved space complexity based on bit manipulation </p>\n\n<p>Improvements </p>\n\n<ul>\n<li><p>@Lundin has already identified major issues with the author's solution, my solution provides additional improvements which are related to </p></li>\n<li><p>Space </p>\n\n<ul>\n<li><p>no need to count the actual number of times you observe a certain digit, just discriminate between 3 cases: never observed, observed once and observed more than once </p></li>\n<li><p>the <code>once</code> variable represents in its first 10 bits the digits that have been observed once </p></li>\n<li><p>the <code>more</code> variable represents in its first 10 bits the digits that have been observed more than once </p></li>\n</ul></li>\n<li><p>Style </p>\n\n<ul>\n<li>This solution is Functional with all the related advantages (more readable, more concise, ...)</li>\n</ul></li>\n</ul>\n\n<p><strong>EDIT</strong>: My initial solution was in CPP so now I'm adding the C one: it is basically the same logic, all the CPP-specific stuff is not core </p>\n\n<h2>C Solution</h2>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n\n/**\n * @brief It just counts the number of 1s in a given binary representation \n */\nunsigned int count_ones(const unsigned int n, const unsigned int partial)\n{\n if(n==0) return partial; \n return ( (n&1)==0 )?(count_ones(n/2, partial)):(count_ones(n/2, partial+1)); \n}\n\n/**\n * @brief It counts the number of unique digits in a given base-10 number \n */\nunsigned int count( const unsigned int num, const unsigned int once, const unsigned int more )\n{\n if(num==0) return (count_ones(once, 0)>0)?(count_ones(once, 0)):1; \n const unsigned int d = num%10; ///< Just to make the code a bit more readable \n\n if((once&(1<<d))==0 && (more&(1<<d))==0) return count(num/10, once|(1<<d), more); ///< New digit observed\n if((once&(1<<d))==(1<<d)) return count(num/10, once&(~(1<<d)), more|(1<<d)); ///< Reobservation of a unique digit\n else return count(num/10, once, more); ///< Reobservation of a non unique digit\n}\n\n\nint main(void) {\n // your code goes here\n printf(\"252 = %d\\n\", count(252,0,0));\n printf(\"25000 = %d\\n\", count(25000,0,0)); \n printf(\"1234567890 = %d\\n\", count(1234567890, 0, 0)); \n printf(\"0 = %d\\n\", count(0,0,0)); \n return 0;\n}\n\n</code></pre>\n\n<p>Output </p>\n\n<pre><code>252 = 1\n25000 = 2\n1234567890 = 10\n0 = 1\n\n</code></pre>\n\n<h2>CPP Solution</h2>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\nusing namespace std;\n\n/**\n * @brief It just counts the number of 1s in a given binary representation \n */\nunsigned int count_ones(const unsigned int n, const unsigned int partial=0)\n{\n if(n==0) return partial; \n return ( (n&1)==0 )?(count_ones(n/2, partial)):(count_ones(n/2, partial+1)); \n}\n\n/**\n * @brief It counts the number of unique digits in a given base-10 number \n */\nunsigned int count( const unsigned int num, const unsigned int once=0, const unsigned int more=0 )\n{\n if(num==0) return max(count_ones(once, 0), static_cast<unsigned int>(1)); \n const auto d = num%10; ///< Just to make the code a bit more readable \n\n if((once&(1<<d))==0 && (more&(1<<d))==0) return count(num/10, once|(1<<d), more); ///< New digit observed\n if((once&(1<<d))==(1<<d)) return count(num/10, once&(~(1<<d)), more|(1<<d)); ///< Reobservation of a unique digit\n else return count(num/10, once, more); ///< Reobservation of a non unique digit\n}\n\nint main() {\n // your code goes here\n cout << count(252) << endl;\n cout << count(25000) << endl; \n cout << count(1234567890) << endl; \n cout << count(0) << endl; \n return 0;\n}\n\n</code></pre>\n\n<p>Output </p>\n\n<pre><code>1\n2\n10\n1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:11:35.393",
"Id": "423002",
"Score": "1",
"body": "While this may be an interesting alternative approach in C++, it's not really a review of the code (which is in C). Commenting on what things you do differently, **why** you are doing it that way and pointing out the flaws in the original code would make this a better answer. Copy-pasting code does not always provide a good learning experience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:24:19.580",
"Id": "423005",
"Score": "0",
"body": "Hi @Edward, \nI have edited my solution adding the version in C (it is basically the same logic as all the CPP stuff is not core) and explaining the improvements \nHope it is better now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T19:41:42.863",
"Id": "423080",
"Score": "0",
"body": "Using recursion in C is not necessarily good style. Counting the number of 1-bits recursively is also slow since the CPU spends most of the time managing memory. If there's no `__builtin_popc` available, the canonical code for the popc operation comes from the book Hacker's Delight."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T06:47:29.963",
"Id": "498529",
"Score": "0",
"body": "Your code is far from being easy to read. Counting the number of non-repeating digits is a typical task for a beginner programmer, and your code is much too complicated for a beginner. All these `<<` operators, the missing spaces and the long lines of code make the code hard to read even for advanced programmers."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T13:48:14.937",
"Id": "219022",
"ParentId": "216150",
"Score": "-1"
}
},
{
"body": "<p>if input=n then the java code is,</p>\n<pre><code>int a[]=new int[10];\nint rem;\nint count=0;\n\nwhile(n>0)\n{\nrem=n%10;\na[rem]=++a[rem]\nn=n/10;\n}\n for(int i=0;i<10;i++)\n{\nif(a[i]==1)\n count++;\n}\nreturn count; // is the output\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T17:42:14.940",
"Id": "498482",
"Score": "2",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-01T17:38:40.890",
"Id": "252889",
"ParentId": "216150",
"Score": "-2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T11:34:12.113",
"Id": "216150",
"Score": "1",
"Tags": [
"c"
],
"Title": "Count unique digits in a given number"
} | 216150 |
<p>I have this function where it queries through the database and returns a random user if the requirement is met if not then try it again. It works and all but I feel like the code could be better/shorter/faster but I'm running a blank.</p>
<p>It's all done through Firestore, where the Serivces.crud.reads() is a Firestore .getDocuments() function. At the end a list of n number of users is returned. I've tested it and it works but there could be a possibility of checking for the same value twice which means the second time it will accept the user since I'm just assuming it's going to be different, since it's a random generated number.</p>
<p>I just want to remove any possibility of getting the current user in the list of users being returned. If I have to re-write my Services.crud.reads() function, I will.</p>
<pre><code>func reads(query: Query, onSuccess: @escaping (QuerySnapshot) -> Void, onFailure: @escaping (String) -> Void) {
query.getDocuments { (snapshot, error) in
if let e = error {
onFailure(#function + ": " + e.localizedDescription)
} else {
if let s = snapshot {
onSuccess(s)
}
}
}
}
</code></pre>
<hr>
<pre><code>func randomUsers(numOfUsers: Int, onSuccess: @escaping ([DocumentReference]) -> Void) {
var users: [DocumentReference] = []
for _ in 0...numOfUsers {
Services.crud.reads(
query: self.collection.whereField("quickID", isGreaterThanOrEqualTo: "\(UInt64.random(in: UInt64.min ... UInt64.max))").limit(to: 1),
onSuccess: { (snapshot) in
if snapshot.count > 0 {
let userID = snapshot.documents.first!.documentID
if cUser.userID == userID {
Services.crud.reads(query: self.collection.whereField("quickID", isLessThanOrEqualTo: "\(UInt64.random(in: UInt64.min ... UInt64.max))").limit(to: 1), onSuccess: { (snapshot) in
let userID = snapshot.documents.first!.documentID
if users.count == numOfUsers {
onSuccess(users)
} else {
users.append(self.collection.document(userID))
print("added")
return
}
}) { (e) in
print(e)
}
} else {
if users.count == numOfUsers {
onSuccess(users)
} else {
users.append(self.collection.document(userID))
print("added")
return
}
}
} else {
Services.crud.reads(query: self.collection.whereField("quickID", isLessThanOrEqualTo: "\(UInt64.random(in: UInt64.min ... UInt64.max))").limit(to: 1), onSuccess: { (snapshot) in
let userID = snapshot.documents.first!.documentID
if cUser.userID == userID {
Services.crud.reads(query: self.collection.whereField("quickID", isGreaterThanOrEqualTo: "\(UInt64.random(in: UInt64.min ... UInt64.max))").limit(to: 1), onSuccess: { (snapshot) in
if users.count == numOfUsers {
onSuccess(users)
} else {
users.append(self.collection.document(userID))
print("added")
return
}
}) { (e) in
print(e)
}
} else {
if users.count == numOfUsers {
onSuccess(users)
} else {
users.append(self.collection.document(userID))
print("added")
return
}
}
}) { (e) in
print(e)
}
}
}) { (e) in
print(e)
}
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T11:38:09.097",
"Id": "216151",
"Score": "2",
"Tags": [
"swift",
"firebase"
],
"Title": "Simplifying a firestore querying function"
} | 216151 |
<p>I was looking for a thread safe implementation of the observer pattern. I read <a href="https://xinhuang.github.io/posts/2015-02-11-how-a-multi-threaded-implementation-of-the-observer-pattern-can-fail.html" rel="noreferrer">https://xinhuang.github.io/posts/2015-02-11-how-a-multi-threaded-implementation-of-the-observer-pattern-can-fail.html</a> and was thinking about point 4 "Don't reinvent the wheel, use Boost.Signals2 instead". So I tried the following code and wanted to ask if it is safe to be used in a multithreaded application? What happens if an <code>Observer</code> is destructed during <code>notifyObservers</code>?</p>
<pre><code>#include <boost/signals2.hpp>
#include <iostream>
#include <string>
class AbstractObserver {
public:
using SignalType = boost::signals2::signal<void()>;
virtual ~AbstractObserver() = default;
virtual void notify() = 0;
void registerAtSubject(SignalType &sig)
{
connection_ = sig.connect([this]() { notify(); });
}
private:
boost::signals2::scoped_connection connection_;
};
class Subject {
AbstractObserver::SignalType sig_;
public:
void registerObserver(AbstractObserver &observer)
{
observer.registerAtSubject(sig_);
}
void notifyObservers() const
{
sig_();
}
};
class Observer : public AbstractObserver {
std::string id_;
public:
explicit Observer(std::string id) : id_(std::move(id))
{};
void notify() override
{
std::cout << "Observer " << id_ << " got notified" << std::endl;
}
};
int main()
{
Subject c;
{
Observer o2("B");
{
Observer o1("A");
c.registerObserver(o1);
c.notifyObservers();
c.registerObserver(o2);
c.notifyObservers();
}
c.notifyObservers();
}
c.notifyObservers();
}
</code></pre>
| [] | [
{
"body": "<p>Boost.Signals2 is a thread-safe library. It uses mutex locking internally. There are some caveats, as explained in <a href=\"https://theboostcpplibraries.com/boost.signals2-multithreading\" rel=\"nofollow noreferrer\">this article</a>:</p>\n\n<blockquote>\n <p>Almost all classes provided by Boost.Signals2 are thread safe and can\n be used in multithreaded applications. For example, objects of type\n <code>boost::signals2::signal</code> and <code>boost::signals2::connection</code> can be\n accessed from different threads.</p>\n \n <p>On the other hand, <code>boost::signals2::shared_connection_block</code> is not\n thread safe. This limitation is not important because multiple objects\n of type <code>boost::signals2::shared_connection_block</code> can be created in\n different threads and can use the same connection object.</p>\n</blockquote>\n\n<p>but in its simplest and default forms, Boost.Signals2 is multi-threading safe.</p>\n\n<p>Your given example is, indeed, thread-safe.</p>\n\n<blockquote>\n <p>What happens if an Observer is destructed during notifyObservers?</p>\n</blockquote>\n\n<p>The slot is disconnected preemptively.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T14:27:31.373",
"Id": "221653",
"ParentId": "216157",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221653",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T12:42:18.753",
"Id": "216157",
"Score": "5",
"Tags": [
"c++",
"multithreading",
"boost"
],
"Title": "C++ observer pattern via boost.signals2"
} | 216157 |
<p>I've written a function to remove <code>empty</code> or <code>""</code> value elements from an array or in other words return an array consisting only of elements containing a value. </p>
<pre><code>Option Explicit
Public Function RemoveBlanksFromArray(ByVal TheArray As Variant) As Variant
Dim temp As Variant
ReDim temp(LBound(TheArray) To LBound(TheArray))
Dim myElement As Variant
Dim myCount As Long
myCount = LBound(temp)
For Each myElement In TheArray
If myElement <> "" Then
ReDim Preserve temp(LBound(temp) To myCount)
temp(myCount) = myElement
myCount = myCount + 1
End If
Next myElement
RemoveBlanksFromArray = temp
End Function
</code></pre>
<p>The Function is passed an <code>Array</code> as an argument. The <code>Array</code> is <code>temp</code> and <code>ReDim</code>ed as a single element. It then loops each element of the passed argument and adds the value if it's not <code>""</code> or <code>Empty</code>. </p>
<p>I've used <code>ReDim Preserve temp(LBound(temp) To myCount)</code> before each element is written to <code>temp</code> to dynamically set the upper bound. </p>
<p>I feel there may be more efficient ways to perform this task. </p>
<p>Are there any inefficiencies in <code>ReDim</code>ing the upper bound the way I have done it? </p>
<p>Can the upper bound of the array be set in any other way dynamically?</p>
<p>Have I broken any sacred rules in the formatting of the function or naming conventions etc?</p>
| [] | [
{
"body": "<blockquote>\n<pre><code>Option Explicit\n</code></pre>\n</blockquote>\n\n<p>Always nice to see.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>Public Function RemoveBlanksFromArray(ByVal TheArray As Variant) As Variant\n</code></pre>\n</blockquote>\n\n<p>The usual convention for parameters is <code>camelCase</code> - i.e. <code>theArray</code>. Otherwise looks fine, maybe I'd call it <code>inputArray</code> so it's obvious to the rest of your code what it contains (<a href=\"https://codereview.stackexchange.com/a/56036/146810\">more on naming</a>).</p>\n\n<p>One thing to watch out for when passing arrays <code>byVal</code>. Arrays are a bit like objects in VBA -you never pass actual objects around, just addresses. Similarly, <code>byVal</code> <a href=\"https://stackoverflow.com/a/49845724/6609896\">doesn't make a copy of the actual data</a> in <code>TheArray</code>, just a copy of the <em>pointer</em> to the array's location in memory. With primitive types when you write something like this:</p>\n\n<pre><code>Sub Foo(ByVal bar As Long)\n</code></pre>\n\n<p>... only a copy of <code>bar</code> is passed, meaning <code>Foo</code> cannot do anything to alter the original variable. However in your code, you <em>could</em> accidentally modify the values in <code>TheArray</code>.</p>\n\n<p>This is one reason why I'd suggest strongly typing the array - as these can only be passed <code>ByRef</code>; in your comparisons you treat the elements like strings:</p>\n\n<blockquote>\n<pre><code>If myElement <> \"\" Then\n</code></pre>\n</blockquote>\n\n<p>So why not explicitly declare the array as such?</p>\n\n<pre><code>Public Function RemoveBlanksFromStringArray(ByRef theArray() As String) As String()\n</code></pre>\n\n<p>Now the <code>ByRef</code> is clear, and you'll get a minor performance boost because you don't have to cast to and from <code>Variant</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code>Dim temp As Variant\n'[...]\nRemoveBlanksFromArray = temp\n</code></pre>\n</blockquote>\n\n<p>I tend to name variables that get assigned to the return value of a function <code>result</code>, just personal preference.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>ReDim temp(LBound(TheArray) To LBound(TheArray))\n</code></pre>\n</blockquote>\n\n<p>Glad to see you've explicitly referenced both bounds, avoiding <code>Option Base 1</code> or any <em>convention</em> (hint, there isn't one)</p>\n\n<hr>\n\n<blockquote>\n<pre><code>Dim myCount As Long\n</code></pre>\n</blockquote>\n\n<p>I think this name is misleading. It's not a count really is it, because depending on <code>LBound(TheArray)</code> it might start at 0 or 1 or 7 for all we know. You could name it something like <code>indexOfTempArray</code>, but I think a count is actually more useful and intuitive, so we'll make it one, but maybe more explicit:</p>\n\n<pre><code>Dim countOfNonBlanks As Long\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>For Each myElement In TheArray\n</code></pre>\n</blockquote>\n\n<p>Now there's a small optimisation to be made here; it's marginally quicker to loop over an array by index than with For-Each, so this becomes</p>\n\n<pre><code>Dim index As Long\nFor index = LBound(TheArray) to UBound(TheArray)\n If TheArray(index) <> \"\" Then\n '...\n</code></pre>\n\n<p>Oh and while we're here, prefer <code>vbNullString</code> to <code>\"\"</code> because the latter could be a non printable character or might have a space in there if you squint etc. vbNullString is unequivocal (<em>Rubberduck</em> would've told you that)</p>\n\n<hr>\n\n<p>That all brings us to the bottle-neck of your code (I think):</p>\n\n<blockquote>\n<pre><code>ReDim Preserve temp(LBound(temp) To myCount)\ntemp(myCount) = myElement\nmyCount = myCount + 1\n</code></pre>\n</blockquote>\n\n<p>Your hunch is right, there's a better way. Arrays in VBA are stored as a continuous pre-allocated bit of memory. (This is why array lookups are so fast, because all you do is look up the address of the first item of the array, and offset by a fixed distance - 1 lookup operation. Collections store the address of <em>every element</em> of the array, so to find an element in memory, you first lookup the address associated with it, <em>then</em> look at that address in memory - 2 lookup operations).</p>\n\n<p>However with VBA Arrays what you gain in speed you lose in flexibility. Because the memory is pre-allocated, you can't just add another element on the end, that memory may be in use for something else. So <code>ReDim Preserve</code> actually copies the entire array to a new (bigger) location in memory. That's slow! <a href=\"https://stackoverflow.com/a/45741887/6609896\">Here's</a> where someone told me all that.</p>\n\n<p>Anyway, <strong>what this boils down to is</strong>; imagine the largest size your <code>temp</code> array could ever be (i.e no blanks found, so the same size as your input array), fill it up partially, then <strong><code>ReDim Preserve</code> it once</strong> back down to the actual size it has to be.</p>\n\n<hr>\n\n<p><strong>Putting all that together we get</strong>:</p>\n\n<pre><code>Public Function RemoveBlanksFromStringArray(ByRef inputArray() As String) As String()\n\n Dim base As Long\n base = LBound(inputArray)\n\n Dim result() As String\n ReDim result(base To UBound(inputArray))\n\n Dim countOfNonBlanks As Long\n Dim i As Long\n Dim myElement As String\n\n For i = base To UBound(inputArray)\n myElement = inputArray(i)\n If myElement <> vbNullString Then\n result(base + countOfNonBlanks) = myElement\n countOfNonBlanks = countOfNonBlanks + 1\n End If\n Next i\n If countOfNonBlanks = 0 Then\n ReDim result(base To base)\n Else\n ReDim Preserve result(base To base + countOfNonBlanks - 1)\n End If\n\n RemoveBlanksFromStringArray = result\n\nEnd Function\n</code></pre>\n\n<p>On a test of 500,000 items</p>\n\n<ul>\n<li>original code took 1.1481±0.0001 s, </li>\n<li>refactored code took 0.1157±0.0001 s </li>\n</ul>\n\n<p>or ~ 10 times faster</p>\n\n<hr>\n\n<h2>Addendum</h2>\n\n<p>Now I think about it, the original code with copying memory boils down to an <span class=\"math-container\">\\$\\mathcal O (n^2)\\$</span> algorithm, the refactored code is <span class=\"math-container\">\\$\\mathcal O (n)\\$</span> (here <span class=\"math-container\">\\$ n\\$</span> is the size of the array, <span class=\"math-container\">\\$\\mathcal O (n^a)\\$</span> basically means you loop over the array <span class=\"math-container\">\\$ a\\$</span> times). Using <code>Timer</code> for some rough results, you can see this trend:</p>\n\n<pre><code>10,000 elements\n Old 0 \n New 0 \n100,000 elements\n Old 0.046875 (same order of magnitude as each other)\n New 0.015625 \n1,000,000 elements\n Old 3.171875 (1 order of magnitude slower relative to New)\n New 0.125 \n10,000,000 elements\n Old 321.46875 (2 orders of magnitude slower)\n New 1.3125 \n</code></pre>\n\n<p>I.e. When you do 10x more elements, OP's O(n^2) code gets 10^2 = 100 times slower, the refactored O(n) gets 10^1 = 10 times slower. Therefore relative to the new code, the old code gets 10x slower.</p>\n\n<p>Interestingly, because both algorithms are doing essentially the same operation (writing to memory), which is an O(1) operation (i.e. independent of the rest of the code), once you operate on large enough arrays, optimising the rest of the code becomes inconsequential (Early vs Late binding, For Each vs Index, re-using LBound vs re-measuring). So once you get the algorithm down to the lowest complexity possible (assuming performance is an issue), then pick whichever method is most readable and maintainable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T16:47:55.997",
"Id": "418293",
"Score": "0",
"body": "Nice answer. You only need to Redim the array `If countOfNonBlanks > 0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T16:58:11.333",
"Id": "418294",
"Score": "0",
"body": "@RickDavin Thanks! Are you sure? Because `ReDim result(base To UBound(inputArray))` is one of the first moves, before we know `countOfNonBlanks`. If we wan't to emulate OP's code and return a 1 element empty array if the input array is entirely blank, `ReDim` *is* needed for `countOfNonBlanks > 0` surely? `ReDim Preserve` is for when `countOfNonBlanks > 0`. Or am I missing something obvious (wouldn't be the first time ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T17:22:42.000",
"Id": "418298",
"Score": "0",
"body": "@Greedo what are you using to get the time comparisons between each version?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T17:27:56.757",
"Id": "418300",
"Score": "0",
"body": "@IvenBach [My `StopWatch` class](https://codereview.stackexchange.com/q/194859/146810) for the timings, `testArray(1 To 500000) As String` filled with ~50% blanks, 50% 10-20 char text. Why, are you not getting similar results, or just out of curiosity? Do you think I should post the test code, it's quite straightforward but fairly verbose because I've used RubberDuck unit tests (OTT)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T17:57:44.320",
"Id": "418303",
"Score": "1",
"body": "Pure curiosity. I'd seen your previous work towards benchmarking. TL;DR = your refactoring blew mine out of the water speed-wise, so much so I'm ashamed to show it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T18:15:24.007",
"Id": "418311",
"Score": "0",
"body": "@IvenBach Oh take a look at the last bit I added. It's not necessarily that my re-factoring is *fast* (i.e. the individual operations may be slow ones), it's more that it's less *complex* (i.e. there are fewer of those operations to carry out for a given array size). So once I let the array size tend to very large, the less complex will always win out. But depending on OP's requirements, a more complex but less bulky approach might be preferable, especially if the array size is small. It's perfectly possible that your refactoring could be faster for 1 element! Just hard to measure accurately"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T18:46:34.180",
"Id": "418315",
"Score": "0",
"body": "@Greedo The benchmarking is excellent! Thanks for the addendum stats. I wasn't aware of the memory allocation for Arrays nor that I couls explicitly declare a type for them so that is most helpful. I need to brush up on the arguments, i don't quite understand the benefit of passing `ByRef` over `ByVal` (but maybe it will make sene another time - it's 4am!) If there is anything to add please share otherwise i'll read into documentation and the like later.on. I'm glad to see for the most part I was on the right track. Thanks for taking the time to.give such a detailed review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T04:11:40.233",
"Id": "418644",
"Score": "0",
"body": "wonderful write up!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T16:41:25.363",
"Id": "216179",
"ParentId": "216161",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "216179",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T13:04:32.190",
"Id": "216161",
"Score": "5",
"Tags": [
"performance",
"vba"
],
"Title": "Public Function to remove empty or \"\" elements from a single dimension array"
} | 216161 |
<p>The following codes generate table row dynamically. I wonder if there are better ways of generating the same data. Also instead of manually coding the heading and the table itself, is it possible to code them with less codes without using the innerHTML function.</p>
<pre><code><table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Mark Score</th>
</tr>
</thead>
</table>
</code></pre>
<p>Data:</p>
<pre><code>const students = {
'24': {
'id':'24',
'Name':'Zuali',
'mark':30,
},
'25': {
'id':'25',
'Name':'Famkima',
'mark':52,
},
'27':{
'id':'27',
'Name':'Duha',
'mark':77,
},
'28':{
'id':'28',
'Name':'Rema',
'mark':81,
},
'29':{
'id':'29',
'Name':'Sanga',
'mark':47,
},
'30':{
'id':'30',
'Name':'Dari',
'mark':23,
},
};
</code></pre>
<p>JS code to create the table data:</p>
<pre><code>const markObtained = Object.keys(students).reduce(function(names, name) {
if (students[name].mark>=20) {
names[name] = students[name];
}
return names;
}, {});
const doc = document.createDocumentFragment();
const table = document.querySelector("table");
for(let i=0; i<Object.keys(markObtained).length; i++) {
const data = Object.values(markObtained)[i];
const tr = document.createElement("tr");
for (const v in data){
const td = document.createElement("td");
td.textContent = data[v];
tr.appendChild(td);
}
table.appendChild(tr);
}
table.appendChild(doc);
</code></pre>
<p>I would highly appreciate if any expert in js can help me better optimize the codes and give me another workaround examples?</p>
| [] | [
{
"body": "<h2>Minor problems and style points</h2>\n\n<ul>\n<li><p>The table has named columns set out already. This is problematic as the <code>for in</code> loop is alphabetic and thus you would be adding <code>Name, id, mark</code> which does not match the column headings.</p>\n\n<p>It would be best to have the student fields defined as an array in the order that they are to be displayed. This can either be as dataset properties of the array or in the source code, or added to the dataset. The example has it in the source (be cause I am lazy)</p></li>\n<li><p>Use <code>for of</code> rather than <code>for(;;)</code> and try to avoid ever using <code>for in</code> as it has a long list of caveats and problems associated with its use.</p></li>\n<li><p>The function <code>markObtained</code>...</p>\n\n<ul>\n<li><p>...seems redundant in the example you give. The data can be accessed just as easily in one pass.</p></li>\n<li><p>...the naming is confusing withing the <code>reduce</code> call. <code>names</code>, and <code>name</code> are both referring to the student <code>id</code>. This is especially problematic as the dataset has a field called <code>Name</code> (which should not be capitalized)</p></li>\n<li><p>...creates an object indexed by id, the dataset you have shown is also an Object. Both are indexed via student id, yet you don't ever use the student id to lookup a student. markObtained would be best to return an array of student id's rather than copy the student references to a new object. See Example A</p></li>\n</ul></li>\n<li><p>The document fragment your create is not used, the last line is adding an empty fragment to the table.</p></li>\n<li><p>A <code>table</code> has <code>insertRow()</code>, and <code>rows</code> have <code>insertCell()</code>, use them to add to the table rather than create them as DOM element via <code>document.createElement</code></p></li>\n</ul>\n\n<h2>Extract <code>ids</code></h2>\n\n<p>From above points regarding the function <code>markObtained</code> The example creates an array of student ids that can be used to locate students in the original dataset. Also renames the variables so not to be confusing.</p>\n\n<p>Example A</p>\n\n<pre><code>const markObtained = Object.keys(students).reduce(function(ids, id) {\n if (students[id].mark>=20) { ids[id] = id }\n return ids;\n}, []);\n</code></pre>\n\n<h2>Adding to DOM</h2>\n\n<p>You are appending to the table that is on the page. Each time you add a cell or row you are forcing a re flow.</p>\n\n<p>You can either create the whole table in code and add it to the DOM when ready, or you can remove the table from the DOM, modify it and put it back see Example B.</p>\n\n<p>If you remove and then put back it would be best to put the table within a container to ensure it goes where it belongs without undue fuss.</p>\n\n<p>Example B</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const students = {\n \"24\": {id: 24, name: \"Zuali\", mark: 30},\n \"25\": {id: 25, name: \"Famkima\", mark: 52},\n \"27\": {id: 27, name: \"Duha\", mark: 77},\n \"28\": {id: 28, name: \"Rema\", mark: 81},\n \"29\": {id: 29, name: \"Sanga\", mark: 47},\n \"30\": {id: 30, name: \"Dari\", mark: 23},\n};\n\nconst PASS_MARK = 20;\nconst FIELDS = [\"id\", \"name\", \"mark\"];\nupdateStudentsTable(students);\n \nfunction addPassed(table, students, pass = PASS_MARK) {\n for (const student of students) {\n if (student.mark >= pass) {\n const row = table.insertRow();\n for (const field of FIELDS) {\n row.insertCell().textContent = student[field];\n }\n }\n }\n}\nfunction updateStudentsTable(students) {\n const table = document.querySelector(\"table\");\n const par = table.parentElement;\n par.removeChild(table);\n addPassed(table, Object.values(students));\n par.appendChild(table);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div>\n <table>\n <thead>\n <tr>\n <th>Id</th><th>Name</th><th>Mark</th>\n </tr>\n </thead>\n </table>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T19:32:30.167",
"Id": "216187",
"ParentId": "216165",
"Score": "2"
}
},
{
"body": "<h3>Convert key-value objects to array</h3>\n\n<p>The way you traverse your objects is convoluted. Calling <code>Object.keys()</code> and <code>Object.values()</code> all over the place like <code>for(let i=0; i<Object.keys(markObtained).length; i++)</code> and <code>const data = Object.values(markObtained)[i];</code> can easily be avoided if you transform your input into an array.</p>\n\n<pre><code>// input = your original students object\nconst students = Array.from(Object.keys(input), k => input[k]);\n</code></pre>\n\n<p>The advantage is you can use built-in methods to <em>filter</em>, <em>map</em>, <em>reduce</em> the array.</p>\n\n<blockquote>\n<pre><code>if (students[name].mark>=20) {\n names[name] = students[name];\n}\n</code></pre>\n</blockquote>\n\n<p>can be replaced with..</p>\n\n<pre><code>students.filter(x => x.mark >= 20).map(x => x.Name);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T07:25:53.043",
"Id": "226668",
"ParentId": "216165",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T13:14:43.597",
"Id": "216165",
"Score": "2",
"Tags": [
"javascript",
"dom",
"iterator"
],
"Title": "JS to create Table data dynamically"
} | 216165 |
<p>I've implemented a self-organising map in Tensorflow's low-level API. After testing with sklearn's Iris data, the results seem correct. I did implement the algorithm also using NumPy before converting it to <code>tf</code>, because I'm new to Tensorflow, and had no idea whether it would work or not. So of course I tried out which would perform better. It turns out the Numpy implementation is far better for a smallish-scale problem.</p>
<p>To me this sounds a bit off. When loading a data set of ~3500x10 to GPU memory and carrying out basically the exact same algorithm with all-tf operations, I was at least expecting some sort of improvement with matrix-matrix broadcasted sums, multiplications and powers.</p>
<p>As I said, I have little experience with Tensorflow, so I started wondering if something is wrong with the code. The result seems good enough, but I'm not aware of many best practices or performance caveats. I'm especially after performance and TF-related feedback, but of course I'll happily take any criticism on my code!</p>
<pre><code>import numpy as np
import tensorflow as tf
from tqdm import tqdm
def learning_rate(epoch: tf.placeholder, max_epochs: int):
with tf.name_scope('learning_rate'):
return tf.exp(-4 * epoch / max_epochs)
def neighbourhood(r: tf.placeholder, epoch: tf.placeholder, max_epochs: int, size: int):
with tf.name_scope('neighbourhood'):
return tf.exp(
- (2 * r / size) ** 2
* (max_epochs / (max_epochs - epoch)) ** 3
)
class SelfOrganisingMap:
def __init__(self, shape: tuple, features: int, *_,
max_epochs: int = None, init: str = 'uniform', learning_rate: float = 0.1):
"""
Self-organising map using TensorFlow.
:param shape: map dimensions
:param features: number of input features
:param _: used to force calling with keyword arguments below
:param max_epochs: used to scale the neighbourhood and learning rate functions
:param init: method of weight initialisation. 'uniform' for drawing from an uniform
distribution between 0..1, 'normal' for drawing from X~N(0,1)
:param learning_rate: initial learning rate multiplier
"""
self._weights = None
self._shape = shape
self._features = features
self._neighbour_shape = (len(shape),) + tuple(1 for _ in shape) + (-1,)
self._epochs = 0
self._max_epochs = max_epochs
self._initial_lr = learning_rate
if init == 'uniform':
self._initialiser = tf.random_uniform_initializer
elif init == 'normal':
self._initialiser = tf.random_normal_initializer
else:
raise AssertionError('Unknown weights initialiser type "%s"!' % init)
@property
def weights(self):
if self._weights is None:
raise ValueError('Map not fitted!')
return self._weights
@property
def initialiser(self):
if self._weights is None:
return self._initialiser
else:
return tf.convert_to_tensor(self._weights)
@property
def shape(self): return self._shape
@property
def n_nodes(self): return int(np.prod(self.shape))
@property
def features(self): return self._features
@property
def epochs(self): return self._epochs
@property
def max_epochs(self): return self._max_epochs
def project(self, data: np.ndarray) -> np.array:
"""
Project data onto the map. NumPy implementation for simplicity.
:param data: samples
:return: node indices
"""
diff = self.weights - data
dist = np.sum(diff ** 2, axis=-1, keepdims=True)
return np.array(np.unravel_index(
np.argmin(dist.reshape((-1, data.shape[0])), axis=0), self.shape
))
def train(self, x: np.ndarray, epochs: int, batch_size: int = 1) -> None:
"""
Create training graph and train SOM.
:param x: training data
:param epochs: number of epochs to train
:param batch_size: number of training examples per step
:return: None
"""
graph = tf.Graph()
sess = tf.Session(graph=graph)
x = x.astype(np.float64)
if x.shape[0] % batch_size != 0:
raise ValueError('Bad batch_size, last batch would be incomplete!')
# Construct graph
with graph.as_default():
indices = tf.convert_to_tensor(np.expand_dims(
np.indices(self.shape, dtype=np.float64), axis=-1
))
weights = tf.get_variable(
'weights', (*self.shape, 1, self.features), initializer=self.initialiser, dtype=tf.float64
)
with tf.name_scope('data'):
data = tf.data.Dataset.from_tensor_slices(x)
data = data.shuffle(buffer_size=10000).repeat(epochs)
data = data.batch(batch_size, drop_remainder=True)
data = data.make_one_shot_iterator().get_next()
with tf.name_scope('winner'):
diff = weights - data
dist = tf.reduce_sum(diff ** 2, axis=-1, keepdims=True)
w_ix = tf.argmin(tf.reshape(dist, (self.n_nodes, data.shape[0])), axis=0)
winner_op = tf.convert_to_tensor(tf.unravel_index(w_ix, self.shape))
with tf.name_scope('update'):
curr_epoch = tf.placeholder(dtype=tf.int64, shape=())
idx_diff = indices - tf.reshape(tf.cast(
winner_op, dtype=tf.float64
), shape=self._neighbour_shape)
idx_dist = tf.norm(idx_diff, axis=0)
l_rate = learning_rate(curr_epoch, self.max_epochs)
n_hood = neighbourhood(
idx_dist, curr_epoch, self.max_epochs, max(self.shape)
)
update = diff * l_rate * tf.expand_dims(n_hood, axis=-1)
update_op = weights.assign(
weights - self._initial_lr * tf.reduce_sum(update, axis=-2, keepdims=True)
)
init = tf.global_variables_initializer()
# Initialise all variables
sess.run(init)
batches = int(np.ceil(x.shape[0] // batch_size))
for i in tqdm(range(epochs)):
for b in range(batches):
sess.run(update_op, feed_dict={
curr_epoch: self.epochs + i
})
self._weights = sess.run(weights)
self._epochs += epochs
</code></pre>
<p>Here's a short test snippet as well:</p>
<pre><code>from sklearn.utils import shuffle
from sklearn.datasets import load_iris
from sklearn.preprocessing import RobustScaler
a, _ = load_iris(True)
a, _ = shuffle(a, _)
a = RobustScaler().fit_transform(a)
epochs = 100
som = SelfOrganisingMap((100, 100), 4, max_epochs=epochs, init='normal')
som.train(a, epochs, batch_size=1)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T14:54:21.213",
"Id": "216170",
"Score": "2",
"Tags": [
"python",
"performance",
"tensorflow"
],
"Title": "Simple Self-Organizing Map (SOM) in Tensorflow"
} | 216170 |
<p>My Sudoku solver is fast enough and good with small data (4*4 and 9*9 Sudoku). But with a 16*16 board it takes too long and doesn't solve 25*25 Sudoku at all. How can I improve my program in order to solve giant Sudoku faster?</p>
<p>I use backtracking and recursion.</p>
<p>It should work with any size Sudoku by changing only the define of <code>SIZE</code>, so I can't make any specific bit fields or structs that only work for <code>9*9</code>, for example. </p>
<pre><code>#include <stdio.h>
#include <math.h>
#define SIZE 16
#define EMPTY 0
int SQRT = sqrt(SIZE);
int IsValid (int sudoku[SIZE][SIZE], int row, int col, int number);
int Solve(int sudoku[SIZE][SIZE], int row, int col);
int main() {
int sudoku[SIZE][SIZE] = {
{0,1,2,0,0,4,0,0,0,0,5,0,0,0,0,0},
{0,0,0,0,0,2,0,0,0,0,0,0,0,14,0,0},
{0,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0},
{11,0,0,0,0,0,0,0,0,0,0,16,0,0,0,0},
{0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,16,0,0,0,0,0,0,2,0,0,0,0,0},
{0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0},
{0,0,14,0,0,0,0,0,0,4,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,1,16,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,14,0,0,13,0,0},
{0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0},
{16,0,0,0,0,0,11,0,0,3,0,0,0,0,0,0},
};
/*
int sudoku[SIZE][SIZE] = {
{6,5,0,8,7,3,0,9,0},
{0,0,3,2,5,0,0,0,8},
{9,8,0,1,0,4,3,5,7},
{1,0,5,0,0,0,0,0,0},
{4,0,0,0,0,0,0,0,2},
{0,0,0,0,0,0,5,0,3},
{5,7,8,3,0,1,0,2,6},
{2,0,0,0,4,8,9,0,0},
{0,9,0,6,2,5,0,8,1}
};*/
if (Solve (sudoku,0,0))
{
for (int i=0; i<SIZE; i++)
{
for (int j=0; j<SIZE; j++) {
printf("%2d ", sudoku[i][j]);
}
printf ("\n");
}
}
else
{
printf ("No solution \n");
}
return 0;
}
int IsValid (int sudoku[SIZE][SIZE], int row, int col, int number)
{
int prRow = SQRT*(row/SQRT);
int prCol = SQRT*(col/SQRT);
for (int i=0;i<SIZE;i++){
if (sudoku[i][col] == number) return 0;
if (sudoku[row][i] == number) return 0;
if (sudoku[prRow + i / SQRT][prCol + i % SQRT] == number) return 0;}
return 1;
}
int Solve(int sudoku[SIZE][SIZE], int row, int col)
{
if (SIZE == row) {
return 1;
}
if (sudoku[row][col]) {
if (col == SIZE-1) {
if (Solve (sudoku, row+1, 0)) return 1;
} else {
if (Solve(sudoku, row, col+1)) return 1;
}
return 0;
}
for (int number = 1; number <= SIZE; number ++)
{
if(IsValid(sudoku,row,col,number))
{
sudoku [row][col] = number;
if (col == SIZE-1) {
if (Solve(sudoku, row+1, 0)) return 1;
} else {
if (Solve(sudoku, row, col+1)) return 1;
}
sudoku [row][col] = EMPTY;
}
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:16:32.937",
"Id": "418280",
"Score": "1",
"body": "Can you add a 9x9 and 16x16 file? It will make answering easier."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:32:26.500",
"Id": "418281",
"Score": "0",
"body": "When you added the 16 X 16 grid you left the size at 9 rather than changing it to 16. This might lead to the wrong results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:35:21.193",
"Id": "418282",
"Score": "5",
"body": "Sudoku is NP complete. No matter what improvements you make to your code, it will become exceptionally slow as `SIZE` becomes large."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:40:25.933",
"Id": "418283",
"Score": "0",
"body": "@pacmaninbw oh sorry, I only forgot to change it while I was editing my post earlier. With that part there is no problem, but thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:42:26.523",
"Id": "418284",
"Score": "1",
"body": "Have you tried to use any heuristic? For example if you try solving for the number that occurs the most often first you will have a smaller problem set to solve."
}
] | [
{
"body": "<p>The first thing that will help is to switch this from a recursive algorithm to an iterative one. This will prevent the stack overflow that prevents you from solving 25x25, and will be a bit faster to boot.</p>\n\n<p>However to speed this up more, you will probably need to use a smarter algorithm. If you track what numbers are possible in each square, you will find that much of the time, there is only 1 possibility. In this case, you know what number goes there. You then can update all of the other squares in the same row, col, or box as the one you just filled in. To implement this efficiently, you would want to define a set (either a bitset or hashset) for what is available in each square, and use a heap to track which squares have the fewest remaining possibilities.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T19:42:51.143",
"Id": "418317",
"Score": "3",
"body": "Might I suggest [Dancing links](https://en.wikipedia.org/wiki/Dancing_Links) as an entry point for your search into a smarter algoriothm?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T23:49:34.913",
"Id": "418331",
"Score": "1",
"body": "The max recursion depth of this algorithm = number of squares, I think. \n `25*25` is only 625. The recursion doesn't create a copy of the board in each stack frame, so it probably only uses about 32 bytes per frame on x86-64. (`Solve` doesn't have any locals other than its args to save across a recursive call: an 8-byte pointer and 2x 4-byte `int`. That plus a return address, and maintaining 16-byte stack alignment as per the ABI, probably adds up to a 32-byte stack frame on x86-64 Linux or OS X. Or maybe 48 bytes with Windows x64 where the shadow space alone takes 32 bytes.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T23:54:50.713",
"Id": "418333",
"Score": "2",
"body": "Anyway, that's only `25*25*48` = 30kB (not 30kiB) of stack memory max, which trivial (stack limits of 1MiB to 8MiB are common). Even a factor of 10 error in my reasoning isn't a problem. So it's not stack overflow, it's simply the `O(SIZE^SIZE)` exponential time complexity that stops SIZE=25 from running in usable time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T23:57:53.457",
"Id": "418335",
"Score": "0",
"body": "Yeah, any idea why it wasn't returning for 25x25 before? Just speed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T00:00:21.687",
"Id": "418336",
"Score": "0",
"body": "@OscarSmith: I'd assume just speed, yeah, that's compatible with the OP's wording. `n^n` grows *very* fast! Or maybe an unsolvable board? Anyway, [Sudoku solutions finder using brute force and backtracking](//codereview.stackexchange.com/q/106220) goes into detail on your suggestion to try cells with fewer possibilities first. There are several other Q&As in the \"related\" sidebar that look useful."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:56:44.810",
"Id": "216175",
"ParentId": "216171",
"Score": "15"
}
},
{
"body": "<p>The strategy needs work: brute-force search is going to scale very badly. As an order-of-magnitude estimate, observe that the code calls <code>IsValid()</code> around <code>SIZE</code> times for each cell - that's O(<em>n</em>³), where <em>n</em> is the <code>SIZE</code>.</p>\n\n<p>Be more consistent with formatting. It's easier to read (and to search) code if there's a consistent convention. To take a simple example, we have:</p>\n\n<blockquote>\n<pre><code>int IsValid (int sudoku[SIZE][SIZE], int row, int col, int number)\nint Solve(int sudoku[SIZE][SIZE], int row, int col)\n\n if (Solve (sudoku,0,0))\n if(IsValid(sudoku,row,col,number))\n</code></pre>\n</blockquote>\n\n<p>all with differing amounts of space around <code>(</code>. This kind of inconsistency gives an impression of code that's been written in a hurry, without consideration for the reader.</p>\n\n<p>Instead of defining <code>SIZE</code> and deriving <code>SQRT</code>, it's simpler to start with <code>SQRT</code> and define <code>SIZE</code> to be <code>(SQRT * SQRT)</code>. Then there's no need for <code><math.h></code> and no risk of floating-point approximation being unfortunately truncated when it's converted to integer.</p>\n\n<hr>\n\n<p>The declaration/definition of <code>main()</code> should specify that it takes no arguments:</p>\n\n<pre><code>int main(void)\n</code></pre>\n\n<p>If we write <code>int main()</code>, that declares <code>main</code> as a function that takes an <em>unspecified</em> number of arguments (unlike C++, where <code>()</code> is equivalent to <code>(void)</code>).</p>\n\n<p>You can see that C compilers treat <code>void foo(){}</code> differently from <code>void foo(void){}</code> <a href=\"https://godbolt.org/z/pJyy64\" rel=\"nofollow noreferrer\">on the Godbolt compiler explorer</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T20:22:55.360",
"Id": "418320",
"Score": "2",
"body": "Very good suggestion to make `SQRT` a compile-time constant. The code uses stuff like `prRow + i / SQRT` and `i % SQRT`, which will compile to a runtime integer division (like x86 `idiv`) because `int SQRT` is a non-`const` global! And with a non-constant initializer, so I don't think this is even valid C. But fun fact: gcc does accept it as C (doing constant-propagation through `sqrt` even with optimization disabled). But clang rejects it. https://godbolt.org/z/4jrJmL. Anyway yes, we get nasty `idiv` unless we use `const int sqrt` (or better unsigned) https://godbolt.org/z/NMB156"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T16:00:01.137",
"Id": "216177",
"ParentId": "216171",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T14:59:39.570",
"Id": "216171",
"Score": "18",
"Tags": [
"performance",
"c",
"recursion",
"sudoku"
],
"Title": "Simple recursive Sudoku solver"
} | 216171 |
<p>I need to find the sum of the digits of the given number and repeat the process until the value lies between 1 to 9. </p>
<p>e.g
if the input is 72457 then, </p>
<p>7+2+4+5+7 = 25</p>
<p>2+5 = 7</p>
<p>so , the function should return 7. </p>
<p>Also, if the input is a negative number like -72457 the function should return -7.</p>
<p>Here's what i tried,</p>
<pre><code>int digitSum(int input1){
int flag=0;
if(input1<0)
flag=1;
int rem,sum=0;
int x=abs(input1);
while(x>0){
rem=x%10;
sum+=rem;
x=x/10;
}
int value = sum%9;
if(value==0){
if(flag==1)
return -9;
else
return 9;
}
else{
if(flag==1)
return -value;
else
return value;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T16:01:02.327",
"Id": "418288",
"Score": "1",
"body": "What if the input is `0`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T16:11:35.160",
"Id": "418289",
"Score": "0",
"body": "You can shuffle the logic around a bit to simplify this by first having an int which represents the sign of the input number by dividing input / abs(input), which will give you either -1 or 1. \n\nThen, during your summation loop, do a comparison of != 0. so that you don't have to worry about the sign.\n\nAnd finish off by returning sum * sign"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T16:23:59.023",
"Id": "418292",
"Score": "1",
"body": "`n % 9` gets you most of the way there; you only need to adjust zero results to ±9, and you're done."
}
] | [
{
"body": "<p>A simplified pure numerical function may be:</p>\n\n<pre><code>int digitSum(int input) {\n int n,m,s = input<0 ? -1:1;\n for(n=input*s; n>9; ) {\n for(m=n, n=0; m>0; m/=10)\n n+=m%10;\n }\n return n*s;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T14:56:13.477",
"Id": "418408",
"Score": "0",
"body": "Thanks, @holger, I missed the recursivness of the problem."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T09:19:26.477",
"Id": "216225",
"ParentId": "216173",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:33:00.010",
"Id": "216173",
"Score": "1",
"Tags": [
"c"
],
"Title": "Find the sum of the digits of a given number"
} | 216173 |
<p>In the codebase I support, I found the following code. I am interested in your opinion about its expediency and especially the expediency of redefining the operator().</p>
<pre><code> template <typename KEY, typename VALUE>
class MyUnorderedMap {
std::unordered_map<KEY, VALUE> map;
public:
template <typename T>
auto insert(const T value) {
return map.insert(value);
}
inline auto& operator()(const KEY& r) { return (*this)[r]; }
inline auto& operator[](const KEY r) { return map[r]; }
inline auto find(const KEY& key) const { return map.find(key); }
inline auto size() const { return map.size(); }
inline auto begin() { return map.begin(); }
inline auto end() { return map.end(); }
inline bool exists(const KEY& userId) const {
return map.find(userId) != map.end();
}
bool remove(const KEY& userId) {
auto it = map.find(userId);
bool retval = (it != map.end());
if (retval)
map.erase(it);
return retval;
}
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:48:20.340",
"Id": "418287",
"Score": "3",
"body": "Welcome to [codereview.se]! It sounds like this is code you found rather than wrote yourself. Is that the case? If so I'm afraid this is off-topic because we only review code written by the user who posted the review question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:27:47.860",
"Id": "418383",
"Score": "0",
"body": "@Null this is kind of crazy, ok, this is my code. more precisely the code that I support"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T20:04:08.690",
"Id": "418611",
"Score": "2",
"body": "Perfectly valid thing to review."
}
] | [
{
"body": "<p>I question the value of this template class. We hide many important members of <code>std::unordered_map</code> (including <code>crbegin()</code>, <code>empty()</code>, <code>reserve()</code>, <code>at()</code>, <code>try_emplace()</code>) for no good reason. The additional functions that are provided have no business being members: they are perfectly implementable as free functions without privileged access.</p>\n\n<p>Considering the members in turn:</p>\n\n<ul>\n<li><code>insert()</code>: only instantiable if <code>T</code> is convertible to the map's <code>value_type</code>. Unnecessarily copies the argument.</li>\n<li><code>operator()</code>: unnecessary, given that we have <code>operator[]</code>.</li>\n<li><code>operator[]</code>: unnecessarily copies its argument.</li>\n<li><code>find()</code>, <code>size()</code> <code>begin()</code>, <code>end()</code>: required only because the map is private.</li>\n<li><code>exists()</code>: should be a free function. If this is generic, why is the parameter called <code>userId</code>?</li>\n<li><code>remove()</code> - why not just use the <code>erase()</code> that accepts a key? Or do we have to build with pre-C++11 library?</li>\n</ul>\n\n<hr>\n\n<p>When I've wanted to provide something like the <code>exists()</code> here, I've made it a standalone template function that can work with many kinds of container:</p>\n\n\n\n<pre><code>/*\n * contains()\n * A convenience overload that searches from beginning to end of a container.\n *\n * If an iterator is supplied, it will be written with the found position or\n * container.end() as appropriate.\n */\ntemplate<typename T, typename U>\ninline bool contains(const T& container, const U& value)\n{\n using std::begin;\n using std::end;\n return find(begin(container), end(container), value) != end;\n}\n\ntemplate<typename T, typename U, typename Iter>\n /* Iter should be a T::iterator or T::const_iterator */\ninline bool contains(T& container, const U& value, Iter& it)\n{\n using std::begin;\n using std::end;\n return (it = find(begin(container), end(container), value)) != end;\n}\n</code></pre>\n\n\n\n<pre><code>/*\n * Overloads for pointer-to-const values within containers of pointer-to-mutable.\n */\ntemplate<typename T, typename U>\ninline bool contains(const T& container, const U* value)\n{\n using std::begin;\n using std::end;\n return find(begin(container), end(container), value) != end;\n}\n\ntemplate<typename T, typename U, typename Iter>\ninline bool contains(const T& container, const U* value, Iter& it)\n{\n using std::begin;\n using std::end;\n return (it = find(begin(container), end(container), value)) != end;\n}\n</code></pre>\n\n\n\n<pre><code>/*\n * Overloads for maps (by key)\n */\ntemplate<typename T>\ninline bool contains(const T& container, const typename T::key_type& key)\n{\n return container.find(key) != container.end();\n}\n\ntemplate<typename T, typename Iter>\ninline bool contains(T& container, const typename T::key_type& key, Iter& it)\n{\n return (it = container.find(key)) != container.end();\n}\n\ntemplate<typename T>\ninline bool contains(const T& container, const typename T::key_type& key,\n typename T::mapped_type& result)\n{\n typename T::const_iterator it;\n return contains(container, key, it) && (result = it->second, true);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T11:53:58.280",
"Id": "216407",
"ParentId": "216174",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "216407",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T15:38:45.703",
"Id": "216174",
"Score": "1",
"Tags": [
"c++",
"collections"
],
"Title": "Wrapper for a standard STL-container"
} | 216174 |
<p>To practice my c++ I decided to implement a simple Kafka producer to wrap the producer in c in librdkafka library. I just want to get your opinion on the way I have implemented teh default, copy and move constructors and make sure what I'm doing is safe.</p>
<ol>
<li>Default constructor:</li>
</ol>
<pre><code>kafka_publisher::kafka_publisher(const std::string &brokers,
const std::string &topic)
{
m_errstr = new char[512];
m_config = rd_kafka_conf_new();
if (rd_kafka_conf_set(m_config,
"bootstrap.servers",
brokers.c_str(),
m_errstr,
sizeof(m_errstr)) != RD_KAFKA_CONF_OK) {
std::string msg = "Failed to initialize Kafka configuration. Caused by ";
throw std::invalid_argument(msg.append(m_errstr));
}
m_publisher = rd_kafka_new(RD_KAFKA_PRODUCER,
m_config,
m_errstr,
sizeof(m_errstr));
if (!m_publisher) {
std::string msg = "Failed to initialize Kafka publisher. Caused by ";
throw std::runtime_error(msg.append(m_errstr));
}
m_topic = rd_kafka_topic_new(m_publisher, topic.c_str(), nullptr);
if (!m_topic) {
std::string msg = "Failed to initialize Kafka topic. Caused by ";
throw std::runtime_error(msg.append(rd_kafka_err2str(rd_kafka_last_error())));
}
}
</code></pre>
<ol start="2">
<li>Copy constructor:</li>
</ol>
<pre><code>kafka_publisher::kafka_publisher(const kafka_publisher &p)
: m_run(p.m_run),
m_config(p.m_config),
m_publisher(p.m_publisher),
m_topic(p.m_topic)
{
strcpy(m_errstr, p.m_errstr);
}
</code></pre>
<ol start="3">
<li>Move constructor:</li>
</ol>
<pre><code>kafka_publisher::kafka_publisher(kafka_publisher &&m)
: m_run(m.m_run),
m_errstr(m.m_errstr),
m_config(m.m_config),
m_publisher(m.m_publisher),
m_topic(m.m_topic)
{
m.m_run = 0;
m.m_errstr = nullptr;
m.m_config = nullptr;
m.m_publisher = nullptr;
m.m_topic = nullptr;
}
</code></pre>
<p>In case if it's helpful, the declaration for this class is:</p>
<pre><code>class kafka_publisher {
public:
kafka_publisher(const std::string &brokers,
const std::string &topic);
kafka_publisher(const kafka_publisher &p);
kafka_publisher(kafka_publisher &&m);
kafka_publisher &operator=(const kafka_publisher &p);
kafka_publisher &operator=(kafka_publisher &&m);
~kafka_publisher();
void publish(std::string &message);
void stop() { m_run = 0; };
private:
int m_run = 1;
char *m_errstr;
rd_kafka_conf_t *m_config;
rd_kafka_t *m_publisher;
rd_kafka_topic_t *m_topic;
};
</code></pre>
<p>Really appreciate your time and effort and helping me improve my c++. Thank you.</p>
| [] | [
{
"body": "<p>It would be more useful (and typical) for CodeReview if you'd post the entire code for the class, starting with the class definition and then the method definitions, rather than starting with one of the methods and then two more and then the class definition.</p>\n\n<p>For example, your declaration for</p>\n\n<pre><code>void publish(std::string &message);\n</code></pre>\n\n<p>looks wrong. If you mean to take <code>message</code> by reference for efficiency, it should be <code>const std::string& message</code>. On the other hand, if it is semantically important that <code>publish</code> is going to <em>modify</em> its argument (an \"out-parameter\"), it would be traditional to pass the argument by pointer, or (better) return it by value.</p>\n\n<pre><code>std::string s;\nkp.publish(s); // confusing — is `s` modified?\nkp.publish(&s); // OK, informs the caller that something wacky is going on\ns = kp.publish(); // best way to return a value\n</code></pre>\n\n<p>However, I strongly suspect from context that what's going on here is actually that <code>publish</code> wants to <em>take ownership of</em> <code>s</code>'s heap-allocated buffer of chars. Ownership transfer is represented in C++ by plain old pass-by-value:</p>\n\n<pre><code>void publish(std::string s);\n\nstd::string s;\nkp.publish(s); // publish a copy of `s`, don't modify the original\nkp.publish(std::move(s)); // publish `s` and let the original be trashed\n</code></pre>\n\n<hr>\n\n<p>The parts of the code you posted don't use <code>m_run</code> at all, so theoretically you could eliminate it.</p>\n\n<p>At least, you should explain why it's an <code>int</code>. We only ever see it assigned the values <code>0</code> and <code>1</code>, which strongly implies to me that <code>m_run</code> ought to be a <code>bool</code>.</p>\n\n<hr>\n\n<p>Without seeing the code of your destructor, we can't tell whether your copy-constructor and move-constructor are doing the right thing or not.</p>\n\n<p>But from what I know about librdkafka, I am reasonably confident that your copy-constructor is incorrect. Your destructor should be calling <code>rd_kafka_topic_destroy</code> to balance out the call to <code>rd_kafka_topic_new</code> in your constructor; so, if I write</p>\n\n<pre><code>kafka_publisher kp1(brokers, topicname);\nkafka_publisher kp2 = kp1;\n// destroy kp2\n// destroy kp1\n</code></pre>\n\n<p>the two destructors will each call <code>rd_kafka_topic_destroy</code>, meaning you'll destroy the topic twice; but you only created it once! So you've got a double-free bug here.</p>\n\n<p>My understanding is that librdkafka objects should be handled by <code>unique_ptr</code> in C++. \"Copying\" a pointer to a librdkafka object (such as a topic) is not generally possible. (Alternatively, you could use <code>shared_ptr</code>; but that seems like overkill.)</p>\n\n<hr>\n\n<pre><code>kafka_publisher(const std::string &brokers,\n const std::string &topic);\n</code></pre>\n\n<p>should be marked <code>explicit</code>.</p>\n\n<hr>\n\n<pre><code>std::string msg = \"Failed to initialize Kafka configuration. Caused by \";\nthrow std::invalid_argument(msg.append(m_errstr));\n</code></pre>\n\n<p>strikes me as unnecessarily confusing. Try to avoid having multiple side-effects on the same line of C++ code. Either add lines until you have one side-effect per line:</p>\n\n<pre><code>std::string msg = \"Failed to initialize Kafka configuration. Caused by \";\nmsg += m_errstr;\nthrow std::invalid_argument(msg);\n</code></pre>\n\n<p>or eliminate side-effects until you have one side-effect per line:</p>\n\n<pre><code>throw std::invalid_argument(\"Failed to initialize Kafka configuration. Caused by \" + m_errstr);\n</code></pre>\n\n<p>I would also caution that <code>rd_kafka_conf_set</code> can probably fail for plenty of reasons that would not be best described as \"invalid argument.\" In production code you'd probably just wrap up the return value in a custom exception type (<code>throw KafkaException(return_code)</code>) and let the higher-level code deal with it if it wanted to.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T18:01:01.830",
"Id": "418304",
"Score": "1",
"body": "When I was looking at the constructor, the `m_errstr = new char[512];` in combination with those `throw`s later on screamed \"Memory leak!\" right into my face. Any thoughts on that? (I personally try to avoid `new` like hell, so I'm not 100% sure)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T18:07:39.700",
"Id": "418309",
"Score": "0",
"body": "@Alex: Yes, definitely, memory leak. I hadn't noticed the `new` at all, during my superficial review. Personally I always forget whether the destructor could fix it up by `delete m_errstr` in this case, and have to go write a test case every time to remind me that [the destructor is not run if the body of a constructor throws](https://wandbox.org/permlink/gtnYuuA7X7FfS5HS). (Destructors of base and member _subobjects_ are run, but the top-level destructor will not have a chance to clean up `m_errstr` in OP's case.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T01:52:12.243",
"Id": "418337",
"Score": "1",
"body": "@Quuxplusone, I can't thank you enough for your time and effort. Pretty much all of your assumptions about the code is right. Rest of the methods I have only sketched and haven't properly implemented yet. I will follow your advice for future reviews. Your line by line explanation specially the semantics are extremely useful. If you come to Singapore, ping me. Beer's on me:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T01:53:10.757",
"Id": "418338",
"Score": "0",
"body": "@Alex Thank you for catching the `m_errstr`, I did feel really uncomfortable with that but I wasn't sure exactly what I was doing wrong. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:43:30.430",
"Id": "418448",
"Score": "0",
"body": "@Alex @Quuxplusone, will there be a similar mem leak with m_config if ctor throws at `rd_kafka_conf_set `? Should I `delete` `m_config` before raising the exception?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:53:53.870",
"Id": "418452",
"Score": "2",
"body": "@swdon: I don't really know librdkafka, but since there seems to be a `rd_kafka_conf_destroy(rd_kafka_conf_t *conf)` it seems reasonable that you have to clean it up yourself. You will have to check back with the doc/examples or ask a question at Stack Overflow."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T17:47:48.010",
"Id": "216184",
"ParentId": "216178",
"Score": "6"
}
},
{
"body": "<p>I have already discussed this in a comment below <a href=\"https://codereview.stackexchange.com/a/216184/92478\">Quuxplusone's answer</a>, but I thought I would make this up into an supplementary answer.</p>\n\n<p>The constructor will leak <code>m_errstr = new char[512];</code> if one of the exceptions is ever thrown. C++ only <a href=\"https://isocpp.org/wiki/faq/exceptions#ctors-can-throw\" rel=\"nofollow noreferrer\">guarantees</a> that the memory which was allocated for the object itself will be freed on exception. However, this will not cover memory allocated in the construction process itself. As was already mentioned, the destructor is not run if the body of the constructor throws. You can read about it on the <a href=\"https://isocpp.org/wiki/faq/exceptions#selfcleaning-members\" rel=\"nofollow noreferrer\">ISO C++ FAQ</a> or try it yourself using the <a href=\"https://wandbox.org/permlink/gtnYuuA7X7FfS5HS\" rel=\"nofollow noreferrer\">example</a> of Quuxplusone.</p>\n\n<p>I also want to point out an observation on the copy constructor. You're using <code>strcpy</code> to transfer the error message to the copied object there. According to the <a href=\"https://en.cppreference.com/w/cpp/string/byte/strcpy\" rel=\"nofollow noreferrer\">documentation</a>, using <code>strcpy</code> with an <code>dest</code> parameter not large enough to hold the value to copy will result in <strong>undefined behavior</strong>. Since there is no pre-allocation of <code>m_errstr</code> there, bad bad things may happen to you (up to and including <a href=\"https://devblogs.microsoft.com/oldnewthing/?p=633\" rel=\"nofollow noreferrer\">time travel</a>).</p>\n\n<p>Fortunately the documentation also has an example how to fix this issue (code theirs):</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <cstring>\n#include <memory>\n\nint main()\n{\n const char* src = \"Take the test.\";\n// src[0] = 'M'; // can't modify string literal\n auto dst = std::make_unique<char[]>(std::strlen(src)+1); // +1 for the null terminator\n std::strcpy(dst.get(), src);\n dst[0] = 'M';\n std::cout << src << '\\n' << dst.get() << '\\n';\n}\n</code></pre>\n\n<p>As a bonus it shows how to use a smart pointer with char arrays, which can be a reasonable solution to the memory leak problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T09:33:38.217",
"Id": "418371",
"Score": "0",
"body": "Thanks so much Alex, for your help. Special thanks for making the extra effort to link the external sources. Would buy you that beer too :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:10:44.243",
"Id": "418481",
"Score": "1",
"body": "It seems kind of insane that cppreference's example would use `make_unique<char[]>` instead of, you know, `std::string`. For OP's purposes, I hope we all agree that `std::string` is the appropriate way to hold string data. `const char *src = \"Take the test.\"; std::string dst = src; dst[0] = 'M'; std::cout << dst << '\\n';` (But since this is a bug in OP's completely-wrong copy ctor, maybe the point is moot. :) )"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T09:16:34.393",
"Id": "216224",
"ParentId": "216178",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "216184",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T16:23:05.817",
"Id": "216178",
"Score": "4",
"Tags": [
"c++",
"constructor"
],
"Title": "Implementing a c++ Kafka producer based on librdkafka"
} | 216178 |
<p>I am making a library which can use different auth mechanisms. I have abstracted the code within an interface:</p>
<pre><code>interface Authenticable
{
public function getName(): string;
/**
* Based on auth type, return the right format of credentials to be sent to the server
*
* @param Authenticable $credentials
* @return mixed
*/
public function encodedCredentials(): string;
}
</code></pre>
<p>One of the possible methods to use this is <code>Plain.php</code>:</p>
<pre><code>class Plain implements Authenticable
{
protected $name = 'PLAIN';
protected $options;
public function __construct(Options $options)
{
$this->options = $options;
}
public function encodedCredentials(): string
{
$credentials = "\x00{$this->options->getUsername()}\x00{$this->options->getPassword()}";
return XML::quote(base64_encode($credentials));
}
public function getName(): string
{
return $this->name;
}
}
</code></pre>
<p>And when initializing auth methods I am using this part of code</p>
<pre><code>public function getAuthType()
{
if (!$this->authType)
$this->authType = new Plain($this->options);
return $this->authType;
}
</code></pre>
<p>which is initializing <code>Plain</code> if no other method was previously given. </p>
<p>What I am wondering here is: should I forward <code>$username</code> and <code>$password</code> to <code>Plain</code> so that I could decouple it from <code>Options</code> class (since those are the only two fields needed in the class)? </p>
<p>On the other hand, that is what <code>Options</code> class is all about. Besides username and pass, it also holds host, port, logger and resource setters and getters, and few helper methods</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T19:16:26.810",
"Id": "418606",
"Score": "1",
"body": "There is an argument to be made for both. For me, it really depends if your `Options` will always be easily accessible or not. Otherwise it looks good. The only thing I would add is there may be room for an Abstract class ( probably keep the interface too ). For things like `public function getName()` etc. Which may need to be duplicated in all children etc... It never hurts to have an interface even it you have an Abstract class, sometimes you can do away with it, if you know you won't need to extend something other then your base class etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T08:31:05.727",
"Id": "418651",
"Score": "0",
"body": "The Abstract class solution sounds great! I have implemented it and removed both the constructor and getter from implementing classes. Much cleaner"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-18T22:02:58.990",
"Id": "430857",
"Score": "0",
"body": "@ArtisticPhoenix Please add an answer instead of a comment. Refer to the section **When _shouldn't_ I comment?** on [Comment everywhere](https://codereview.stackexchange.com/help/privileges/comment)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T06:02:28.757",
"Id": "430879",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ - I was thinking it was to opinion based but, I suppose \"code review\" is a bit more flexible with that than SO. As I said I can see an argument for either one."
}
] | [
{
"body": "<p>I would lay it out something like this:</p>\n\n<pre><code>interface AuthenticableInterface\n{\n public function getName(): string;\n\n /**\n * Based on auth type, return the right format of credentials to be sent to the server\n *\n * @param Authenticable $credentials\n * @return mixed\n */\n public function encodedCredentials(): string;\n}\n\nclass AbstractAuthenticable implements AuthenticableInterface\n{\n protected $name = 'PLAIN';\n protected $options;\n\n public function __construct(Options $options)\n {\n $this->options = $options;\n }\n\n abstract public function encodedCredentials(): string;\n\n public function getName(): string\n {\n return $this->name;\n }\n}\n\nclass Plain extends AbstractAuthenticable{\n\n public function encodedCredentials(): string\n {\n $credentials = \"\\x00{$this->options->getUsername()}\\x00{$this->options->getPassword()}\";\n return XML::quote(base64_encode($credentials));\n }\n\n}\n</code></pre>\n\n<p>I kept the interface, a lot of people get confused between using abstract and interface. I should add that the interface is inherited through the extending of the abstract class, so there is no need to declare (implement) it again.</p>\n\n<p>Interfaces basically just outline the classes API (application program interface, or I like to say public interface), Abstract classes do the same thing (basically) as an interface but you can have concrete implementation of common functionality within the class. Interface doesn't allow you to implement any functionality.</p>\n\n<p>By keeping the interface you could in theory create a Authenticable that uses a base other then the Abstract class. This is useful especially when type casting.</p>\n\n<pre><code>class foo{\n public function __construct(AuthenticableInterface $Authenticable){\n //...\n }\n}\n</code></pre>\n\n<p>So instead of hinting the Abstract class or the Concrete class you can type hint the interface which can be satisfied even when using a completely different base class. In this case it may not be strictly necessary to carry the interface but it does give you that little bit of extra flexibility for the hierarchy. </p>\n\n<p>A good example of the above would be to make a token based login for something like REST where you don't have a username and password, and so that class could be quite different then the base class that uses a user and a password.</p>\n\n<p>Another example I can think of is if you have a hierarchy in your user system, such as a Parent and Subusers, or Admins and non-admins. You may want something like a passwordless Login As functionality that relies more on the user's role and relationship to decide if it should authenticate. Something like a button you just click to login as one of your associated subusers etc. We use subusers a lot in our user systems.</p>\n\n<p>Rather or not you should decouple the username and password depends really on how you want to pass that data. Obviously username and password are going to be really important so it may be worth adding them as function arguments. But as I mentioned above you may create authentication that does not use a username and password. </p>\n\n<p>I would say the biggest argument for it is, then the password and username is not \"hidden\" or buried in some kind of BLOB or array data. But on the same token (pun intended) you may have some classes that don't need them. So the biggest disadvantage is then requiring it as part of the class, which may break the single interface design.</p>\n\n<p>For example consider this interface and class:</p>\n\n<pre><code>interface Authenticable\n{\n public function setPassword(string $password);\n}\n\nclass LoginAs\n{\n //public function setPassword(string $password);\n}\n</code></pre>\n\n<p>So you can see setting a password for \"LoginAs\" doesn't really make sense and this would stretch what we can do with our interface. By having them as options they are not exposed to the interface because they are wrapped in another object.</p>\n\n<p>I'll end by saying if you keep them in the options you will want to do some more robust error checking such as this:</p>\n\n<pre><code>public function encodedCredentials(): string\n{\n $credentials = \"\\x00{$this->options->getUsername()}\\x00{$this->options->getPassword()}\";\n return XML::quote(base64_encode($credentials));\n}\n</code></pre>\n\n<p>I modified your <code>getUsername</code> function in <code>Options</code>. I like to set them up this way.</p>\n\n<pre><code>class options{\n\n public function getUsername($default=null){\n if(isset($this->username)) return $this->username;\n\n if(!is_null($default)) return $default;\n\n throw new OptionException(\"Option {$username} is not set\");\n } \n}\n</code></pre>\n\n<p>By doing this we can control what we get back when its not set. By setting a default other than null, when default is not set we throw an error. Typically I do this using the magic <code>__call</code> method etc.. Basically I showed this to show how you can implement some error checking on those values. Obviously you could check this in each <code>encodedCredentials()</code> but you can also bake it into the options class so it happens when we try to get an options etc...</p>\n\n<p>Hope that helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T05:52:50.073",
"Id": "222564",
"ParentId": "216183",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T17:39:51.727",
"Id": "216183",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"authentication",
"library"
],
"Title": "PHP library that can use different authentication mechanisms"
} | 216183 |
<p>I am interested in learning how I can improve the speed of the code in this pygame file. I iterate over 6400 * 1800 * 3 or 34,560,000 elements of various numpy arrays here to apply noise values to them. The noise library I'm using can be found on GitHub <a href="https://github.com/caseman/noise" rel="nofollow noreferrer">here</a>.</p>
<p>I am calling static variables from a class called <code>ST</code> here. <code>ST.MAP_WIDTH</code> = 6400 and <code>ST.MAP_HEIGHT</code> = 1800. All other <code>ST</code> attributes called here are assigned in the code. They are the noise-maps I'm making.</p>
<pre><code>from __future__ import division
from singleton import ST
import numpy as np
import noise
import timeit
import random
import math
def __noise(noise_x, noise_y, octaves=1, persistence=0.5, lacunarity=2.0):
"""
Generates and returns a noise value.
:param noise_x: The noise value of x
:param noise_y: The noise value of y
:return: numpy.float32
"""
value = noise.pnoise2(noise_x, noise_y,
octaves, persistence, lacunarity,
random.randint(1, 9999))
return np.float32(value)
def __elevation_mapper(noise_x, noise_y):
"""
Finds and returns the elevation noise for the given noise_x and
noise_y parameters.
:param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer
:param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer
:return: float
"""
return __noise(noise_x, noise_y, 8, 0.9)
def __climate_mapper(y, noise_x, noise_y):
"""
Finds and returns the climate noise for the given noise_x and
noise_y parameters.
:param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer
:param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer
:return: float
"""
# find distance from bottom of map and normalize to range [0, 1]
distance = math.sqrt((y - (ST.MAP_HEIGHT >> 1))**2) / ST.MAP_HEIGHT
value = __noise(noise_x, noise_y, 8, 0.7)
return (1 + value - distance) / 2
def __rainfall_mapper(noise_x, noise_y):
"""
Finds and returns the rainfall noise for the given noise_x and
noise_y parameters.
:param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer
:param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer
:return: float
"""
return __noise(noise_x, noise_y, 4, 0.65, 2.5)
def create_map_arr():
"""
This function creates the elevation, climate, and rainfall noise maps,
normalizes them to the range [0, 1], and then assigns them to their
appropriate attributes in the singleton ST.
"""
start = timeit.default_timer()
elevation_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)
climate_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)
rainfall_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)
randomizer = random.uniform(0.0001, 0.9999)
# assign noise map values
for y in range(ST.MAP_HEIGHT):
for x in range(ST.MAP_WIDTH):
noise_x = x / ST.MAP_WIDTH - randomizer
noise_y = y / ST.MAP_HEIGHT - randomizer
elevation_arr[y][x] = __elevation_mapper(noise_x, noise_y)
climate_arr[y][x] = __climate_mapper(y, noise_x, noise_y)
rainfall_arr[y][x] = __rainfall_mapper(noise_x, noise_y)
# normalize to range [0, 1] and assign to relevant ST attributes
ST.ELEVATIONS = (elevation_arr - elevation_arr.min()) / \
(elevation_arr.max() - elevation_arr.min())
ST.CLIMATES = (climate_arr - climate_arr.min()) / \
(climate_arr.max() - climate_arr.min())
ST.RAINFALLS = (rainfall_arr - rainfall_arr.min()) / \
(rainfall_arr.max() - rainfall_arr.min())
stop = timeit.default_timer()
print("GENERATION TIME: " + str(stop - start))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T21:58:28.567",
"Id": "418327",
"Score": "1",
"body": "Have a look at [`numpy.meshgrid`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html#numpy.meshgrid) and its examples. I think they'll do what you need."
}
] | [
{
"body": "<h1>Losing your Loops</h1>\n\n<p>Austin Hastings' comment gives you a good hint where to look at. The main takeaway for you should be:</p>\n\n<p><strong>(Most) loops are damn slow in Python. Especially multiple nested loops.</strong></p>\n\n<p>NumPy can help to <em>vectorize</em> your code, i.e. in this case that more of the looping is done in the C backend instead of in the Python interpreter. I would highly recommend to have a listen to the talk <a href=\"https://www.youtube.com/watch?v=EEUXKG97YRw\" rel=\"nofollow noreferrer\">Losing your Loops: Fast Numerical Computing with NumPy</a> by Jake VanderPlas. Although primarily tailored towards data science, it gives a good overview on the topic.</p>\n\n<p>I did some slight modifications to your original script to include some of the vectorization ideas while still using your chosen Perlin noise library. (Sidenote: I changed the <code>__</code> prefix to a single <code>_</code>, because that is the convention most Python programmers use for <em>internal</em> functions. See <a href=\"https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables\" rel=\"nofollow noreferrer\">PEP8 style guide</a>.)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># -*- coding: utf-8 -*-\nfrom __future__ import division, print_function\nimport numpy as np\nimport noise\nimport timeit\n\n\nclass ST(object):\n MAP_HEIGHT = 1800\n MAP_WIDTH = 6400\n\n\ndef _noise(noise_x, noise_y, octaves=1, persistence=0.5, lacunarity=2.0):\n \"\"\"\n Generates and returns a noise value.\n\n :param noise_x: The noise value of x\n :param noise_y: The noise value of y\n :return: numpy.float32\n \"\"\"\n if isinstance(noise_x, np.ndarray):\n #rand_seed = np.random.randint(1, 9999, noise_x.size)\n rand_seed = np.ones((noise_x.size, )) # just for comparison\n value = np.array([noise.pnoise2(x, y, octaves, persistence, lacunarity, r)\n for x, y, r in zip(noise_x.flat, noise_y.flat, rand_seed)])\n return value.reshape(noise_x.shape)\n else:\n value = noise.pnoise2(noise_x, noise_y,\n octaves, persistence, lacunarity,\n 1.0) # just for comparison\n #np.random.randint(1, 9999))\n return np.float32(value)\n\n\ndef _elevation_mapper(noise_x, noise_y):\n \"\"\"\n Finds and returns the elevation noise for the given noise_x and\n noise_y parameters.\n\n :param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer\n :param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer\n :return: float\n \"\"\"\n return _noise(noise_x, noise_y, 8, 0.9)\n\n\ndef _climate_mapper(y, noise_x, noise_y):\n \"\"\"\n Finds and returns the climate noise for the given noise_x and\n noise_y parameters.\n\n :param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer\n :param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer\n :return: float\n \"\"\"\n # find distance from bottom of map and normalize to range [0, 1]\n distance = np.sqrt((y - (ST.MAP_HEIGHT >> 1))**2) / ST.MAP_HEIGHT\n\n value = _noise(noise_x, noise_y, 8, 0.7)\n\n return (1.0 + value - distance) / 2.0\n\n\ndef _rainfall_mapper(noise_x, noise_y):\n \"\"\"\n Finds and returns the rainfall noise for the given noise_x and\n noise_y parameters.\n\n :param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer\n :param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer\n :return: float\n \"\"\"\n return _noise(noise_x, noise_y, 4, 0.65, 2.5)\n\n\ndef create_map_arr():\n \"\"\"\n This function creates the elevation, climate, and rainfall noise maps,\n normalizes them to the range [0, 1], and then assigns them to their\n appropriate attributes in the singleton ST.\n \"\"\"\n # assign noise map values\n randomizer = np.random.uniform(0.0001, 0.9999)\n\n start_arr = timeit.default_timer()\n\n X, Y = np.mgrid[0:ST.MAP_WIDTH, 0:ST.MAP_HEIGHT]\n noise_x = X / ST.MAP_WIDTH - randomizer\n noise_y = Y / ST.MAP_HEIGHT - randomizer\n elevation_arr_np = _elevation_mapper(noise_x, noise_y)\n climate_arr_np = _climate_mapper(Y, noise_x, noise_y)\n rainfall_arr_np = _rainfall_mapper(noise_x, noise_y)\n\n duration_arr = timeit.default_timer() - start_arr\n\n start_loop = timeit.default_timer()\n\n elevation_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)\n climate_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)\n rainfall_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)\n for y in range(ST.MAP_HEIGHT):\n for x in range(ST.MAP_WIDTH):\n noise_x = x / ST.MAP_WIDTH - randomizer\n noise_y = y / ST.MAP_HEIGHT - randomizer\n\n elevation_arr[y, x] = _elevation_mapper(noise_x, noise_y)\n climate_arr[y, x] = _climate_mapper(y, noise_x, noise_y)\n rainfall_arr[y, x] = _rainfall_mapper(noise_x, noise_y)\n\n duration_loop = timeit.default_timer() - start_loop\n\n print(np.allclose(elevation_arr, elevation_arr_np.T))\n print(np.allclose(climate_arr, climate_arr_np.T))\n print(np.allclose(rainfall_arr, rainfall_arr_np.T))\n\n print(\"GENERATION TIME: loop: {:.6f}, array: {:.6f}\".format(duration_loop, duration_arr))\n\nif __name__ == \"__main__\":\n create_map_arr()\n</code></pre>\n\n<p>The bottleneck is still in</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>value = np.array([noise.pnoise2(x, y, octaves, persistence, lacunarity, r)\n for x, y, r in zip(noise_x.flat, noise_y.flat, rand_seed)])\n</code></pre>\n\n<p>and it would be highly favorable to use an implementation which supports 2D input, preferably from NumPy, directly (see further reading below).</p>\n\n<p>Nevertheless, the modifications bring the execution time down to a third of the original time on my machine (which is not that powerful):</p>\n\n<pre><code>True\nTrue\nTrue\nGENERATION TIME: loop: 338.094228, array: 101.549388\n</code></pre>\n\n<p>Those three <code>True</code>s are from a little test I added to check if the generated maps are the same within reasonable accuracy. For this purpose the additional random value in <code>_noise</code> was disabled.</p>\n\n<h1>Further reading</h1>\n\n<p>There have also already been similar questions on Code Review (see, e.g. <a href=\"https://codereview.stackexchange.com/a/182996\">here</a>), where a reviewer created a Perlin noise implementation purely in Numpy. There also seems to be a <a href=\"https://github.com/pvigier/perlin-numpy\" rel=\"nofollow noreferrer\">GitHub project</a> also doing Perlin noise with Numpy. So maybe have a look at them if your not forced to stick with <code>noise</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T23:54:56.570",
"Id": "418334",
"Score": "0",
"body": "Thank you! I will take a look at the other ways to generate Perlin Noise. I was only using that library because it was the fastest I'd found so far."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T22:58:49.483",
"Id": "216197",
"ParentId": "216186",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "216197",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T18:44:31.460",
"Id": "216186",
"Score": "5",
"Tags": [
"python",
"performance",
"python-2.x",
"numpy"
],
"Title": "Improving the speed of creation for three Perlin Noise Maps in Python?"
} | 216186 |
<p>I've created code in JavaScript for a form validation in a variety of different ways, including if the field is empty, if it contains special characters, if it has numbers/letters when it shouldn't have, and if it exceeds a certain limit. There's also some special cases when the field asks for a year/price. My code does exactly what I want already and everything works as intended, however, I am wondering if there is any way to shorten it, as I feel like I have basically hardcoded the functions for each field, and there is probably a better way of doing it, which would shorten my code quite a bit.</p>
<p>The JavaScript is here:</p>
<pre><code>var numbers = /^[0-9]+$/;
var letters = /^[A-Za-z]+$/;
var specialChars = /[^a-zA-Z ]/g;
var special = /^\d{1,3}$/;
var price = /^-?(\d{1,3})(\.\d{1,2})*?$/;
var year = /^\d{1,4}$/;
function ValidateMovSearch() {
const value = document.movSearch.mvTitle.value;
const focusvalue = document.movSearch.mvTitle;
if (value.match(numbers)) {
alert ("Please only use letters!")
focusvalue.focus();
return false;
}
if (value == "") {
alert ("Please do not leave this blank!")
focusvalue.focus();
return false;
}
if (value.length > 50) {
alert ("Maximum of 50 characters allowed!")
focusvalue.focus();
return false;
}
if (value.match(specialChars)) {
alert ("Only characters A-Z, a-z are allowed!")
focusvalue.focus();
return false;
}
return (true);
}
function ValidateMovInsert() {
if (document.movInsert.actID.value.match(letters)) {
alert ("Please only use numbers!")
document.movInsert.actID.focus();
return false;
}
if (document.movInsert.actID.value == "") {
alert ("Please do not leave this blank!")
document.movInsert.actID.focus();
return false;
}
if (document.movInsert.actID.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movInsert.actID.focus();
return false;
}
if (!(document.movInsert.actID.value.match(special))) {
alert ("Only characters 0-9 are allowed!")
document.movInsert.actID.focus();
return false;
}
if (document.movInsert.mvTitle.value.match(numbers)) {
alert ("Please only use letters!")
document.movInsert.mvTitle.focus();
return false;
}
if (document.movInsert.mvTitle.value == "") {
alert ("Please do not leave this blank!")
document.movInsert.mvTitle.focus();
return false;
}
if (document.movInsert.mvTitle.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movInsert.mvTitle.focus();
return false;
}
if (document.movInsert.mvTitle.value.match(specialChars)) {
alert ("Only characters A-Z, a-z are allowed!")
document.movInsert.mvTitle.focus();
return false;
}
if (document.movInsert.mvPrice.value.match(letters)) {
alert ("Please only use numbers!")
document.movInsert.mvPrice.focus();
return false;
}
if (document.movInsert.mvPrice.value == "") {
alert ("Please do not leave this blank!")
document.movInsert.mvPrice.focus();
return false;
}
if (document.movInsert.mvPrice.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movInsert.mvPrice.focus();
return false;
}
if (!(document.movInsert.mvPrice.value.match(price))) {
alert ("Only characters 0-9 and . are allowed!")
document.movInsert.mvPrice.focus();
return false;
}
if (document.movInsert.mvYear.value.match(letters)) {
alert ("Please only use numbers!")
document.movInsert.mvYear.focus();
return false;
}
if (document.movInsert.mvYear.value == "") {
alert ("Please do not leave this blank!")
document.movInsert.mvYear.focus();
return false;
}
if (document.movInsert.mvYear.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movInsert.mvYear.focus();
return false;
}
if (!(document.movInsert.mvYear.value.match(year))) {
alert ("Only characters 0-9 are allowed!")
document.movInsert.mvYear.focus();
return false;
}
if (document.movInsert.mvGenre.value.match(numbers)) {
alert ("Please only use numbers!")
document.movInsert.mvGenre.focus();
return false;
}
if (document.movInsert.mvGenre.value == "") {
alert ("Please do not leave this blank!")
document.movInsert.mvGenre.focus();
return false;
}
if (document.movInsert.mvGenre.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movInsert.mvGenre.focus();
return false;
}
if (document.movInsert.mvGenre.value.match(specialChars)) {
alert ("Only characters A-Z, a-z are allowed!")
document.movInsert.mvGenre.focus();
return false;
}
return (true);
}
function ValidateMovDelete() {
if (document.movDelete.mvTitle.value.match(letters)) {
alert ("Please only use numbers!")
document.movDelete.mvTitle.focus();
return false;
}
if (document.movDelete.mvTitle.value == "") {
alert ("Please do not leave this blank!")
document.movDelete.mvTitle.focus();
return false;
}
if (document.movDelete.mvTitle.value.length > 50) {
alert ("Maximum of 50 characters allowed!")
document.movDelete.mvTitle.focus();
return false;
}
if (!(document.movDelete.mvTitle.value.match(special))) {
alert ("Only characters A-Z, a-z are allowed!")
document.movDelete.mvTitle.focus();
return false;
}
return (true);
}
</code></pre>
<p>And my HTML form is here:</p>
<pre><code><form name = "movInsert" align = "center" action="movieInserting.php"
onSubmit = "return ValidateMovInsert()">
Actor ID:<br>
<input type = "text" name = "actID"
<br><br>
Movie Title:<br>
<input type = "text" name = "mvTitle"
<br><br>
Movie Price:<br>
<input type = "text" name = "mvPrice"
<br><br>
Movie Year:<br>
<input type = "text" name = "mvYear"
<br><br>
Movie Genre:<br>
<input type = "text" name = "mvGenre"
<br><br>
<input type = "submit" value = "Insert">
</form>
</code></pre>
| [] | [
{
"body": "<p>The technique you are looking for is a <a href=\"https://en.wikipedia.org/wiki/Dispatch_table#JavaScript_implementation\" rel=\"nofollow noreferrer\">dispatch table</a>. You're only dispatching regular expressions, so the table doesn't need to have functions in it at all.</p>\n\n<p>Collect the validating regexes and their corresponding error messages into a data structure. Use HTML classes on the input fields to select which checks apply to each field.</p>\n\n<p>Include the field name (or some other descriptive property) in the error message.</p>\n\n<p>Attach the <code>onsubmit</code> handler in your code, not in the HTML, so that the page still works even if the JavaScript doesn't get loaded.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const validations = {\n number: [ /^\\d*$/, \"Please only use numbers!\" ],\n some: [ /./, \"Please do not leave this blank!\" ],\n words: [ /^[a-zA-Z ]*$/, \"Please only use letters and spaces!\" ],\n concise: [ /^.{0.50}$/, \"Maximum of 50 characters allowed!\" ],\n price: [ /^[+-]?\\d{1,3}\\.?\\d{0,2}$/, \"Only 0-9 and . are allowed!\" ],\n year: [ /^\\d{1,4}$/, \"Please enter a valid year!\" ]\n}\n\nfunction ValidateMovSearch(submitted) {\n var valid=true;\n const fields=Array.from( submitted.target.querySelectorAll(\"input\") ); \n \n fields.forEach( field => {\n const checks=Array.from( field.classList )\n .filter( checkname => validations.hasOwnProperty(checkname) ) \n .map( checkname => validations[checkname] );\n \n field.value=field.value.trim(); \n\n checks.forEach( check => {\n const regex=check[0], \n message=check[1];\n // check if valid-so-far, to limit number of alerts\n if (valid && !regex.test( field.value )) { \n alert(field.name + \": \" + message); \n field.focus();\n valid=false; \n }\n });\n });\n return valid;\n}\ndocument.movInsert.onsubmit=ValidateMovSearch;</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form name=\"movInsert\">\n Actor ID:<br> <input type=\"text\" name=\"Actor ID\" class=\"some number\">\n<br>Movie Title:<br> <input type=\"text\" name=\"Movie Title\" class=\"some concise words\">\n<br>Movie Price:<br> <input type=\"text\" name=\"Movie Price\" class=\"some price\">\n<br>Movie Year:<br> <input type=\"text\" name=\"Movie Year\" class=\"some year\">\n<br>Movie Genre:<br> <input type=\"text\" name=\"Movie Genre\" class=\"some concise words\">\n<br><input type = \"submit\" value = \"Insert\">\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T04:01:04.253",
"Id": "216208",
"ParentId": "216190",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T21:21:59.417",
"Id": "216190",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Form validation in a variety of different ways depending on the field input"
} | 216190 |
<p>I created a math quiz/game called "Factions". In the game, there are 2 teams. Red team and Blue team. They take turns answering questions relating to fractions. If they get it correct, they gain points equal to the round number * 100. If not, then they lose points equal to the round number * 100. Each team starts off with 100 points. When a team's points reaches 0, they lose the game. Here is the code for the game.</p>
<pre><code>from tkinter import *
import random
import time
class Game(object):
def __init__(self):
global root
self.round = 1
self.operators = ["+", "+", "+", "+", "-", "-", "-", "*", "*", "/"]
self.operator = ""
# Scores and team labels
self.blue_team_label = Label(root, text="BLUE TEAM", bg="blue")
self.blue_team_label.config(font=("Courier", 50))
self.blue_team_label.grid(row=0, column=0, columnspan=10)
self.red_team_label = Label(root, text="RED TEAM", bg="red")
self.red_team_label.config(font=("Courier", 50))
self.red_team_label.grid(row=0, column=23, columnspan=10)
self.blue_team_points = 1000
self.blue_team_points_label = Label(root, text="Points: " + str(self.blue_team_points))
self.blue_team_points_label.config(font=("Courier", 30))
self.blue_team_points_label.grid(row=5, column=0, columnspan=10)
self.red_team_points = 1000
self.red_team_points_label = Label(root, text="Points: " + str(self.red_team_points))
self.red_team_points_label.config(font=("Courier", 30))
self.red_team_points_label.grid(row=5, column=23, columnspan=10)
self.question = "(self.first_numerator / self.first_denominator) " + self.operator + \
"(self.second_numerator / self.second_denominator) "
self.turn = "BLUE TURN"
self.round_label = Label(root, text="ROUND " + str(self.round))
self.round_label.config(font=("courier", 20))
self.round_label.grid(row=26, column=23, columnspan=10)
# Questions
self.generate_question()
def generate_question(self):
"""
Generate the questions for the game.
"""
self.first_numerator = random.randint(1, 5 * self.round)
self.operator = random.choice(self.operators)
self.second_numerator = random.randint(1, 5 * self.round)
self.first_denominator = random.randint(1, 5 * self.round)
self.second_denominator = random.randint(1, 5 * self.round)
self.row_1_question = Label(root, text=str(self.first_numerator) + " " + " " + " " + str(self.second_numerator))
self.row_2_question = Label(root, text=" " + "/" + " " + self.operator + " " + "/" + " = ")
self.row_3_question = Label(root, text="{0} {1}".format(str(self.first_denominator),
str(self.second_denominator)))
self.row_1_question.grid(row=25, column=10, columnspan=5)
self.row_2_question.grid(row=26, column=10, columnspan=5)
self.row_3_question.grid(row=27, column=10, columnspan=5)
self.row_1_question.config(font=("courier", 12))
self.row_2_question.config(font=("courier", 12))
self.row_3_question.config(font=("courier", 12))
self.question = "(self.first_numerator / self.first_denominator) " + self.operator + "(self.second_numerator " \
"/ self.second_denominator) "
self.question_entry_box = Entry(root)
self.question_entry_box.grid(row=26, pady=12, column=16, columnspan=3)
self.question_check_button = Button(root, text="ENTER", command=self.check_answer)
self.question_check_button.grid(row=26, column=20)
self.turn_label = Label(root, text=self.turn)
self.turn_label.config(font=("courier", 20))
self.turn_label.grid(row=26, column=0, columnspan=9)
def check_answer(self):
self.answer = eval(self.question)
self.attempted_answer = self.question_entry_box.get()
if self.turn == "BLUE TURN":
if self.answer == float(self.attempted_answer):
self.blue_team_points += self.round * 100
else:
self.blue_team_points -= self.round * 100
else:
if self.answer == float(self.attempted_answer):
self.red_team_points += self.round * 100
else:
self.red_team_points -= self.round * 100
self.update()
def update(self):
self.blue_team_label = Label(root, text="BLUE TEAM", bg="blue")
self.blue_team_label.config(font=("Courier", 50))
self.blue_team_label.grid(row=0, column=0, columnspan=10)
self.red_team_label = Label(root, text="RED TEAM", bg="red")
self.red_team_label.config(font=("Courier", 50))
self.red_team_label.grid(row=0, column=23, columnspan=10)
self.blue_team_points_label = Label(root, text="Points: " + str(self.blue_team_points))
self.blue_team_points_label.config(font=("Courier", 30))
self.blue_team_points_label.grid(row=5, column=0, columnspan=10)
self.red_team_points_label = Label(root, text="Points: " + str(self.red_team_points))
self.red_team_points_label.config(font=("Courier", 30))
self.red_team_points_label.grid(row=5, column=23, columnspan=10)
if self.turn == "BLUE TURN":
self.turn = "RED TURN"
else:
self.turn = "BLUE TURN"
self.round += 1
if self.blue_team_points < 1:
game_over_label = Label(root, text="BLUE TEAM LOSES")
game_over_label.config(font=("courier", 20))
game_over_label.grid(row=50, column=0, columnspan=10)
time.sleep(3)
sys.exit()
if self.red_team_points < 1:
game_over_label = Label(root, text="RED TEAM LOSES")
game_over_label.config(font=("courier", 20))
game_over_label.grid(row=50, column=0, columnspan=10)
time.sleep(3)
sys.exit()
self.round_label = Label(root, text="ROUND " + str(self.round))
self.round_label.config(font=("courier", 20))
self.round_label.grid(row=26, column=23, columnspan=10)
self.generate_question()
root = Tk()
root.title("Factions")
game = Game()
mainloop()
</code></pre>
<p>This is my first project with tkinter, and one of my first in Python. I want feedback on how to make the game better, and any glitches you find.</p>
| [] | [
{
"body": "<h2>Don't mix presentation and business logic</h2>\n\n<p>Let's take a look at <code>self.turn</code>. You're using it for two purposes - to talk to humans (that's why it's a string), and for the computer to track which turn it is. These concerns should be separated. If there will always be two players, the turn could be represented by a boolean, or maybe as an integer that's the player ID. It should only be converted to a string when you want to display whose turn it is on the screen.</p>\n\n<p>Your entire game is baked into one <code>Game</code> class, but a bunch of separation needs to be done. A great example of a method that should only appear in the business logic layer is <code>generate_question</code>. It shouldn't interact with the UI at all. Solving this issue will dramatically clean up your code, make debugging and maintenance easier, and generally decrease headaches.</p>\n\n<h2>Use modern formatting</h2>\n\n<p>Rather than this:</p>\n\n<pre><code>str(self.first_numerator) + \" \" + \" \" + \" \" + str(self.second_numerator)\n</code></pre>\n\n<p>you can do:</p>\n\n<pre><code>f'{self.first_numerator} {self.second_numerator}'\n</code></pre>\n\n<h2>Be careful about rounding</h2>\n\n<p>This:</p>\n\n<p><code>== float(</code></p>\n\n<p>is a great way to create a nasty bug. Sometimes this will evaluate to false even if the numbers seem like they should match -- they're just infinitesimally different. Either track integers as a member of fractions, or if you really need to compare floats, do so with some small tolerance, i.e.</p>\n\n<pre><code>epsilon = 1e-12\nif abs(self.answer - self.attempted_answer) < epsilon:\n # ...\n</code></pre>\n\n<h2>Create an upper <code>main</code> function</h2>\n\n<p>...to house the code that's currently in global scope.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<p>This:</p>\n\n<pre><code> if self.turn == \"BLUE TURN\":\n if self.answer == float(self.attempted_answer):\n self.blue_team_points += self.round * 100\n else:\n self.blue_team_points -= self.round * 100\n else:\n if self.answer == float(self.attempted_answer):\n self.red_team_points += self.round * 100\n else:\n self.red_team_points -= self.round * 100\n</code></pre>\n\n<p>can be compressed - make a variable to hold the result of your multiplication:</p>\n\n<pre><code>award = self.round * 100\n</code></pre>\n\n<p>And you don't need to repeat the entire block based on turn if you make a <code>Player</code> class with an <code>award</code> method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T02:15:05.003",
"Id": "216203",
"ParentId": "216191",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216203",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T21:33:52.557",
"Id": "216191",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"game",
"tkinter",
"quiz"
],
"Title": "2-team fraction quiz/test in Python 3 with Tkinter"
} | 216191 |
<p>I wrote a program in pygame that basically acts as a physics engine for a ball. You can hit the ball around and your strokes are counted, as well as an extra stroke for going out of bounds. If I do further develop this, I'd make the angle and power display toggleable, but I do like showing them right now:</p>
<pre><code>import pygame as pg
import math
SCREEN_WIDTH = 1500
SCREEN_HEIGHT = 800
WINDOW_COLOR = (100, 100, 100)
BALL_COLOR = (255, 255, 255)
BALL_OUTLINE_COLOR = (255, 0, 0)
LINE_COLOR = (0, 0, 255)
ALINE_COLOR = (0, 0, 0)
START_X = int(.5 * SCREEN_WIDTH)
START_Y = int(.99 * SCREEN_HEIGHT)
POWER_MULTIPLIER = .85
SPEED_MULTIPLIER = 2
BALL_RADIUS = 10
pg.init()
pg.display.set_caption('Golf')
window = pg.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pg.event.set_grab(True)
pg.mouse.set_cursor((8, 8), (0, 0), (0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0))
strokeFont = pg.font.SysFont("monospace", 50)
STROKECOLOR = (255, 255, 0)
powerFont = pg.font.SysFont("arial", 15, bold=True)
POWERCOLOR = (0, 255, 0)
angleFont = pg.font.SysFont("arial", 15, bold=True)
ANGLECOLOR = (0, 255, 0)
penaltyFont = pg.font.SysFont("georgia", 40, bold=True)
PENALTYCOLOR = (255, 0, 0)
class Ball(object):
def __init__(self, x, y, rad, c, oc):
self.x = x
self.y = y
self.radius = rad
self.color = c
self.outlinecolor = oc
def show(self, window):
pg.draw.circle(window, self.outlinecolor, (self.x, self.y), self.radius)
pg.draw.circle(window, self.color, (self.x, self.y), self.radius - int(.4 * self.radius))
@staticmethod
def path(x, y, p, a, t):
vx, vy = p * math.cos(a), p * math.sin(a) #Velocities
dx, dy = vx * t, vy * t - 4.9 * t ** 2 #Distances Traveled
print(' x-pos: %spx' % str(round(dx + x)))
print(' y-pos: %spx' % str(round(abs(dy - y))))
return round(dx + x), round(y - dy)
@staticmethod
def quadrant(x,y,xm,ym):
if ym < y and xm > x:
return 1
elif ym < y and xm < x:
return 2
elif ym > y and xm < x:
return 3
elif ym > y and xm > x:
return 4
else:
return False
def draw_window():
window.fill(WINDOW_COLOR)
ball.show(window)
if not shoot:
arrow(window, ALINE_COLOR, ALINE_COLOR, aline[0], aline[1], 5)
arrow(window, LINE_COLOR, LINE_COLOR, line[0], line[1], 5)
stroke_text = 'Strokes: %s' % strokes
stroke_label = strokeFont.render(stroke_text, 1, STROKECOLOR)
if not strokes:
window.blit(stroke_label, (SCREEN_WIDTH - .21 * SCREEN_WIDTH, SCREEN_HEIGHT - .985 * SCREEN_HEIGHT))
else:
window.blit(stroke_label, (SCREEN_WIDTH - (.21+.02*math.floor(math.log10(strokes))) * SCREEN_WIDTH, SCREEN_HEIGHT - .985 * SCREEN_HEIGHT))
power_text = 'Shot Strength: %sN' % power_display
power_label = powerFont.render(power_text, 1, POWERCOLOR)
if not shoot: window.blit(power_label, (cursor_pos[0] + .008 * SCREEN_WIDTH, cursor_pos[1]))
angle_text = 'Angle: %s°' % angle_display
angle_label = angleFont.render(angle_text, 1, ANGLECOLOR)
if not shoot: window.blit(angle_label, (ball.x - .06 * SCREEN_WIDTH, ball.y - .01 * SCREEN_HEIGHT))
if Penalty:
penalty_text = 'Out of Bounds! +1 Stroke'
penalty_label = penaltyFont.render(penalty_text, 1, PENALTYCOLOR)
penalty_rect = penalty_label.get_rect(center=(SCREEN_WIDTH/2, .225*SCREEN_HEIGHT))
window.blit(penalty_label, penalty_rect)
pg.display.flip()
def angle(cursor_pos):
x, y, xm, ym = ball.x, ball.y, cursor_pos[0], cursor_pos[1]
if x-xm:
angle = math.atan((y - ym) / (x - xm))
elif y > ym:
angle = math.pi/2
else:
angle = 3*math.pi/2
q = ball.quadrant(x,y,xm,ym)
if q: angle = math.pi*math.floor(q/2) - angle
if round(angle*180/math.pi) == 360:
angle = 0
if x > xm and round(angle*180/math.pi) == 0:
angle = math.pi
return angle
def arrow(screen, lcolor, tricolor, start, end, trirad):
pg.draw.line(screen, lcolor, start, end, 2)
rotation = math.degrees(math.atan2(start[1] - end[1], end[0] - start[0])) + 90
pg.draw.polygon(screen, tricolor, ((end[0] + trirad * math.sin(math.radians(rotation)),
end[1] + trirad * math.cos(math.radians(rotation))),
(end[0] + trirad * math.sin(math.radians(rotation - 120)),
end[1] + trirad * math.cos(math.radians(rotation - 120))),
(end[0] + trirad * math.sin(math.radians(rotation + 120)),
end[1] + trirad * math.cos(math.radians(rotation + 120)))))
def distance(x,y):
return math.sqrt(x**2 + y**2)
x, y, time, power, ang, strokes = 0, 0, 0, 0, 0, 0
xb, yb = None, None
shoot, Penalty = False, False
p_ticks = 0
ball = Ball(START_X, START_Y, BALL_RADIUS, BALL_COLOR, BALL_OUTLINE_COLOR)
quit = False
BARRIER = 1
try:
while not quit:
seconds=(pg.time.get_ticks()-p_ticks)/1000
if seconds > 1.2: Penalty = False
cursor_pos = pg.mouse.get_pos()
line = [(ball.x, ball.y), cursor_pos]
line_ball_x, line_ball_y = cursor_pos[0] - ball.x, cursor_pos[1] - ball.y
aline = [(ball.x, ball.y), (ball.x + .015 * SCREEN_WIDTH, ball.y)]
if not shoot:
power_display = round(
distance(line_ball_x, line_ball_y) * POWER_MULTIPLIER / 10)
angle_display = round(angle(cursor_pos) * 180 / math.pi)
if shoot:
if ball.y < SCREEN_HEIGHT:
if BARRIER < ball.x < SCREEN_WIDTH:
time += .3 * SPEED_MULTIPLIER
print('\n time: %ss' % round(time, 2))
po = ball.path(x, y, power, ang, time)
ball.x, ball.y = po[0], po[1]
else:
print('Out of Bounds!')
Penalty = True
p_ticks = pg.time.get_ticks()
strokes += 1
shoot = False
if BARRIER < xb < SCREEN_WIDTH:
ball.x = xb
else:
ball.x = START_X
ball.y = yb
else:
shoot = False
ball.y = START_Y
for event in pg.event.get():
if event.type == pg.QUIT:
quit = True
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
quit = True
if event.type == pg.MOUSEBUTTONDOWN:
if not shoot:
shoot = True
x, y = ball.x, ball.y
xb, yb = ball.x, ball.y
time, power = 0, (
distance(line_ball_x, line_ball_y)) * POWER_MULTIPLIER / 10
print('\n\nBall Hit!')
print('\npower: %sN' % round(power, 2))
ang = angle(cursor_pos)
print('angle: %s°' % round(ang * 180 / math.pi, 2))
print('cos(a): %s' % round(math.cos(ang), 2)), print('sin(a): %s' % round(math.sin(ang), 2))
strokes += 1
draw_window()
print("\nShutting down...")
pg.quit()
except Exception as error:
print(f'A fatal error ({error}) has occurred. The program is shutting down.')
pg.quit()
</code></pre>
<p>Feedback of any kind is very welcome!</p>
| [] | [
{
"body": "<p>Overall it isn't bad.</p>\n\n<h2>Direct imports for common symbols</h2>\n\n<p>Based on your discretion, certain often-used and unambiguous symbols can be imported without their module namespace, i.e.</p>\n\n<pre><code>from pg.font import SysFont\n# ...\nstrokeFont = SysFont(\"monospace\", 50)\n</code></pre>\n\n<h2>snake_case</h2>\n\n<p>i.e. <code>stroke_font</code> for variables and function names. Also, <code>Penalty</code> should be lower-case because it isn't a class.</p>\n\n<h2>debug printing</h2>\n\n<p>This kind of thing:</p>\n\n<pre><code>print(' x-pos: %spx' % str(round(dx + x)))\n</code></pre>\n\n<p>can be improved in a few ways. Firstly, it looks like a debugging output and not actual game content, so typically you won't want to print this at all. That doesn't mean that you have to delete it, though - you can use actual Python logging at level debug to be able to select at the top level whether these statements are printed.</p>\n\n<p>Also: do you really need round? Could you instead go</p>\n\n<pre><code>print(f' x-pos: {dx + x:.0f}px')\n</code></pre>\n\n<h2>f-strings</h2>\n\n<p>As in the previous example, you should consider using the new syntactical sugar of f-strings instead of the <code>%</code> operator.</p>\n\n<h2>Global clutter</h2>\n\n<p>It's tempting in Python to add a bunch of stuff (x, y, time, power, etc.) to the global scope. Don't give in! Put these into a game state object. Break up your global code into multiple subroutines, potentially in methods of the game state object.</p>\n\n<h2>Shadowing</h2>\n\n<p>Don't call something <code>time</code>. <code>time</code> is already a thing in Python.</p>\n\n<h2>Math</h2>\n\n<p>I kind of had to jump through some hoops to take advantage of <code>atan2</code>. I don't recommend doing this, but here's a one-liner alternative to your <code>quadrant</code> function:</p>\n\n<pre><code>return int(4 + 2/pi*atan2(y - ym, xm - x)) % 4 + 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T08:38:10.980",
"Id": "418362",
"Score": "0",
"body": "Note: f-strings only work in Python 3. Using `print(...)` could be seen as indication that the OP works in Python 3, but the tags itself don't show what Python version is actually used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T08:41:07.990",
"Id": "418363",
"Score": "0",
"body": "I'm using python 3. I use f-strings for sentences with many variables but the `%s` formatting is just by habit"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T12:12:29.557",
"Id": "418392",
"Score": "0",
"body": "I would disagree on the \"shadowing\". If we didn't allow to use names that are also standard library modules we wouldn't be able to use these as well: `code`, `warnings`, `cmd`, `email`, `signal`, `queue`, `symbol`. And there is probably a pypi package for every convenient variable name. I understand that `time` is a very well known module, but where do we draw the line? My main point is, that OP doesn't even use the module so they don't shadow anything at all. If they did import that module i would totally agree with you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T12:35:17.013",
"Id": "418396",
"Score": "2",
"body": "An easy place to draw the line is - do what PyCharm does. It has this check built-in. Obviously pip package names are not a problem unless they're in your requirements, but the more common Python library names should be avoided."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T01:52:20.257",
"Id": "216202",
"ParentId": "216199",
"Score": "6"
}
},
{
"body": "<p>Some of this is nit-pickery, some is more fundamental:</p>\n\n<p><strong>Import Order</strong></p>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"noreferrer\">PEP-8</a> suggests an ordering to imports. No reason not to use it:</p>\n\n<blockquote>\n <p>Imports should be grouped in the following order:</p>\n\n<pre><code>Standard library imports.\nRelated third party imports.\nLocal application/library specific imports.\n</code></pre>\n \n <p>You should put a blank line between each group of imports.</p>\n</blockquote>\n\n<p><strong>Code Organization: Constants</strong></p>\n\n<p>You have a bunch of \"constants\" defined. They're all-caps, which is good. They're declared together and at the top of the file, which is good. But they really shouldn't be global constants.</p>\n\n<p>For example, you have a <code>Ball</code> class. Yet there are global constants named <code>BALL_COLOR</code> and <code>BALL_OUTLINE_COLOR</code> and <code>BALL_RADIUS</code>. Why is that? If they're related to your class, make them class constants.</p>\n\n<pre><code>class Ball:\n BODY_COLOR = (255, 255, 255)\n OUTLINE_COLOR = (255, 0, 0)\n RADIUS = 10\n</code></pre>\n\n<p><strong>Code Organization: Types</strong></p>\n\n<p>In the same vein, you make a lot of use of tuples. But you just create them in-line and rely on convention to access them. Why not go ahead and use a <a href=\"https://docs.python.org/3/library/collections.html?highlight=collections%20namedtuple#collections.namedtuple\" rel=\"noreferrer\"><code>collections.namedtuple</code></a> or even two?</p>\n\n<pre><code>import collections\n\nSize = collections.namedtuple('Size', 'width height')\nPosition = collections.namedtuple('Position', 'x y')\n\nWINDOW_SIZE = Size(width=1500, height=800)\nSTART_POS = Position(x=0.5 * WINDOW_SIZE.width, y=0.99 * WINDOW_SIZE.height)\n</code></pre>\n\n<p><strong>Code Organization: Functions</strong></p>\n\n<p>You have a lot of stuff at module scope. Sooner or later you'll want to either write a unit test, or run the debugger, or load your code into the command-line Python REPL. All of this is made easier if you move the module-scope statements into a <code>main</code> function, or some other-named function.</p>\n\n<pre><code>def main():\n pg.init()\n pg.display.set_caption('Golf')\n ... etc ...\n</code></pre>\n\n<p>You have a set of font/color variables that you create at module scope. There aren't currently enough drawing functions to create a <code>Window</code> class or anything, but you might consider putting them into a <code>Config</code> class. (And using <code>snake_case</code> names.)</p>\n\n<p>Also, you have a lot of <code>pygame</code> boilerplate mixed in with your game logic. I'd suggest separating the boilerplate into separate functions, something like:</p>\n\n<pre><code>while still_playing:\n handle_events()\n update()\n render() # You call this \"draw_window()\" which is fine.\n</code></pre>\n\n<p>Most of your logic, of course, will be in <code>update()</code>. In fact, since it mostly has to do with updating the position of the <code>Ball</code> object, it should mostly be in a call to <code>ball.update_position(delay)</code> (or some such name).</p>\n\n<p>You make use of a pair of temporaries <code>x</code> and <code>y</code>, but it seems like you could replace those with an old-position attribute on the <code>Ball</code>, or a second Ball object, or something.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T02:57:02.287",
"Id": "216205",
"ParentId": "216199",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "216205",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T23:22:33.067",
"Id": "216199",
"Score": "8",
"Tags": [
"python",
"pygame",
"physics"
],
"Title": "Golf game boilerplate"
} | 216199 |
<p>Trying to script a simple command line tool for ingesting media to a target location following a structured naming convention. </p>
<p>It's functional in its current state but I'd like to know if there are things to improve. </p>
<pre><code>#!/usr/local/bin/bash
#make target directory for transfer
make_directory(){
echo -e "\n\nFollow the prompt to create a project directory.\n\n"
sleep .5
while [[ -z "$target_directory" ]]
do
echo -e "Path of target directory?"
read target_directory
done
while [[ -z "$brand" ]]
do
echo -e "\nBrand Prefix?"
read brand
done
while [[ -z "$project" ]]
do
echo -e "\nProject Name?"
read project
done
while [[ -z "$media_type" ]]
do
echo -e "\nMedia Type?"
read media_type
done
while [[ -z "$location" ]]
do
echo -e "\nLocation?"
read location
done
while [[ -z "$employee" ]]
do
echo -e "\nEmployee?"
read employee
done
path=${target_directory}/$(date +'%Y%m%d')_${brand}_${project}_${media_type}_${location}_${employee}
echo -e "\nCreating directory: ${path}\n\n"
mkdir -p "${path}"
}
# construct rsync command
construct_rsync(){
echo -e "\n\nFollow the prompt to construct the rsync command.\n\n"
while [[ -z "$source_path" ]]
do
echo -e "Path to source media?"
read source_path
done
if [[ "$option" == "2" ]]; then
while [[ -z "$target_directory" ]]
do
echo -e "Target directory?"
read target_directory
done
path=$target_directory
fi
while true;
do
read -p "Additional rsync options? [y/n] " rsync_add
case $rsync_add in
[Yy]* )
echo -e "\nEnter additional rsync parameters:"
read rsync_options
break;;
[Nn]* )
break;;
*) echo "Please enter y or no!"
esac
done
echo -e "\nConstructing rsync command...\n"
sleep .5
echo -e "Running rsync command:\n
rsync \n
-r \n
--info=progress2 \n
--log-file=${path}/$(date +'%Y%m%d')_transfer_log.txt \n
${rsync_options} \n
${source_path}/ \n
${path} \n"
rsync -r --info=progress2 --log-file="${path}/$(date +'%Y%m%d')_transfer_log.txt" ${rsync_options} "${source_path}/" "${path}"
}
# log exit code of rsync
log(){
echo -e "\nCreating error log..."
echo $? > "${path}/error_log.txt"
sleep .5
if [[ "$?" == "0" ]]; then
echo -e "\nTransfer complete!"
elif [[ "$?" != "0" ]]; then
echo -e "\nError in transfer! Please refer to error_log.txt!"
fi
}
# read user input and run appropriate functions
while true
do
read -p "Enter [1] to start an ingest or [2] to complete a partial ingest. " option
case $option in
1 )
make_directory
sleep .5
construct_rsync
sleep .5
log
break;;
2 )
construct_rsync
sleep .5
log
break;;
* )
echo "Please enter a valid option!";;
esac
done
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T14:59:47.400",
"Id": "418410",
"Score": "0",
"body": "Welcome to Code Review! I rolled back your last 2 edits. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:09:40.970",
"Id": "418414",
"Score": "1",
"body": "Thanks! I wasn't familiar with proper etiquette."
}
] | [
{
"body": "<p>Your code is pretty clear and readable. Congratulations!</p>\n\n<p>Here are some suggestions:</p>\n\n<ol>\n<li><p>Stop using <code>sleep</code>! Unless this is for a Hollywood hacker movie, it just slows things down. Nobody thinks delays are cool after the first three times you run something.</p></li>\n<li><p>Take command-line arguments instead of prompting for everything. It's a lot easier to just put stuff into a command line than it is to respond to it at the keyboard. Something like:</p>\n\n<pre><code>ingest -t $HOME/media -b SONY -p \"My Project\" \n</code></pre>\n\n<p>There are plenty of <a href=\"https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash#13359121\">SO answers</a> on how to do this.</p></li>\n<li><p>Add some more functions! Anything you find yourself doing twice should be a function. Also, anything that you have to \"break the flow\" in order to do should be a function. Here are some examples:</p>\n\n<pre><code>while [[ -z \"$target_directory\" ]]\n do\n echo -e \"Path of target directory?\"\n read target_directory\n done\n\nwhile [[ -z \"$brand\" ]]\n do\n echo -e \"\\nBrand Prefix?\"\n read brand\n done\n</code></pre>\n\n<p>That's twice! Write a function to do this:</p>\n\n<pre><code>target_dir=$(prompt_for_variable target_dir 'Path of target directory?')\"\nbrand=\"$(prompt_for_variable brand 'Brand Prefix?')\"\n</code></pre>\n\n<p>Now consider this:</p>\n\n<pre><code>while true;\ndo\n read -p \"Additional rsync options? [y/n] \" rsync_add\n case $rsync_add in\n [Yy]* )\n</code></pre>\n\n<p>Right in the middle of \"construct_rsync\" you stop and loop forever prompting the user for a y/n answer. Write a function for that!</p>\n\n<pre><code>if get_yn 'Additional rsync options?'\nthen\n read -p \"Enter the additional options: \" rsync_options\nfi\n</code></pre></li>\n<li><p>Don't lie to anybody, especially yourself. You have a function called <code>construct_rsync</code> but what does it do? It <em>runs the command.</em> Either change the name, or change the function.</p></li>\n<li><p>Beware of <code>$?</code>. In your <code>log</code> function you refer to it several times. But <code>$?</code> is updated each time a command is run. So if you're going to make decisions based on the value, you should either capture the value into a separate variable (<code>status=$?</code> ... <code>if $status</code>) or make a single decision right up front (<code>if $? ... else ... fi</code>)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T14:10:02.857",
"Id": "418404",
"Score": "0",
"body": "Thanks for the detailed feedback! \n\nI don't have much experience with bash or coding in general so it's very helpful to see some better approaches. \n\nI do not understand how to implement a user prompt function. I believe i'm misunderstanding bash syntax, how arguments are passed, or missing a piece of the problem. If I write a generalized while loop inside a function it does not run properly when using $1 and $2 to populate.\n\n prompt_user(){\n while [[ -z $input ]]\n do \n echo \"$2\"\n read \"$1\" \n }"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T20:57:13.007",
"Id": "418491",
"Score": "0",
"body": "There's potential problems when mixing `while` loops with user input, because in some circumstances (depending on bash version, also) the body of the `while` loop will execute as a sub-shell (separate process, with its own file handles and stuff). Be sure and check Stack Overflow if you're having trouble."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T21:18:09.947",
"Id": "418496",
"Score": "0",
"body": "I managed to get my original functionality working and it was a combination of misunderstanding the way variables were passed and some syntactical errors causing it to not work on my end.\n\nAppreciate the input!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T03:15:00.183",
"Id": "216206",
"ParentId": "216201",
"Score": "4"
}
},
{
"body": "<p>Consider setting <code>-e</code> and <code>-u</code> to make the script abort on some common failures, rather than wildly continuing. The existing script has almost no error checking; as a simple example, closing standard input will lead to an infinite loop repeatedly executing <code>read</code>.</p>\n\n<p>Instead of using non-standard <code>echo -e</code> to prompt, prefer to supply the prompt as argument to <code>read</code>:</p>\n\n<pre><code> read -p \"Path of target directory? \" target_directory\n</code></pre>\n\n<p>Instead of merely checking that the directory path is a non-empty string with <code>[[ -z ]]</code>, we should probably be checking that it's a real directory, with <code>[ -d ]</code>.</p>\n\n<p>Output lines should end with newline, and should generally not begin with newline. And error messages should go to the standard error stream (<code>>&2</code>) rather than to standard output.</p>\n\n<p>There are some quotes needed when expanding pathname variables - at present, any filenames including whitespace will be seen as two or more arguments.</p>\n\n<p>Testing <code>$?</code> is an antipattern. This block:</p>\n\n<blockquote>\n<pre><code>sleep .5\n\nif [[ \"$?\" == \"0\" ]]; then\n echo -e \"\\nTransfer complete!\"\nelif [[ \"$?\" != \"0\" ]]; then\n echo -e \"\\nError in transfer! Please refer to error_log.txt!\"\nfi\n</code></pre>\n</blockquote>\n\n<p>can be written much more simply as</p>\n\n<pre><code>if sleep .5\nthen\n echo \"Transfer complete!\"\nelse\n echo \"Error in transfer! Please refer to error_log.txt!\"\nfi\n</code></pre>\n\n<p>(though I suspect you actually meant to test the exit code of a different command to the <code>sleep</code>).</p>\n\n<p>Finally, run Shellcheck on the code. I get far too many warnings (some of which I've already identified above):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>shellcheck -f gcc 216201.sh\n216201.sh:7:14: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:7:16: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:7:66: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:7:68: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:13:17: note: read without -r will mangle backslashes. [SC2162]\n216201.sh:18:22: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:19:13: note: read without -r will mangle backslashes. [SC2162]\n216201.sh:24:22: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:25:13: note: read without -r will mangle backslashes. [SC2162]\n216201.sh:30:22: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:31:13: note: read without -r will mangle backslashes. [SC2162]\n216201.sh:36:22: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:37:13: note: read without -r will mangle backslashes. [SC2162]\n216201.sh:42:22: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:43:13: note: read without -r will mangle backslashes. [SC2162]\n216201.sh:48:14: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:48:43: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:48:45: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:58:14: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:58:16: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:58:67: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:58:69: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:62:9: note: read without -r will mangle backslashes. [SC2162]\n216201.sh:69:13: note: read without -r will mangle backslashes. [SC2162]\n216201.sh:76:9: note: read without -r will mangle backslashes. [SC2162]\n216201.sh:79:26: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:80:17: note: read without -r will mangle backslashes. [SC2162]\n216201.sh:88:14: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:88:45: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:90:36: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:91:11: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:92:8: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:93:22: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:94:59: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:95:22: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:96:21: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:97:13: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:99:87: note: Double quote to prevent globbing and word splitting. [SC2086]\n216201.sh:106:14: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:111:11: note: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?. [SC2181]\n216201.sh:112:18: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:113:13: note: Check exit code directly with e.g. 'if mycmd;', not indirectly with $?. [SC2181]\n216201.sh:114:18: note: Backslash is literal in \"\\n\". Prefer explicit escaping: \"\\\\n\". [SC1117]\n216201.sh:122:1: note: read without -r will mangle backslashes. [SC2162]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T14:56:40.680",
"Id": "418409",
"Score": "0",
"body": "Excellent feedback! I've restructured a bit of my code per the two answers i've gotten.\n\nAs I understand it, I've set up the mkdir such that it will create the parent directories if they do not exist. \n\nAs to the others, I need flexibility in the naming to accommodate any string I just can't have empty strings.\n\nHow do you suggest I check for empty string and re-prompt the user if the input is empty?\n\nI tried to implement a while loop in a function and my inexperience with bash is making progress slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T15:25:06.937",
"Id": "418430",
"Score": "0",
"body": "I may have misunderstood from reading the code whether the target directory had to pre-exist; sorry if I got that wrong. The simple loop seems reasonable to me: `until [ \"${dir-}\" ]; do read -p \"Enter directory: \" dir; done` (the `${dir-}` expansion allows `$dir` to be unset without error despite `set -u`)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T13:28:14.207",
"Id": "216245",
"ParentId": "216201",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T01:06:15.813",
"Id": "216201",
"Score": "4",
"Tags": [
"bash"
],
"Title": "Simple media ingest script"
} | 216201 |
<p>I use a dummy solution to solve the leetcode <a href="https://leetcode.com/problems/3sum/description/" rel="nofollow noreferrer">3Sum</a> problem. </p>
<p>I employ the <em>set</em> data type to handle duplicates, then transform back to list.</p>
<blockquote>
<p>Given an array <code>nums</code> of <em>n</em> integers, are there elements <em>a</em>, <em>b</em>, <em>c</em> in <code>nums</code> such that <em>a</em> + <em>b</em> + <em>c</em> = 0? Find all unique triplets in the array which gives the sum of zero.</p>
<p><strong>Note:</strong></p>
<p>The solution set must not contain duplicate triplets.</p>
<p><strong>Example:</strong></p>
<p>Given array <code>nums = [-1, 0, 1, 2, -1, -4]</code>,</p>
<p>A solution set is:</p>
<pre><code>[
[-1, 0, 1],
[-1, -1, 2]
]
</code></pre>
</blockquote>
<p>My codes:</p>
<pre><code>from typing import List
import logging
import unittest
import random
from collections import defaultdict,Counter
##logging.disable(level=#logging.CRITICAL)
##logging.basicConfig(level=#logging.DEBUG, format="%(levelname)s %(message)s")
class Solution:
def threeSum(self, nums, target: int=0) -> List[List[int]]:
"""
:type nums: List[int]
:type target: int
"""
if len(nums) < 3: return []
triplets = []
if target == [0, 0, 0]:
triplets.append([0, 0, 0])
return triplets # finish fast
lookup = {nums[i]:i for i in range(len(nums))} #overwrite from the high
if len(lookup) == 1:#assert one identical element
keys = [k for k in lookup.keys()]
if keys[0] != 0:
return []
else:
triplets.append([0,0,0])
return triplets
triplets_set = set()
for i in range(len(nums)):
num_1 = nums[i]
sub_target = target - num_1
# #logging.debug(f"level_1_lookup: {lookup}")
for j in range(i+1, len(nums)):
num_2 = nums[j]
num_3 = sub_target - num_2
k = lookup.get(num_3) #
if k not in {None, i, j}: #don't reproduce itself
result = [num_1, num_2, num_3]
result.sort()
result = tuple(result)
triplets_set.add(result)
triplets = [list(t) for t in triplets_set]
return triplets
</code></pre>
<p>My solution gets this result:</p>
<blockquote>
<p>Your runtime beats 28.86 % of python3 submissions.</p>
</blockquote>
<p>Could anyone please give hints to improve?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T05:48:09.253",
"Id": "418343",
"Score": "1",
"body": "Can you check the problem description? It is about pairs (a, b) which sum to 9, but the examples are about triples which sum to zero. – Btw, if you beat 28.86 of other submissions then you are slower 71.14 percent, not slower than 80 percent :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T06:31:48.557",
"Id": "418346",
"Score": "1",
"body": "As *set* is a common verb in English, try to avoid confusion: *set* is a Python [built-in *data* type](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset). (Grant me the favour and never call any amount of program source code [\"codes\"](https://en.m.wikipedia.org/wiki/Code_(disambiguation)#Computing).) How could `target: int` `== [0, 0, 0]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:25:27.383",
"Id": "418382",
"Score": "0",
"body": "amazing, better than leetcode's big data testing. @greybeard"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T06:04:30.407",
"Id": "418647",
"Score": "0",
"body": "Ah, before I forget *again*: Congrats on asking for a review, for `hints to improve` instead of a turn-key solution, on (seemingly) trying to come up with a solution of your own instead of scraping the web/SE/leetcode. Way to learn!"
}
] | [
{
"body": "<p>Multi-part answer: [0) these preliminaries] 1) review of code presented 2) hints for improvement excluding <em>personal</em>, from <em>programming</em> over <em>python</em> and <em>accepting a programming challenge</em> to <em>k-sum</em> and <em>leetcode 3Sum</em>.</p>\n\n<p>One general principle to follow is <em>do as expected</em>, in programming, it has been formulated in many guises, including <a href=\"https://en.m.wikipedia.org/wiki/Principle_of_least_astonishment#Formulation\" rel=\"nofollow noreferrer\">Principle of Least Surprise</a>. Every other route leaves you under pressure to justify, at risk of being misunderstood. </p>\n\n<p>In coding, <em>document, in the program source code</em>:<br>\nWhat is \"everything\" there for? </p>\n\n<p>Such rules often have been gathered into <em>guide lines</em>, for Python, follow the <a href=\"https://www.python.org/dev/peps/pep-0008/#contents\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a>.</p>\n\n<hr>\n\n<ul>\n<li>Instead of a <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">docstring</a>, your module starts with imports - most of them unused.</li>\n<li><em>If your code</em> mentioned <em>leetcode</em>, the presentation of a <code>class Solution</code> with just one function definition wouldn't beg justification.</li>\n<li>the definition of <code>threeSum()</code> shows (a cute addition of <code>target</code>&default and) a curious mix of leetcode's templates for Python 2&3, lacking a proper docstring</li>\n<li>comparing \"the int\" <code>target</code> to the list literal <code>[0, 0, 0]</code> is dangerous given Python's zeal to allow operations: do you know by heart when that evaluates to <code>True</code>?<br>\n(Do you expect most every reader of your code to?)<br>\n(Belatedly, it occurred to me that you may have intended to compare <code>nums</code> to <code>[0, 0, 0]</code> - bogus if <code>target != 0</code>)</li>\n<li>verbosity - \nyou can denote a tuple containing a single literal list like <code>([v, v, v],)</code></li>\n<li>2nd early out:<br>\nwith only one key→value in the <em>dict</em>, there's no need to access it:<br>\n<em>every</em> key will equal <code>nums[0]</code><br>\nYou need to check for <code>3*nums[0] != target</code></li>\n<li>naming (Not your fault: <code>Solution</code> and <code>threeSum</code> are substandard.<br>\n<code>nums</code>/_1-3 don't <em>feel</em> bad enough to change):<br>\n- <code>target</code>, <code>triplets</code>, <code>sub_target</code>: right on!<br>\n- given Python's \"duck typing\", I'd stick with <code>triplets</code> (, never introducing <code>triplets_set</code>)<br>\n- <code>lookup</code> is a horrible name → <code>value_to_index</code> (or, in a suitably small context, just <code>index</code>)<br>\n(- there's one thing wrong with <code>k</code>: it gets in the way when extending three_sum() to k_sum()…)</li>\n<li><em>pythonic</em> or not (or exploiting library functions, rather?):<br>\n<code>value_to_index = { value: index for index, value in enumerate(nums) }</code><br>\n(same for <code>for i, num_1 in enumerate(nums)</code>, <code>for j, num_2 in enumerate(nums[i+1:], i+1)</code>)</li>\n<li>commenting<br>\n- you <em>did</em> comment, and I find half of the comments helpful<br>\n- I don't get <code>#overwrite from the high</code> (that <em>may</em> just be me)<br>\n- <code>#don't reproduce itself</code>: probably <code>use any element/index once, at most</code> rather than <code>don't repeat an element/index</code><br>\n- you did <em>not</em> comment the outer for loop, arguably the most profitable place:<br>\n<em>how</em> is what the execution constructs a <em>solution</em>?:<br>\nfor each value, <code>value_to_index</code> keeps just the last index: how does this <em>not</em> prevent any valid triple to show up in the solution?</li>\n<li>checking <code>k</code>: <em>nice</em>!<br>\n(I'd go for <code>in (None, i, j)</code>)</li>\n<li><p>you don't provide a \"tinker harness\"</p>\n\n<pre><code>if __name__ == '__main__':\n object_disoriented = Solution()\n print(object_disoriented.threeSum([-1, 0, 1, 2, -1, -4]))\n print(object_disoriented.threeSum([1, 1, 1], 3))\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>(Something else to follow is <em>make (judicious) use of every help you can</em>: if you use an IDE supporting Python, chances are it can help you with PEP8.)\n(Running low on steam, this part will start more frugal than expected.)</p>\n\n<p><em>Real Programming</em> is the creation of a language that simplifies the solution of the problem at hand.</p>\n\n<p>With Python providing most <em>mechanisms</em> needed in programming challenges, that leaves:</p>\n\n<ul>\n<li>Code readably. </li>\n<li>Create elements easy to use correctly.</li>\n</ul>\n\n<p>I bickered you some about <em>having a consistent problem description</em>.<br>\nThis is another place where <a href=\"http://pythontesting.net/agile/test-first-programming/\" rel=\"nofollow noreferrer\">Test First</a> shines:<br>\nAs long as you find yourself not knowing what to test, you are not in a position to implement anything, yet. (Inconsistencies in specification tend to stand out in test design & implementation.)</p>\n\n<p><em>Programming challenges</em> à la leetcode.com typically build on simpler challenges - you met 2sum, which puts you in a favourable position to tackle 3sum.<br>\nThe performance part of these challenges is about not doing things over, not discarding knowledge more often than about algebraic insight.</p>\n\n<p>The generic solution to 2sum is to take values and <em>find the complement</em> (1sum?).<br>\nThe extension to <em>k</em>-sum is to split <em>k</em> into smaller numbers.</p>\n\n<p>Ways to have information about the order of a set or sequence (say, <em>elements</em>) of instances of a type with ordering reusable is to have them ordered (<code>ordered = sorted(elements)</code>) or sorted (<code>histogram = Counter(elements)</code>).<br>\nFor 2sum, you could search for <code>target/2</code> and work inside-out.<br>\nFor 3sum, one value will be no greater, another no smaller than both others. The third one will not \"lie outside\" the former two.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-28T14:52:01.833",
"Id": "216425",
"ParentId": "216207",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T03:28:20.473",
"Id": "216207",
"Score": "1",
"Tags": [
"python",
"performance",
"algorithm",
"programming-challenge",
"k-sum"
],
"Title": "In an set of integers, find three elements summing to zero (3-sum, leetcode variant)"
} | 216207 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.