body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I built a simple Rock Paper Scissors game in Python as my first "project", and I want a feedback from you. I want your opinion on how I write my code, is it okay and readable enough? PEP8 laws, things to improve or preserve?</p> <p><strong>Computer Choice - Generating a random choice with the <code>random</code> module and the <code>random.randomchoice()</code> method from a <code>list</code>.</strong></p> <p><strong>User Choice - Taking an Input from the user as a character (R, P and S) and uppercasing the character.</strong></p> <p><strong>Finally, I'm checking who is the winner with <code>if</code> conditions.</strong></p> <pre><code>import random choices = ['Rock', 'Paper', 'Scissors'] bot_choices = random.SystemRandom().choice(choices) def result(user, bot): return f'\nComputer Choice: {bot}\nYour Choice: {user}' class RPS: def __init__(self): self.user_choice = str(input('(R)ock, (P)aper, (S)cissors: ')).upper() if not self.user_choice or self.user_choice not in ['R', 'P', 'S']: print('Invalid Input!') else: self.get_winner() print(result(self.user_choice, bot_choices)) def get_winner(self): if self.user_choice == 'R' and bot_choices == 'Paper' or self.user_choice == 'P' and bot_choices == 'Scissors' or self.user_choice == 'S' and bot_choices == 'Rock': print('Result: Computer Won!') elif self.user_choice == 'R' and bot_choices == 'Rock' or self.user_choice == 'P' and bot_choices == 'Paper' or self.user_choice == 'S' and bot_choices == 'Scissors': print('Result: Tie!') else: print('Result: You Won!') if __name__ == '__main__': game = RPS() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T18:06:23.950", "Id": "464953", "Score": "0", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." } ]
[ { "body": "<p>Well, there are few points to address.</p>\n\n<ul>\n<li><p>Your code is structured in a lot of ways: at the same level, we have variables, a function and a class. You have game logic directly in the module, which is evaluated once (at module import), so your bot always have the same choice made.</p></li>\n<li><p>Also, the RPS class is not necessary. It only do stuff on instantiation, and it uses a function outside itself to print each player's choice. I think you should remove it, mainly because you will never need several RPS objects at once, nor have to store informations for a while.</p></li>\n<li><p>Regarding to formatting your code, personnaly I always set a character limit per line of 100. I find it helps to keep the code a little bit more readable (personnal choice).</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T15:03:51.343", "Id": "464928", "Score": "0", "body": "Thank you, but my program is running only one time, so it will generate different choices every time i'm running my program." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T14:50:56.640", "Id": "237157", "ParentId": "237152", "Score": "2" } }, { "body": "<p>Echoing all of VincentRG's points, with a little clarification and demonstration:</p>\n\n<ol>\n<li><p>The only reason to wrap code in a <code>if __name__ == '__main__'</code> block is to keep it from being executed when your module is imported by another module. By that token, the fact that you initialize <code>bot_choices</code> outside of that block means that those random choices will be determined only <em>once</em> at the time of import, so the importing module will get the same result every time it calls <code>RPS()</code>. This is probably not what you want. It doesn't affect the way your program runs since you don't actually have any other modules, but if you're going to check for <code>__main__</code> you should understand <em>why</em> you're doing that and apply the same logic to other parts of your code.</p></li>\n<li><p>This does not need to be a class and therefore should not be. Here's how to write it as a single simple function (this is mostly just taking your existing code and moving it around):</p></li>\n</ol>\n\n<pre><code>import random\n\ndef rock_paper_scissors() -&gt; None:\n bot_choice = random.SystemRandom().choice(['Rock', 'Paper', 'Scissors'])\n\n user_choice = str(input('(R)ock, (P)aper, (S)cissors: ')).upper()\n if user_choice not in ['R', 'P', 'S']:\n print('Invalid Input!')\n return\n\n if (user_choice == 'R' and bot_choice == 'Paper' \n or user_choice == 'P' and bot_choice == 'Scissors' \n or user_choice == 'S' and bot_choice == 'Rock'):\n print('Result: Computer Won!')\n elif user_choice == bot_choice[0]:\n print('Result: Tie!')\n else:\n print('Result: You Won!')\n\n print(f'\\nComputer Choice: {bot_choice}\\nYour Choice: {user_choice}')\n\nif __name__ == '__main__':\n rock_paper_scissors()\n</code></pre>\n\n<p>More notes:</p>\n\n<ul>\n<li>Not necessary to check <code>user_choice</code> for truthiness if you're already checking it for membership in a collection of truthy values.</li>\n<li>The name <code>bot_choices</code> is confusing if it's a single choice. Changed it to <code>bot_choice</code>.</li>\n<li>There's no reason to name the <code>choices</code> variable since you never use it again after picking <code>bot_choice</code>.</li>\n<li>You can simplify the tie check way down by just checking the user choice against the first letter of the bot choice. </li>\n<li>This would be simpler yet if you defined the choices as an <code>Enum</code> and had the player and bot use the same enum instead of their own hardcoded strings.</li>\n</ul>\n\n<p>If you have no need to reuse this function or this module, this script doesn't even need to define a function. You could have a file that just looks like:</p>\n\n<pre><code>import random\n\nbot_choice = random.SystemRandom().choice(['Rock', 'Paper', 'Scissors'])\n\nuser_choice = str(input('(R)ock, (P)aper, (S)cissors: ')).upper()\nif user_choice not in ['R', 'P', 'S']:\n print('Invalid Input!')\n exit()\n\nif (user_choice == 'R' and bot_choice == 'Paper' \n or user_choice == 'P' and bot_choice == 'Scissors' \n or user_choice == 'S' and bot_choice == 'Rock'):\n print('Result: Computer Won!')\nelif user_choice == bot_choice[0]:\n print('Result: Tie!')\nelse:\n print('Result: You Won!')\n\nprint(f'\\nComputer Choice: {bot_choice}\\nYour Choice: {user_choice}')\n</code></pre>\n\n<p>and it would behave exactly the same.</p>\n\n<p>Here's how you might use an <code>Enum</code> to specify the choices:</p>\n\n<pre><code>import enum\nimport random\n\nclass Choice(enum.Enum):\n ROCK = \"R\"\n PAPER = \"P\"\n SCISSORS = \"S\"\n\nwhat_beats = {\n Choice.SCISSORS: Choice.ROCK,\n Choice.ROCK: Choice.PAPER,\n Choice.PAPER: Choice.SCISSORS,\n}\n\nbot_choice = random.choice([c for c in Choice])\n\ntry:\n user_choice = Choice(input('(R)ock, (P)aper, (S)cissors: ').upper())\nexcept ValueError:\n print('Invalid input!')\n exit()\n\nif what_beats[user_choice] == bot_choice:\n print('Result: Computer Won!')\nelif user_choice == bot_choice:\n print('Result: Tie!')\nelse:\n print('Result: You Won!')\n\nprint(f'\\nComputer Choice: {bot_choice.name.title()}'\n f'\\nYour Choice: {user_choice.name.title()}')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T18:04:30.233", "Id": "237174", "ParentId": "237152", "Score": "3" } } ]
{ "AcceptedAnswerId": "237174", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T14:06:47.090", "Id": "237152", "Score": "4", "Tags": [ "python", "rock-paper-scissors" ], "Title": "Rock-Paper-Scissors implementation" }
237152
<p>After following the suggestions you can find <a href="https://codereview.stackexchange.com/questions/236986/c-determinant-calculator-follow-up">here</a>, I'd like to show the result again (but I did not change the algorithm):</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;iomanip&gt; int getDimension(); void getUserInput(std::vector&lt;std::vector&lt;double&gt;&gt;&amp; vect, int i, int dimension); double getDeterminant(const std::vector&lt;std::vector&lt;double&gt;&gt; vect); void printMatrix(const std::vector&lt;std::vector&lt;double&gt;&gt; vect); int main() { //First, the user has to enter the dimension of the matrix int dimension = getDimension(); //Now, the user has to enter the matrix line by line, seperated by commas std::vector&lt;std::vector&lt;double&gt;&gt; vect(dimension, std::vector&lt;double&gt; (dimension)); for(int i = 1; i &lt;= dimension; i++) { getUserInput(vect, i, dimension); } //Output printMatrix(vect); std::cout &lt;&lt; "Determinant of the matrix is : " &lt;&lt; getDeterminant(vect) &lt;&lt; "\n"; return 0; } int getDimension() { int dimension; std::cout &lt;&lt; "Please enter dimension of Matrix: "; std::cin &gt;&gt; dimension; std::cout &lt;&lt; "\n"; if(dimension &lt; 0 || std::cin.fail()) { std::cin.clear(); std::cin.ignore(); std::cout &lt;&lt; "ERROR: Dimension cannot be &lt; 0.\n"; return getDimension(); } return dimension; } void getUserInput(std::vector&lt;std::vector&lt;double&gt;&gt;&amp; vect, int i, int dimension) { std::string str = ""; std::cout &lt;&lt; "Enter line " &lt;&lt; i &lt;&lt; " only seperated by commas: "; std::cin &gt;&gt; str; std::cout &lt;&lt; "\n"; str = str + ','; std::string number = ""; int count = 0; for(std::size_t k = 0; k &lt; str.length(); k++) { if(str[k] != ',') { number = number + str[k]; } else if(count &lt; dimension) { if(number.find_first_not_of("0123456789.-") != std::string::npos) { std::cout &lt;&lt; "ERROR: Not only numbers entered.\n"; getUserInput(vect, i, dimension); break; } else if(number.find_first_not_of("0123456789") == std::string::npos) { vect[i - 1][count] = std::stod(number); number = ""; count++; } else { std::cout &lt;&lt; "ERROR: Not enough numbers entered.\n"; getUserInput(vect, i, dimension); break; } } else { std::cout &lt;&lt; "ERROR: Too many numbers entered.\n"; getUserInput(vect, i, dimension); break; } } } double getDeterminant(const std::vector&lt;std::vector&lt;double&gt;&gt; vect) { int dimension = vect.size(); if(dimension == 0) { return 1; } if(dimension == 1) { return vect[0][0]; } //Formula for 2x2-matrix if(dimension == 2) { return vect[0][0] * vect[1][1] - vect[0][1] * vect[1][0]; } double result = 0; int sign = 1; for(int i = 0; i &lt; dimension; i++) { //Submatrix std::vector&lt;std::vector&lt;double&gt;&gt; subVect(dimension - 1, std::vector&lt;double&gt; (dimension - 1)); for(int m = 1; m &lt; dimension; m++) { int z = 0; for(int n = 0; n &lt; dimension; n++) { if(n != i) { subVect[m-1][z] = vect[m][n]; z++; } } } //recursive call result = result + sign * vect[0][i] * getDeterminant(subVect); sign = -sign; } return result; } void printMatrix(const std::vector&lt;std::vector&lt;double&gt;&gt; vect) { for(std::size_t i = 0; i &lt; vect.size(); i++) { for(std::size_t j = 0; j &lt; vect.size(); j++) { std::cout &lt;&lt; std::setw(8) &lt;&lt; vect[i][j] &lt;&lt; " "; } std::cout &lt;&lt; "\n"; } } </code></pre> <p>Do you have any more suggestions on improving the code?</p>
[]
[ { "body": "<p>You need to check for <code>std::cin::eof()</code> before <code>std::cin.fail()</code> (or simply <code>!std::cin</code>), because there's no point repeating the read infinitely if we've reached EOF.</p>\n\n<p>To demonstrate, just run the program with closed standard input, e.g.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>make 237153\n./237153 &lt;&amp;-\n</code></pre>\n\n<p>The reading of the matrix's elements fails in a different way at end of stream:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>./237153 &lt;&lt;&lt;'2 2-,4 3,2'\nPlease enter dimension of Matrix: \nEnter line 1 only seperated by commas: \nERROR: Not enough numbers entered.\nEnter line 1 only seperated by commas: \nEnter line 2 only seperated by commas: \nterminate called after throwing an instance of 'std::invalid_argument'\n what(): stod\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T14:39:41.553", "Id": "237156", "ParentId": "237153", "Score": "3" } }, { "body": "<p>To add to the other answer(s):</p>\n\n<ul>\n<li><p>The parameters to both <code>getDeterminant</code> and <code>printMatrix</code> should be const-ref instead of passed by-value.</p></li>\n<li><p><code>int dimension = getDimension();</code> should be <code>const int dimension = getDimension();</code></p></li>\n<li><p>Note that <code>str = str + ',';</code> and <code>number = number + str[k];</code> could be rewritten to <code>str += ','</code> and <code>number += str[k]</code>, respectively, for potentially better readability. (Same could be said more about <code>result = result ...</code>).</p></li>\n<li><p><code>int dimension = vect.size();</code> should be <code>const</code>.</p></li>\n<li><p>You could have a look at range-based for loops to make e.g., <code>printMatrix</code> easier to read. That is, you don't really need to play with the indices directly, you could just <code>for(auto x : vect) ...</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T19:38:07.817", "Id": "237257", "ParentId": "237153", "Score": "3" } } ]
{ "AcceptedAnswerId": "237156", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T14:16:43.817", "Id": "237153", "Score": "1", "Tags": [ "c++", "mathematics" ], "Title": "C++ determinant calculator - 2nd follow-up" }
237153
<p>I've a method which is used to build a native sql query. I've 4 String builder as input and based on different conditions, I need to build my query.</p> <p>Here is the code</p> <pre><code>private void appendConditions(StringBuilder query, StringBuilder condition, StringBuilder condition2, StringBuilder condition3) { if (StringUtils.isNotEmpty(condition.toString())) { query.append(ApplicationConstants.AND+"("); query.append("( " + condition + " )"); if (StringUtils.isNotEmpty(condition2.toString())) { query.append(ApplicationConstants.AND); query.append("( " + condition2 + " )"); if (StringUtils.isNotEmpty(condition3.toString())) { query.append(ApplicationConstants.AND); query.append("( " + condition3 + " )"); } } else { if (StringUtils.isNotEmpty(condition3.toString())) { query.append(ApplicationConstants.AND); query.append("( " + condition3 + " )"); } } query.append(" )"); } else { if (StringUtils.isNotEmpty(condition2.toString())) { query.append(ApplicationConstants.AND+"("); query.append("( " + condition2 + " )"); if (StringUtils.isNotEmpty(condition3.toString())) { query.append(ApplicationConstants.AND); query.append("( " + condition3 + " )"); } query.append(" )"); } else { if (StringUtils.isNotEmpty(condition3.toString())) { query.append(ApplicationConstants.AND+"("); query.append("( " + condition3 + " )"); query.append(" )"); } } } </code></pre> <p>}</p> <p>When I run my Sonar report, it says the Cognitive complexity is higher for this method. Can I simplify this methods avoiding many if-else loops</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T05:28:31.537", "Id": "465198", "Score": "0", "body": "Where does `ApplicationConstants.AND` come from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:48:57.800", "Id": "465287", "Score": "1", "body": "Do you have unit tests that exercise this code? This is tangential to the question but for code this complex you NEED unit tests before you start changing it. Since its just building strings it should be easy to unit test." } ]
[ { "body": "<p>A very short review;</p>\n\n<ul>\n<li>Escape your parameters with <a href=\"https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#escapeSql(java.lang.String)\" rel=\"noreferrer\">escapeSql</a>, this is so important!</li>\n<li>You should pass the conditions in array, so that the call can pass an arbitrary amount of conditions</li>\n<li><code>ApplicationConstants.AND</code> &lt;- total overkill, just use <code>AND</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T18:23:34.610", "Id": "464958", "Score": "9", "body": "Going down the SQL path, I'd argue that parameterized queries is even better than escaping the parameters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T18:07:34.117", "Id": "465149", "Score": "0", "body": "Call me OCD crazy, but I do both (escape, then pass to a parameterized query.)\n\nHeck, when I get my way, I put everything in stored procedures (DMLs and DML templates are never exposed in code, nor in config files), called with CallableStatements and with parameters already escaped.\n\nIt's extra work to set up, but it has saved me countless hours in maintaining and trouble shooting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T16:06:42.920", "Id": "465294", "Score": "4", "body": "@luis.espinal escape and then parameterize? If this means what I think it means the end effect will be that you're storing an SQL-escaped version of the data in the database, which is an absolute nightmare to anyone trying to maintain it after you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T21:49:17.917", "Id": "465402", "Score": "0", "body": "This is only a concern if the data has questionable \"injections\". A string with \"John Doe\" can be sql-escaped ad infinitum yielding \"John Doe.\"\n\nI do this when I have to interface with teams or software that might take values I send and concatenate them into SQL statements (rather than using binding variables.)\n\nI've had more headaches by cowboys that do that than by doing what I've just described.\n\nYMMV, depending on how *you* (the generic *you*) codes and what kind of teams you must interact with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T13:00:40.100", "Id": "465708", "Score": "0", "body": "This should probably go to chat, but using parameterized queries *and* escaping is just bad practice, in all cases." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T17:38:23.783", "Id": "237171", "ParentId": "237168", "Score": "8" } }, { "body": "<p>I am not sure what exactly you're trying to achieve, but after reading through the code I have following thoughts:</p>\n\n<ol>\n<li>Why do you use <code>StringUtils.isNotEmpty</code> instead of <code>.isEmpty()</code>? It looks fairly unlikely that <code>condition.toString()</code> would return <code>null</code>. Also, for <code>StringBuilder</code> you may want to use length (<code>condition.length != 0</code>)</li>\n<li>Since if's logic for different <code>conditions</code> is almost identical, you can use a loop:</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>private void appendConditions(StringBuilder query, StringBuilder... conditions) {\n StringBuilder subQuery = new StringBuilder();\n for (StringBuilder condition: conditions) {\n if (condition.length != 0) {\n if (subQuery.length != 0) {\n query.append(ApplicationConstants.AND);\n }\n subQuery.append(\"( \" + condition + \" )\");\n }\n if (subQuery.length != 0) {\n query.append(ApplicationConstants.AND+\"(\"+subQuery+\")\");\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T18:24:52.607", "Id": "464959", "Score": "6", "body": "`!= \"\"` should not be used when comparing strings. It would compare the *object reference* instead of the actual *content*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T13:10:58.903", "Id": "465444", "Score": "0", "body": "@SimonForsberg sure, stupid me. It should have been .isEmpty(). Fixed!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T17:51:59.840", "Id": "237172", "ParentId": "237168", "Score": "2" } }, { "body": "<p>Let's look for some patterns in your code:</p>\n\n<p>First of all, we notice that you have three parameters with similar names. <code>condition</code>, <code>condition2</code> and <code>condition3</code>. These names indicates a code smell, that we should use an array or list instead.</p>\n\n<p>Taking one step at a time, we see this code is repeated multiple times:</p>\n\n<pre><code>if (StringUtils.isNotEmpty(condition.toString())) {\n query.append(ApplicationConstants.AND+\"(\");\n query.append(\"( \" + condition + \" )\");\n\nif (StringUtils.isNotEmpty(condition2.toString())) {\n query.append(ApplicationConstants.AND);\n query.append(\"( \" + condition2 + \" )\");\n\nif (StringUtils.isNotEmpty(condition3.toString())) {\n query.append(ApplicationConstants.AND);\n query.append(\"( \" + condition3 + \" )\");\n\nif (StringUtils.isNotEmpty(condition3.toString())) {\n query.append(ApplicationConstants.AND);\n query.append(\"( \" + condition3 + \" )\");\n\nif (StringUtils.isNotEmpty(condition2.toString())) {\n query.append(ApplicationConstants.AND+\"(\");\n query.append(\"( \" + condition2 + \" )\");\n\nif (StringUtils.isNotEmpty(condition3.toString())) {\n query.append(ApplicationConstants.AND);\n query.append(\"( \" + condition3 + \" )\");\n\nif (StringUtils.isNotEmpty(condition3.toString())) {\n query.append(ApplicationConstants.AND+\"(\");\n query.append(\"( \" + condition3 + \" )\");\n</code></pre>\n\n<p>This indicates that we can extract a method. (We can also notice that the <code>\"(\"</code> should be added for the <em>first true</em> if-statement, this is important but we will ignore this for now and get back to this later).</p>\n\n<pre><code>private boolean addParameter(StringBuilder query, StringBuilder condition) {\n if (StringUtils.isNotEmpty(condition.toString())) {\n query.append(ApplicationConstants.AND);\n query.append(\"( \" + condition + \" )\");\n return true;\n }\n return false;\n}\n\nprivate void appendConditions(StringBuilder query, StringBuilder condition, StringBuilder condition2,\n StringBuilder condition3) {\nif (addParameter(condition)) {\n if (addParameter(condition2)) {\n if (addParameter(condition3)) {\n // we don't actually care about the result here\n }\n } else {\n if (addParameter(condition3)) {\n // not here either\n }\n }\n query.append(\" )\");\n} else {\n if (addParameter(condition2)) {\n if (addParameter(condition3)) {\n // again, don't care about result\n }\n query.append(\" )\");\n } else {\n if (addParameter(condition3)) {\n // yeah ok, here we actually care...\n query.append(\" )\");\n }\n }\n}\n</code></pre>\n\n<p>Now it's pretty clear that <code>query.append(\" )\");</code> should always be done last, so that can be moved out and then we can avoid some <code>if</code> statements.</p>\n\n<pre><code>private void appendConditions(StringBuilder query, StringBuilder condition, StringBuilder condition2,\n StringBuilder condition3) {\nif (addParameter(condition)) {\n if (addParameter(condition2)) {\n addParameter(condition3);\n } else {\n addParameter(condition3);\n }\n} else {\n if (addParameter(condition2)) {\n addParameter(condition3);\n } else {\n addParameter(condition3);\n }\n}\nquery.append(\" )\");\n</code></pre>\n\n<p>And now we're doing the same in both some if's and else's, so that can be simplified:</p>\n\n<pre><code>private void appendConditions(StringBuilder query, StringBuilder condition, StringBuilder condition2,\n StringBuilder condition3) {\nif (addParameter(condition)) {\n addParameter(condition2);\n addParameter(condition3);\n} else {\n addParameter(condition2);\n addParameter(condition3);\n}\nquery.append(\" )\");\n</code></pre>\n\n<p>Once again we're doing the same thing:</p>\n\n<pre><code>private void appendConditions(StringBuilder query, StringBuilder condition, StringBuilder condition2,\n StringBuilder condition3) {\naddParameter(condition);\naddParameter(condition2);\naddParameter(condition3);\nquery.append(\" )\");\n</code></pre>\n\n<p>So we're essentially doing the same thing three times. This is where a loop would be handy.</p>\n\n<pre><code>private void appendConditions(StringBuilder query, StringBuilder... conditions) {\n for (StringBuilder condition : conditions) {\n addParameter(condition);\n }\n query.append(\" )\");\n</code></pre>\n\n<p>And now of course, we don't really need that separate <code>addParameter</code> method.</p>\n\n<pre><code>private void appendConditions(StringBuilder query, StringBuilder... conditions) {\n for (StringBuilder condition : conditions) {\n if (StringUtils.isNotEmpty(condition.toString())) {\n query.append(ApplicationConstants.AND);\n query.append(\"( \" + condition + \" )\");\n }\n }\n query.append(\" )\");\n</code></pre>\n\n<hr>\n\n<p>Now, let's get back to the parenthesis: <code>+\"(\"</code> is added in the first true if-statement in your original code. So this, in connection with the closing <code>\" )\"</code> can be handled by for example keeping a <code>boolean</code> to check for if an if-statement has been true so far.</p>\n\n<pre><code>private void appendConditions(StringBuilder query, StringBuilder... conditions) {\n boolean conditionUsed = false;\n for (StringBuilder condition : conditions) {\n if (StringUtils.isNotEmpty(condition.toString())) {\n query.append(ApplicationConstants.AND);\n if (!conditionUsed) {\n conditionUsed = true;\n query.append(\" (\");\n }\n query.append(\"( \" + condition + \" )\");\n }\n }\n if (conditionUsed) {\n query.append(\" )\");\n }\n</code></pre>\n\n<p>But when reflecting more about what it is that you do, we see that you have a collection of <code>StringBuilder</code>s, you check each if it is not empty, then you join them together with <code>ApplicationConstants.AND</code>.</p>\n\n<pre><code> String specialConditions = Arrays.stream(conditions)\n .map(StringBuilder::toString)\n .filter(StringUtils::isNotEmpty)\n .collect(Collectors.joining(ApplicationConstants.AND));\n if (StringUtils.isNotEmpty(specialConditions)) {\n query.append(\" (\");\n query.append(specialConditions);\n query.append(\" )\");\n }\n</code></pre>\n\n<p>Voilà!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T18:40:35.547", "Id": "237177", "ParentId": "237168", "Score": "27" } }, { "body": "<p>I wouldn't follow this approach at all, trying to create a dynamic SQL by hand using StringBuilder or StringBuffer.</p>\n\n<p>It is inevitable that the complexity will shoot off the roof. And it is very rare to find a need for building SQL statements dynamically like that. </p>\n\n<p>In 30 years, I haven't seen a justification. Every application I've known has a finite set of access patterns, ergo a finite set of SQL statements it needs. </p>\n\n<p>Instead, I would suggest you use parameterized SQL statements (see example below from <a href=\"http://tutorials.jenkov.com/jdbc/preparedstatement.html\" rel=\"noreferrer\">this tutorial</a>)</p>\n\n<pre><code>String sql = \"update people set firstname=? , lastname=? where id=?\";\n\nPreparedStatement preparedStatement =\n connection.prepareStatement(sql);\n\npreparedStatement.setString(1, \"Gary\"); \npreparedStatement.setString(2, \"Larson\"); \npreparedStatement.setLong (3, 123);\n\nint rowsAffected = preparedStatement.executeUpdate();\n</code></pre>\n\n<p>Better yet, load that string from a resource bundle or property.</p>\n\n<p>Other possibilities include using a DSL like <a href=\"http://www.jooq.org/\" rel=\"noreferrer\">jOOQ</a> (example below, from the jOOQ's site):</p>\n\n<pre><code>create.select(AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME, count())\n .from(AUTHOR)\n .join(BOOK).on(AUTHOR.ID.equal(BOOK.AUTHOR_ID))\n .where(BOOK.LANGUAGE.eq(\"DE\"))\n .and(BOOK.PUBLISHED.gt(date(\"2008-01-01\")))\n .groupBy(AUTHOR.FIRST_NAME, AUTHOR.LAST_NAME)\n .having(count().gt卌)\n .orderBy(AUTHOR.LAST_NAME.asc().nullsFirst())\n .limit(2)\n .offset(1)\n</code></pre>\n\n<p>Or <a href=\"http://blog.mysema.com/2011/01/querying-in-sql-with-querydsl.html\" rel=\"noreferrer\">QueryDSL</a> (example below):</p>\n\n<pre><code>QCustomer customer = new QCustomer(\"c\"); // alias for the CUSTOMER table\n\nSQLTemplates dialect = new HSQLDBTemplates(); // SQL-dialect\nSQLQuery query = new SQLQueryImpl(connection, dialect); \nList&lt;String&gt; lastNames = query.from(customer)\n .where(customer.firstName.eq(\"Bob\"))\n .list(customer.lastName);\n</code></pre>\n\n<p>Or, if you are using JPA, to use the JPA's <a href=\"https://www.baeldung.com/jpa-criteria-api-in-expressions\" rel=\"noreferrer\">Criteria API</a> (example below):</p>\n\n<pre><code>Subquery&lt;Department&gt; subquery = criteriaQuery.subquery(Department.class);\nRoot&lt;Department&gt; dept = subquery.from(Department.class);\nsubquery.select(dept)\n .distinct(true)\n .where(criteriaBuilder.like(dept.get(\"name\"), \"%\" + searchKey + \"%\"));\n\ncriteriaQuery.select(emp)\n .where(criteriaBuilder.in(emp.get(\"department\")).value(subquery));\n</code></pre>\n\n<p>Good luck.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T18:24:25.700", "Id": "465313", "Score": "1", "body": "So much this. If you absolutely need to build a query at runtime, use something like the Criteria API with for example Hibernate" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T18:33:08.650", "Id": "237256", "ParentId": "237168", "Score": "7" } } ]
{ "AcceptedAnswerId": "237177", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T17:15:33.767", "Id": "237168", "Score": "7", "Tags": [ "java", "sql" ], "Title": "Simplifying constructing native SQL query with nested if-else's" }
237168
<p>I am working as a validation technician for excel spreadsheets in a pharma company. Sadly &amp; interestingly I don't know much about VBA and Excel.</p> <p>To validate those excel spreadsheet, I developped with macro-recording the following code, which helps me identifying the cell properties.</p> <p>The goal is to quickly obtain relevant parameters by entering minimum of informations (password; analysis range)</p> <p>Here is an example of what I am currently achieving :</p> <p><a href="https://i.stack.imgur.com/hVL6X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hVL6X.png" alt="Spreadsheet before analysis"></a></p> <p>Running the macro</p> <p><a href="https://i.stack.imgur.com/N4cTf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N4cTf.png" alt="Spreadsheet after anaylysis"></a></p> <p><strong>Question :</strong></p> <ul> <li><p><strong>how can I improve this code so it runs faster</strong></p></li> <li><p><strong>If anybody worked with this kind of macro : any suggestions for further developments are welcome</strong></p></li> </ul> <p>Here are some ideas I cannot implement yet due to lack of knowledge</p> <p>Ideas for further improvement :</p> <ul> <li><p>Currently code overwrites worksheet name because I dont know how to extract sheet name</p></li> <li><p>Ideally, it would be better to copy the worksheet then add the custom formula on the second sheet, so the original worksheet isn't changed</p></li> <li><p>Insert input box to define worksheet and workbook password (these two have the same password)</p></li> <li><p>Wish I could retrieve even more informations but I dont know how (such as existing data-validation requirements etc etc)</p></li> </ul> <p><em>Sorry for your eyes, dear developpers, I am aware its really messy code but I didnt find a way to clear it efficiently, and it's currently working fine but rather slowly with old computer</em></p> <p>Many thanks for your help,</p> <p>Max</p> <pre><code>Option Explicit Public Const MDP As String = "PASSWORD" ---------- Sub Cell_analysis() 'Unprotect ActiveSheet.Unprotect Password:=MDP ActiveWorkbook.Unprotect Password:=MDP 'Define range with input box Dim rng As Range Dim DefaultRange As Range Dim FormatRuleInput As String ActiveSheet.Name = "Sheet1" If TypeName(Selection) = "Range" Then Set DefaultRange = Selection Else Set DefaultRange = ActiveCell End If On Error Resume Next Set rng = Application.InputBox( _ Title:="Select Worksheet Range", _ Prompt:="Select Worksheet Range", _ Default:=DefaultRange.Address, _ Type:=8) On Error GoTo 0 If rng Is Nothing Then Exit Sub 'Unmerge all cells rng.UnMerge 'Use following formula to retrieve cell informations ActiveSheet.Copy After:=Sheets(1) rng.Cells.FormulaR1C1 = "=CELL(""Format"",'Sheet1 (2)'!RC)&amp;"" , ""&amp;CELL(""Protect"",'Sheet1 (2)'!RC)&amp;"" , ""&amp;ISFORMULA('Sheet1 (2)'!RC)" 'Conditional formatting Dim condition1, condition2, condition3, condition4, condition5, condition6, condition7, condition8, condition9, condition10, condition11, condition12, condition13, condition14, condition15, condition16, condition17, condition18, condition19, condition20, condition21, condition22, condition23, condition24, condition25, condition26 As FormatCondition 'Clear existing formatting rng.FormatConditions.Delete 'List conditions Set condition1 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="G , 0") Set condition2 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="D1 , 0") Set condition3 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="D2 , 0") Set condition4 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F0 , 0") Set condition5 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F1 , 0") Set condition6 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F2 , 0") Set condition7 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F3 , 0") Set condition8 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F4 , 0") Set condition9 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F5 , 0") Set condition10 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F6 , 0") Set condition11 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F7 , 0") Set condition12 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F8 , 0") Set condition13 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F9 , 0") Set condition14 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="G , 1") Set condition15 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="D1 , 1") Set condition16 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="D2 , 1") Set condition17 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F0 , 1") Set condition18 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F1 , 1") Set condition19 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F2 , 1") Set condition20 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F3 , 1") Set condition21 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F4 , 1") Set condition22 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F5 , 1") Set condition23 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F6 , 1") Set condition24 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F7 , 1") Set condition25 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F8 , 1") Set condition26 = rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:="F9 , 1") 'conditional formatting options With condition1 .Interior.Color = RGB(255, 255, 255) .Font.ColorIndex = 3 End With With condition2 .Interior.Color = RGB(153, 204, 255) .Font.ColorIndex = 3 End With With condition3 .Interior.Color = RGB(102, 178, 255) .Font.ColorIndex = 3 End With With condition4 .Interior.Color = RGB(229, 255, 204) .Font.ColorIndex = 3 End With With condition5 .Interior.Color = RGB(204, 255, 153) .Font.ColorIndex = 3 End With With condition6 .Interior.Color = RGB(178, 255, 102) .Font.ColorIndex = 3 End With With condition7 .Interior.Color = RGB(153, 255, 51) .Font.ColorIndex = 3 End With With condition8 .Interior.Color = RGB(128, 218, 0) .Font.ColorIndex = 3 End With With condition9 .Interior.Color = RGB(102, 204, 0) .Font.ColorIndex = 3 End With With condition10 .Interior.Color = RGB(76, 153, 0) .Font.ColorIndex = 3 End With With condition11 .Interior.Color = RGB(51, 102, 0) .Font.ColorIndex = 3 End With With condition12 .Interior.Color = RGB(37, 72, 0) .Font.ColorIndex = 3 End With With condition13 .Interior.Color = RGB(25, 45, 0) .Font.ColorIndex = 3 End With With condition14.Interior .Color = RGB(255, 255, 255) End With With condition15.Interior .Color = RGB(153, 204, 255) End With With condition16.Interior .Color = RGB(102, 178, 255) End With With condition17.Interior .Color = RGB(229, 255, 204) End With With condition18.Interior .Color = RGB(204, 255, 153) End With With condition19.Interior .Color = RGB(178, 255, 102) End With With condition20.Interior .Color = RGB(153, 255, 51) End With With condition21.Interior .Color = RGB(128, 218, 0) End With With condition22.Interior .Color = RGB(102, 204, 0) End With With condition23.Interior .Color = RGB(76, 153, 0) End With With condition24.Interior .Color = RGB(51, 102, 0) End With With condition25.Interior .Color = RGB(37, 72, 0) End With With condition26.Interior .Color = RGB(25, 45, 0) End With 'Select the sheet to see the final result Worksheets("Sheet1").Activate 'Result shaping rng.Select With Selection .HorizontalAlignment = xlCenter .VerticalAlignment = xlTop .Orientation = 0 .AddIndent = False .IndentLevel = 0 .ShrinkToFit = False .ReadingOrder = xlContext .MergeCells = False .ColumnWidth = 15 .RowHeight = 18 .Borders(xlInsideVertical).LineStyle = xlContinuous .Borders(xlEdgeTop).LineStyle = xlContinuous .Borders(xlEdgeBottom).LineStyle = xlContinuous .Borders(xlEdgeRight).LineStyle = xlContinuous .Borders(xlInsideHorizontal).LineStyle = xlContinuous .Borders(xlEdgeLeft).LineStyle = xlContinuous .HorizontalAlignment = xlCenter .VerticalAlignment = xlCenter .Font.Name = "Calibri" .Font.Bold = True .Font.Size = 11 .Font.Underline = False .Font.Italic = False End With 'Display result of analyzed cells MsgBox rng.Count &amp; " Cells treated : " &amp; rng.Columns.Count &amp; " Columns" &amp; " &amp; " &amp; rng.Rows.Count &amp; " Rows" End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T23:52:49.327", "Id": "464991", "Score": "2", "body": "[The Macro Recorder Curse](https://rubberduckvba.wordpress.com/2019/06/30/the-macro-recorder-curse/) can be cured (read other post too)! [RubberduckVBA](http://rubberduckvba.com/) will provide useful hints to improve code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T00:01:18.043", "Id": "464992", "Score": "0", "body": "Data belongs to databases and should be validated there. Have look at `Object-Browser` in`VBA-IDE`(on view tab) to get all members of a type (e.g Range)." } ]
[ { "body": "<ul>\n<li>To keep you <a href=\"https://clean-code-developer.com/\" rel=\"nofollow noreferrer\">DRY</a> use loops and arrays.</li>\n<li>Never (almost) use <code>.Select</code>, <code>Selection.</code> see <a href=\"https://rubberduckvba.wordpress.com/2019/06/30/the-macro-recorder-curse/\" rel=\"nofollow noreferrer\">the-macro-recorder-curse</a></li>\n<li>Avoid implicit references (e.g <code>Worksheets(\"Sheet1\").Activate</code> is <code>ActiveWorkBook.Worksheets(\"Sheet1\").Activate</code>). Use explicit refs, best Sheets <a href=\"https://rubberduckvba.wordpress.com/2019/12/19/code-name-sheet1/\" rel=\"nofollow noreferrer\">CodeName</a>, as e.g Sheetnames can be edited and wrong codename raises error at compile not run-time as missing sheetname.</li>\n</ul>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub Cell_analysis()\n Dim wb As Workbook\n Set wb = ThisWorkbook\n'Unprotect\n wb.Unprotect Password:=MDP\n Sheet1.Unprotect Password:=MDP\n\n'Define range with input box\n Dim rng As Range\n Dim DefaultRange As Range\n Dim FormatRuleInput As String\n Sheet1.Name = \"Sheet1\"\n\n If TypeName(Selection) = \"Range\" Then 'as you select sth it is valid to use Selection here\n Set DefaultRange = Selection\n Else\n Set DefaultRange = ActiveCell\n End If\n\n On Error Resume Next 'when using On Error Resume Next, always handle error or you propagate \"ignorance is bliss!\"\n Set rng = Application.InputBox( _\n Title:=\"Select Worksheet Range\", _\n Prompt:=\"Select Worksheet Range\", _\n Default:=DefaultRange.Address, _\n Type:=8)\n If Err.Number &lt;&gt; 0 Then\n 'handle error\n End If\n On Error GoTo 0\n If rng Is Nothing Then Exit Sub\n\n'Unmerge all cells\n With rng\n .UnMerge\n\n'Use following formula to retrieve cell informations\n Dim NewSheet As Worksheet\n Sheet1.Copy After:=Sheet1\n Set NewSheet = ThisWorkbook.Worksheets(Sheet1.Index + 1)\n .Cells.FormulaR1C1 = \"=CELL(\"\"Format\"\",'\" &amp; NewSheet.Name &amp; \"'!RC) &amp; CELL(\"\"Protect\"\",'\" &amp; NewSheet.Name &amp; \"'!RC) &amp; ISFORMULA('\" &amp; NewSheet.Name &amp; \"'!RC)\"\n\n 'Conditional formatting\n Dim ConditionArr(0 To 25) As FormatCondition ', condition2, condition3, condition4, condition5, condition6, condition7, condition8, condition9, condition10, condition11, condition12, condition13, condition14, condition15, condition16, condition17, condition18, condition19, condition20, condition21, condition22, condition23, condition24, condition25, condition26 As FormatCondition\n\n 'Clear existing formatting\n With .FormatConditions\n .Delete\n Dim StringArr As Variant\n StringArr = Array(\"G , 0\", \"D1 , 0\", \"D2 , 0\", \"F0 , 0\", \"F1 , 0\", \"F2 , 0\", \"F3 , 0\", \"F4 , 0\", \"F5 , 0\", \"F6 , 0\", \"F7 , 0\", \"F8 , 0\", \"F9 , 0\" _\n , \"G , 1\", \"D1 , 1\", \"D2 , 1\", \"F1 , 1\", \"F1 , 1\", \"F2 , 1\", \"F3 , 1\", \"F4 , 1\", \"F5 , 1\", \"F6 , 1\", \"F7 , 1\", \"F8 , 1\", \"F9 , 1\")\n 'List conditions\n Dim n As Long\n For n = 0 To UBound(ConditionArr) - 1\n Set ConditionArr(n) = .Add(xlTextString, TextOperator:=xlContains, String:=StringArr(n))\n Next n\n\n Dim ColorArr As Variant\n 'conditional formatting options\n ColorArr = Array(RGB(255, 255, 255), RGB(153, 204, 255), RGB(102, 178, 255), RGB(229, 255, 204), RGB(204, 255, 153), RGB(178, 255, 102), RGB(153, 255, 51) _\n , RGB(128, 218, 0), RGB(102, 204, 0), RGB(76, 153, 0), RGB(51, 102, 0), RGB(37, 72, 0), RGB(25, 45, 0) _\n , RGB(255, 255, 255), RGB(153, 204, 255), RGB(102, 178, 255), RGB(229, 255, 204), RGB(204, 255, 153), RGB(178, 255, 102), RGB(153, 255, 51) _\n , RGB(128, 218, 0), RGB(102, 204, 0), RGB(76, 153, 0), RGB(51, 102, 0), RGB(37, 72, 0), RGB(25, 45, 0))\n For n = 0 To UBound(ColorArr) - 1\n With ConditionArr(n)\n .Interior.Color = ColorArr(n)\n If n &lt; 13 Then\n .Font.ColorIndex = 3\n End If\n End With\n Next n\n End With\n\n'Select the sheet to see the final result\n\n Sheet1.Activate\n\n 'Result shaping\n\n .HorizontalAlignment = xlCenter\n .VerticalAlignment = xlTop\n .Orientation = 0\n .AddIndent = False\n .IndentLevel = 0\n .ShrinkToFit = False\n .ReadingOrder = xlContext\n .MergeCells = False\n .ColumnWidth = 15\n .RowHeight = 18\n .Borders(xlInsideVertical).LineStyle = xlContinuous\n .Borders(xlEdgeTop).LineStyle = xlContinuous\n .Borders(xlEdgeBottom).LineStyle = xlContinuous\n .Borders(xlEdgeRight).LineStyle = xlContinuous\n .Borders(xlInsideHorizontal).LineStyle = xlContinuous\n .Borders(xlEdgeLeft).LineStyle = xlContinuous\n .HorizontalAlignment = xlCenter\n .VerticalAlignment = xlCenter\n .Font.Name = \"Calibri\"\n .Font.Bold = True\n .Font.Size = 11\n .Font.Underline = False\n .Font.Italic = False\n End With\n\n'Display result of analyzed cells\n MsgBox rng.Count &amp; \" Cells treated : \" &amp; rng.Columns.Count &amp; \" Columns\" &amp; \" &amp; \" &amp; rng.Rows.Count &amp; \" Rows\"\n\nEnd Sub\n</code></pre>\n\n<p>Maybe not much faster, but far better readable, code shrunk to 40%</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T22:38:38.967", "Id": "466089", "Score": "1", "body": "This use of arrays feels awkward and unwarranted. It also constrains mandates the order of the formatting because of the static number `13` for the element position. Truth be told though, I did this same before learning about parameterizing methods, as included in my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T23:32:09.583", "Id": "466092", "Score": "0", "body": "@IvenBach I agree! Focused too much on not repeating, Extracting the formating to a method, is far less error prone and far easier to understand (what should be main goal when writing code).." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T02:12:59.477", "Id": "237197", "ParentId": "237186", "Score": "2" } }, { "body": "<p>Having <code>Option Explicit</code> is a great start :+1: for that alone!</p>\n\n<hr>\n\n<p>Your Const <code>MDP</code> doesn't need to be declared outside your Sub. In fact it should be a local variable to that Sub as it's only used there. You unprotect the ActiveSheet &amp; ActiveWorkbook but never reprotect that. Feels like a possible oversight.</p>\n\n<hr>\n\n<p>Explicitly declare your <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/sub-statement\" rel=\"nofollow noreferrer\">Sub statement</a>s with <code>Public</code> or <code>Private</code>. If you don't declare this it is implicitly <code>Public</code>. Make your intent clear by including it.</p>\n\n<hr>\n\n<p>Comments. I did the same thing when I first started with VBA. Code should be self documenting. Write code in such a way that it is self evident <em>what</em> is occurring. Then if need you to explain <em>why</em> something is done a specific way a comment is appropriate. Otherwise the comment is noise. <code>'Unmerge all cells</code> is self evident with <code>rangeVariable.UnMerge</code> the comment is restating what was already stated.</p>\n\n<p>If you have a comment that's explaining <em>what</em> is being done, like a comment banner, then that is an indicator you should break that logical group of code into its own Sub/Function (aka Member). This increases the abstraction layer and makes the code more self documenting.</p>\n\n<hr>\n\n<p>Declare your variables just before using them. This lets you realize that <code>Dim FormatRuleInput As String</code> is never referenced anywhere and should be deleted.</p>\n\n<p>Use descriptive variable names. <code>rng</code> doesn't help specify what it is whereas <code>formatConditionsArea</code> tells me you're working with FormatConditions.</p>\n\n<p>Declare variables on their own individual line. <code>Dim condition1, ... , condition26 As FormatCondition</code> has only the last variable <code>condition26</code> as a FormatCondition. You can see this behavior by displaying the Locals window from the menu at the top Edit>Locals Window then step into/through the code with <code>F8</code>.</p>\n\n<p>To remedy this eliminate them all together. You can use a <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/with-statement\" rel=\"nofollow noreferrer\">With statement</a> to hold the variable reference while you assign the properties. Removes the need for the variable altogether.</p>\n\n<pre><code>With rng.FormatConditions.Add(xlTextString, TextOperator:=xlContains, String:=\"G , 0\")\n .Interior.Color = RGB(255, 255, 255)\n .Font.ColorIndex = 3\nEnd With\n</code></pre>\n\n<p>Then notice that you're doing the same thing again and again. Extract this into a dedicated sub with parameters. The refactored <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/sub-statement\" rel=\"nofollow noreferrer\">Sub</a> below includes the use of the <a href=\"https://docs.microsoft.com/en-us/office/vba/language/concepts/getting-started/understanding-named-arguments-and-optional-arguments\" rel=\"nofollow noreferrer\">Optional keyword</a>. The first 3 parameters are required and the last is optional (self documenting code example right here). The use of the <code>IsMissing</code> function mandates that <code>fontColorIndex</code> type is a <code>Variant</code>.</p>\n\n<pre><code>Private Sub ApplyConditionalFormattingTo(ByVal formatArea As Range, _\n ByVal checkForValue As String, _\n ByVal interiorColor As Long, _\n Optional ByVal fontColorIndex As Variant)\n With formatArea.FormatConditions.Add(XlFormatConditionType.xlTextString, TextOperator:=XlContainsOperator.xlContains, String:=checkForValue)\n .Interior.Color = interiorColor\n\n If Not IsMissing(FontColorIndex) Then\n .Font.ColorIndex = FontColorIndex\n End If\n End With\nEnd Sub\n</code></pre>\n\n<p>Then supply arguments to those parameters. This cleans up the code a lot. A <a href=\"https://docs.microsoft.com/en-us/office/vba/Language/Reference/User-Interface-Help/const-statement\" rel=\"nofollow noreferrer\">Const statement</a> is used so that if the need arises you change it once and all uses of it update.</p>\n\n<pre><code>Const FontColorIndex As Long = 3\nApplyConditionalFormattingTo rng, \"G , 0\", RGB(255, 255, 255), FontColorIndex\n...\nApplyConditionalFormattingTo rng, \"F9 , 1\", RGB(25, 45, 0)\n</code></pre>\n\n<hr>\n\n<p>Create a variable to store the sheet you want to work on. Then work off that variable.</p>\n\n<pre><code>Dim formatSheet As Worksheet\nSet formatSheet = ActiveSheet\nDim formatRuleInput As String\nformatSheet.Name = \"Sheet1\"\n</code></pre>\n\n<p>Later after you copy the sheet you can activate the sheet you were formatting with <code>formatSheet.Activate</code>. Are you making a copy of the worksheet in case something messes up? If so, explicitly mark the copied sheet as such. If not then this copy just feels out of place.</p>\n\n<p>You want to avoid using <code>someVariable.Select</code> followed by <code>Selection.AnyMember</code> as it's almost never required. This occurred because you used the macro recorder. Replace</p>\n\n<pre><code>Worksheets(\"Sheet1\").Activate\nrng.Select\nWith Selection\n .HorizontalAlignment = xlCenter\n</code></pre>\n\n<p>with the code below. Directly connect them together as <code>someVariable.AnyMember</code> to eliminate this selecting.</p>\n\n<pre><code>formatSheet.Activate\nWith addConditionsArea\n .HorizontalAlignment = xlCenter\n</code></pre>\n\n<p>Within the with block there are a lot of properties that likely don't need to be there. The macro recorder does not generate efficient code and will usually include properties you don't actually want/need. Review each member in that with block and remove those you don't need.</p>\n\n<p>A example of the macro recorders inefficiency is </p>\n\n<pre><code>.Borders(xlEdgeTop).LineStyle = xlContinuous\n.Borders(xlEdgeBottom).LineStyle = xlContinuous\n.Borders(xlEdgeRight).LineStyle = xlContinuous\n.Borders(xlEdgeLeft).LineStyle = xlContinuous\n</code></pre>\n\n<p>which can be replaced with</p>\n\n<pre><code>.BorderAround XlLineStyle.xlContinuous\n</code></pre>\n\n<hr>\n\n<p>Putting everything together.</p>\n\n<pre><code>Option Explicit\n\nPublic Sub CellAnalysis()\n Const MDP As String = \"PASSWORD\"\n ActiveSheet.Unprotect Password:=MDP\n ActiveWorkbook.Unprotect Password:=MDP\n\n Dim formatSheet As Worksheet\n Set formatSheet = ActiveSheet\n Dim FormatRuleInput As String\n formatSheet.Name = \"Sheet1\"\n\n Dim defaultRange As Range\n If TypeName(Selection) = \"Range\" Then\n Set defaultRange = Selection\n Else\n Set defaultRange = ActiveCell\n End If\n\n On Error Resume Next\n Dim formatConditionsArea As Range\n Set formatConditionsArea = Application.InputBox( _\n Title:=\"Select Worksheet Range\", _\n Prompt:=\"Select Worksheet Range\", _\n Default:=defaultRange.Address, _\n Type:=8)\n\n On Error GoTo 0\n If formatConditionsArea Is Nothing Then Exit Sub\n\n formatConditionsArea.UnMerge\n\n 'Use following formula to retrieve cell informations\n formatSheet.Copy After:=Sheets(1)\n formatConditionsArea.Cells.FormulaR1C1 = \"=CELL(\"\"Format\"\",'Sheet1 (2)'!RC)&amp;\"\" , \"\"&amp;CELL(\"\"Protect\"\",'Sheet1 (2)'!RC)&amp;\"\" , \"\"&amp;ISFORMULA('Sheet1 (2)'!RC)\"\n\n formatConditionsArea.FormatConditions.Delete\n\n Const fontColorIndex As Long = 3\n ApplyConditionalFormattingTo formatConditionsArea, \"G , 0\", RGB(255, 255, 255), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"D1 , 0\", RGB(153, 204, 255), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"D2 , 0\", RGB(102, 178, 255), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"F0 , 0\", RGB(229, 255, 204), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"F1 , 0\", RGB(204, 255, 153), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"F2 , 0\", RGB(178, 255, 102), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"F3 , 0\", RGB(153, 255, 51), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"F4 , 0\", RGB(128, 218, 0), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"F5 , 0\", RGB(102, 204, 0), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"F6 , 0\", RGB(76, 153, 0), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"F7 , 0\", RGB(51, 102, 0), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"F8 , 0\", RGB(37, 72, 0), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"F9 , 0\", RGB(25, 45, 0), fontColorIndex\n ApplyConditionalFormattingTo formatConditionsArea, \"G , 1\", RGB(255, 255, 255)\n ApplyConditionalFormattingTo formatConditionsArea, \"D1 , 1\", RGB(153, 204, 255)\n ApplyConditionalFormattingTo formatConditionsArea, \"D2 , 1\", RGB(102, 178, 255)\n ApplyConditionalFormattingTo formatConditionsArea, \"F0 , 1\", RGB(229, 255, 204)\n ApplyConditionalFormattingTo formatConditionsArea, \"F1 , 1\", RGB(204, 255, 153)\n ApplyConditionalFormattingTo formatConditionsArea, \"F2 , 1\", RGB(178, 255, 102)\n ApplyConditionalFormattingTo formatConditionsArea, \"F3 , 1\", RGB(153, 255, 51)\n ApplyConditionalFormattingTo formatConditionsArea, \"F4 , 1\", RGB(128, 218, 0)\n ApplyConditionalFormattingTo formatConditionsArea, \"F5 , 1\", RGB(102, 204, 0)\n ApplyConditionalFormattingTo formatConditionsArea, \"F6 , 1\", RGB(76, 153, 0)\n ApplyConditionalFormattingTo formatConditionsArea, \"F7 , 1\", RGB(51, 102, 0)\n ApplyConditionalFormattingTo formatConditionsArea, \"F8 , 1\", RGB(37, 72, 0)\n ApplyConditionalFormattingTo formatConditionsArea, \"F9 , 1\", RGB(25, 45, 0)\n\n 'Select the sheet to see the final result\n formatSheet.Activate\n With formatConditionsArea\n .HorizontalAlignment = xlCenter\n .VerticalAlignment = xlTop\n .ColumnWidth = 15\n .RowHeight = 18\n .BorderAround XlLineStyle.xlContinuous\n .Borders(xlInsideVertical).LineStyle = xlContinuous\n .Borders(xlInsideHorizontal).LineStyle = xlContinuous\n .HorizontalAlignment = xlCenter\n .VerticalAlignment = xlCenter\n .Font.Bold = True\n End With\n\n 'Display result of analyzed cells\n MsgBox formatConditionsArea.Count &amp; \" Cells treated : \" &amp; formatConditionsArea.Columns.Count &amp; \" Columns\" &amp; \" &amp; \" &amp; formatConditionsArea.Rows.Count &amp; \" Rows\"\nEnd Sub\n\nPrivate Sub ApplyConditionalFormattingTo(ByVal formatArea As Range, _\n ByVal checkForValue As String, _\n ByVal interiorColor As Long, _\n Optional ByVal fontColorIndex As Variant)\n With formatArea.FormatConditions.Add(XlFormatConditionType.xlTextString, _\n TextOperator:=XlContainsOperator.xlContains, _\n String:=checkForValue)\n .Interior.Color = interiorColor\n\n If Not IsMissing(fontColorIndex) Then\n .Font.ColorIndex = fontColorIndex\n End If\n End With\nEnd Sub\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T12:29:02.827", "Id": "466134", "Score": "0", "body": "The `'Select the sheet to see the final result` and `formatSheet.Activate` lines are a _good_ example of a **why** comment. When I was reading through the write up, I my initial thought was \"There's no need to `formatSheet.Activate`!\" but the **why** comment let me know that there was a reason for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T00:22:28.057", "Id": "466390", "Score": "0", "body": "Hey, thank you for these detailed explanations ! \nHelped me a lot understanding what was going on" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T22:26:01.720", "Id": "237666", "ParentId": "237186", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T20:50:25.327", "Id": "237186", "Score": "4", "Tags": [ "vba", "excel" ], "Title": "VBA to retrieve/display information of cells in excel" }
237186
<p>The code below is a custom array class that handles indexing, copying, printing, etc. explicitly.<br> Is there a better approach for specification (declaration and definition) of the assignment operator (with swap function) and the index [] operator?<br> Furthermore, are there any improvements that can be made to the other methods to improve functionality?</p> <pre><code>// Overloading operators for Array class #include&lt;iostream&gt; #include&lt;cstdlib&gt; using namespace std; // A class to represent an integer array class Array{ private: int *ptr; int size; public: Array(int *p = NULL, int s = 0); Array(const Array&amp;); ~Array(); Array&amp; operator= (Array); // Overloading [] operator to access elements in array style int &amp;operator[] (int); // Utility function to print contents void print() const; friend void swap(Array&amp; first, Array&amp; second);}; // Implementation of [] operator. This function must return a // reference as array element can be put on left side int &amp;Array::operator[](int index){ if (index &gt;= size || index &lt; 0){ throw out_of_range("Index out of Range error"); } return ptr[index]; } // constructor for array class Array::Array(int *p, int s){ size = s; ptr = NULL; if (s != 0){ ptr = new int[s]; for (int i = 0; i &lt; s; i++) ptr[i] = p[i];} } // destructor for array class Array::~Array(){ delete[] ptr; ptr = NULL;} // copy constructor for array class Array::Array(const Array&amp; A) { size = A.size; ptr = new int[size]; for (int i = 0; i &lt; size; i++) ptr[i] = A.ptr[i];} //swap friend function of assignment operator void swap(Array&amp; first, Array&amp; second){ using std::swap; swap(first.size, second.size); swap(first.ptr, second.ptr);} //Assignment operator for array class Array&amp; Array::operator=(Array other){ swap(*this, other); return *this;} //print function for array elements void Array::print() const{ cout &lt;&lt; "{"; for(int i = 0; i &lt; size; i++) cout&lt;&lt;ptr[i]&lt;&lt;" "; cout&lt;&lt;"}"&lt;&lt;endl;} // Driver program to test above methods int main() { int a[] = {1, 2, 3, 4, 5, 6}; Array arr1(a, 6); arr1[0] = 7; arr1.print(); Array arr2 = arr1; arr2.print(); arr1[-1] = 4; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T08:37:05.060", "Id": "465525", "Score": "0", "body": "Welcome to Code Review! Your edit invalidated an answer, which breaks the question-and-answer nature of this site. See [What should I do when someone answers my question?](/help/someone-answers)." } ]
[ { "body": "<p>This isn't really a code review so much as help on how to get this to compile. </p>\n\n<ul>\n<li><code>Array::Array(int *p = NULL, int s = 0){</code> default parameters go on the declaration, not the definition.*</li>\n<li><code>Array::Array&amp; operator=(Array other){</code> Qualify the <code>operator</code> with <code>Array::</code>, not the return type. You're not returning an <code>Array::Array</code>**, you're defining the <code>operator=</code> member function of <code>Array</code></li>\n<li><code>void Array::swap(Array&amp; first, Array&amp; second){</code> swap is not a member of array, it's a friend. Remove the <code>Array::</code></li>\n</ul>\n\n<p>*This is because the <em>client</em> (caller) to the method needs to know what the defaults are supposed to be, since default parameters are mostly a syntactic shortcut. If you put the defaults into the definition (e.g. a cpp/.o file), a client which includes the header cannot see the definition and thus cannot use them. In other words, there exists no <code>Array::Array()</code> constructor right now, there's only the <code>Array::Array(int *, int)</code>, but through C++ magic it can look as though <code>Array::Array()</code> is being called. </p>\n\n<p>** An <code>Array::Array</code> type is impossible because you can't name a child type the same as its parent type. It would be ambiguous with the constructor.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T23:37:47.617", "Id": "464989", "Score": "0", "body": "Thanks for the feedback! Is it possible to avoid the Aborted (core dumped) message when the out_of_range error is thrown?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T23:47:42.917", "Id": "464990", "Score": "0", "body": "Furthermore, how would one implement a try-catch statement for invalid index values?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T00:02:08.077", "Id": "464993", "Score": "1", "body": "I would argue that you should not throw an exception on [], but that's debatable. My reasoning is that [] is canonically a dangerous operation in C++, and should be semantically thought of as a dereference of a potentially out-of-bounds address, usable *only* if you're absolutely certain it will not fail. This type of dangerous operation is integral to C++ since there's no convenient layer below it to handle it better. A method call like `GetAt(IndexType)` or something might throw by testing the bounds -- not by catching another exception, the class knows whether the argument is valid or not." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T23:14:50.057", "Id": "237193", "ParentId": "237192", "Score": "2" } }, { "body": "<p>Don't <code>using namespace std;</code> - especially not in a header, where it inflicts the harm on every source that includes the header.</p>\n\n<p>Prefer <code>nullptr</code> to <code>NULL</code>, because the former is more strongly typed.</p>\n\n<p>Use <code>std::size_t</code> for indexing, rather than <code>int</code>.</p>\n\n<p>When overloading <code>operator[]</code>, it's usually necessary to provide two versions:</p>\n\n<pre><code>int&amp; operator[](std::size_t);\nint const&amp; operator[](std::size_t) const;\n</code></pre>\n\n<p>Usually, <code>operator[]</code> doesn't throw. Provide a separate \"checked\" interface if your clients need that as well. That's normally named <code>at()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T11:43:00.627", "Id": "237226", "ParentId": "237192", "Score": "1" } } ]
{ "AcceptedAnswerId": "237193", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-12T22:45:20.847", "Id": "237192", "Score": "0", "Tags": [ "c++", "array", "reinventing-the-wheel", "constructor", "overloading" ], "Title": "Array indexing with copy constructor, assignment operator and index operator overload" }
237192
<p>I have recently started coding in c++ and have made a simple console application. When executed the program asks the user to position their cursor wherever they want continuous repeating clicks, after 7 seconds it then asks the user to set an interval for the clicks. Since I am fairly new I am wondering if there is anything I could have done better to optimise the performance of the code or any other tips and tricks I can use, much appreciated</p> <p>my code is (main.cpp):</p> <pre><code>#include &lt;iostream&gt; #include &lt;Windows.h&gt; using namespace std; void leftClick(double mouse_x, double mouse_y){ INPUT input; input.type=INPUT_MOUSE; input.mi.dx=(mouse_x * 65536) / GetSystemMetrics(SM_CXSCREEN) + 1; input.mi.dy=(mouse_y * 65536) / GetSystemMetrics(SM_CYSCREEN) + 1; input.mi.dwFlags=(MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_MOVE|MOUSEEVENTF_LEFTDOWN|MOUSEEVENTF_LEFTUP); input.mi.mouseData=0; input.mi.time=0; SendInput(1,&amp;input,sizeof(INPUT)); } int main(){ cout &lt;&lt; "Place the cursor where you want to click..." &lt;&lt; endl; Sleep(7000); POINT p; GetCursorPos(&amp;p); cout &lt;&lt; "Set the interval to click: "; int cinterval {0}; cin &gt;&gt; cinterval; cout &lt;&lt; "Current Interval: " &lt;&lt; cinterval * 1000 &lt;&lt; endl; while(true){ leftClick(p.x, p.y); Sleep(cinterval * 1000); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T02:22:06.300", "Id": "465001", "Score": "0", "body": "(Tricks - when coding, know them, but keep your code simple.)" } ]
[ { "body": "<p>Here are some suggestions you can use to improve your code.</p>\n\n<h1>Formatting</h1>\n\n<p>Insert a space before a <code>{</code> that starts a compound statement and does not go on a separate line; e.g., instead of <code>int main(){</code>, write</p>\n\n<pre><code>int main() {\n</code></pre>\n\n<p>or</p>\n\n<pre><code>int main()\n{\n</code></pre>\n\n<p>Place a space after a comma and after a control word (<code>while</code>, etc.): <code>SendInput(1, &amp;input, sizeof(INPUT))</code> and <code>while (true) {</code>.</p>\n\n<p>Place two spaces around the <code>=</code> operator.</p>\n\n<p>The indentation level of the <code>leftClick</code> function should be reduced to 4 spaces to keep consistent with <code>main</code>.</p>\n\n<h1>Naming</h1>\n\n<p>In C++, functions are usually named in <code>snake_case</code> instead of <code>camelCase</code>. This is subjective though.</p>\n\n<h1>Standard library usage</h1>\n\n<p>Please try to avoid <code>using namespace std;</code> because it is considered bad practice. The contents of the C++ standard library are put in a special namespace to avoid polluting the global namespace and causing name clashes. The <code>std</code> namespace is not intended for use with using directives (in general). <code>using namespace std;</code> forces you to avoid standard names and invalidates the purpose of the <code>std</code> namespace. See <a href=\"https://stackoverflow.com/q/1452721\">Why is “using namespace std;” considered bad practice?</a>.</p>\n\n<p><code>std::endl</code> is generally inferior to <code>\\n</code>, but it is necessary in this case because of flushing requirements. Good.</p>\n\n<p>Currently, your code isn't clear in terms of unit of time. Is the interval intended to be in seconds, milliseconds, or microseconds? The standard <code>&lt;chrono&gt;</code> library solves this problem. And instead of <code>Sleep</code>, use <code>std::this_thread::sleep_for</code> from <code>&lt;thread&gt;</code>, which plays well with <code>&lt;chrono&gt;</code>:</p>\n\n<pre><code>using namespace std::chrono_literals;\n\nstd::cout &lt;&lt; \"Place the cursor where you want to click ...\" &lt;&lt; std::endl;\nstd::this_thread::sleep_for(7s); // NB: valid syntax!\n</code></pre>\n\n<p>Indicate your presumed unit of time:</p>\n\n<pre><code>cout &lt;&lt; \"Set the interval to click (ms): \";\n\nint cinterval {0};\ncin &gt;&gt; cinterval;\n\n// ...\nstd::this_thread::sleep_for(std::chrono::milliseconds{cinterval});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-09T09:30:26.150", "Id": "495978", "Score": "0", "body": "I would also suggest setting a minimum interval time to 16 milliseconds, i.e. once per frame at 60 frames per second. That way you don't flood the input queue and cause the target application to lock up." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T03:14:32.000", "Id": "237199", "ParentId": "237195", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T01:16:39.140", "Id": "237195", "Score": "5", "Tags": [ "c++", "performance", "windows" ], "Title": "Windows autoclicker with a console interface" }
237195
<p>Long one here, but election transparency is worth a rough code review.</p> <p>The Iowa Caucuses have numerous errors in delegate awards because they did their computations manually (their closed-source app failed).</p> <p>In response I released a Swift "Caucus Report" iOS app for the upcoming Nevada caucuses. It is open sourced at <a href="https://github.com/darrellroot/CaucusReport" rel="nofollow noreferrer">https://github.com/darrellroot/CaucusReport</a></p> <p>Most of the algorithm for calculating delegates is documented at <a href="https://nvdems.com/wp-content/uploads/2020/02/Caucus-Memo_-Delegate-Count-Scenarios-and-Tie-Breakers.pdf" rel="nofollow noreferrer">https://nvdems.com/wp-content/uploads/2020/02/Caucus-Memo_-Delegate-Count-Scenarios-and-Tie-Breakers.pdf</a></p> <p>The one other piece of data required (from the delegate selection plan) is viability percentage:</p> <ul> <li>For precincts electing 2 delegates, viability is 25% of voting attendees + early voters (rounded up)</li> <li>For precincts electing 3 delegates, viability is 1/6th of voting attendees + early voters (rounded up)</li> <li>For precincts electing 4 delegates, viability is 15% of voting attendees + early voters (rounded up)</li> </ul> <p>(they have precincts with 1 delegate but don't document a viability percentage for 1-delegate precincts...so my app refuses to deal with that case at this time)</p> <p>Below is my summary of the procedure and documented algorithm, but ambitious reviewers should go to the source.</p> <p>Here's the procedure for the caucus:</p> <ol> <li>Early voters already expressed their 1st, 2nd, and 3rd preference</li> <li>Attendees will be counted and a viability number of votes announced</li> <li>Attendees will choose their candidate (1st alignment)</li> <li>Candidates with insufficient votes (total of early and attendee) will be announced as non-viable. Attendees have the option of moving to another candidate, or staying with a non-viable candidate.</li> <li>Early voters for non-viable candidates have their votes reassigned to their 2nd or 3rd choice, if they are viable.</li> <li>Early and attendee are counted (2nd alignment)</li> </ol> <p>The algorithm for awarding delegates based on the 2nd alignment vote is as follows: (I really recommend reviewing "caucus math" at <a href="https://nvdems.com/wp-content/uploads/2020/02/Caucus-Memo_-Delegate-Count-Scenarios-and-Tie-Breakers.pdf" rel="nofollow noreferrer">https://nvdems.com/wp-content/uploads/2020/02/Caucus-Memo_-Delegate-Count-Scenarios-and-Tie-Breakers.pdf</a>).</p> <ul> <li>A "caucus formula" is calculated: NumberOfVotes x precinctDelegates / totalParticipants Numbers >= .5 are rounded up. Numbers &lt; .5 are rounded down. That's the number of delegates for each candidate with the following exceptions:</li> <li>Unallocated Delegates​: I​f any delegates are remaining ​after rounding​, give out the extra delegate(s) starting with the candidate that is closest to rounding up to the next whole number.</li> <li>Too Many Delegates: If you've given out more delegates than your precinct was allocated ​after rounding​, subtract the extra delegate(s) starting with the candidate that is furthest away from rounding up to the next whole number.</li> <li>You cannot take away a viable group’s only delegate (this may result in more delegates being assigned than were planned for the precinct)</li> <li>Note: If there is an exact decimal tie, use a game of chance to break the tie.</li> </ul> <p>That's an awful algorithm, but I've translated it to the following:</p> <ol> <li>Calculate the "caucus formula" for each candidate.</li> <li>Assign one delegate to each viable candidate, subtracting 1.0 from the "caucus formula" each time you assign a delegate.</li> <li>If more delegates are to be assigned, give them to the highest remaining "caucus formula" (from viable candidates only), decrementing the formula by 1.0. Repeat until all delegates are assigned.</li> <li>If there is a caucus formula tie with insufficient delegates to assign, stop and document the tie for random card draw.</li> </ol> <p>Here's an example of a test case using the model (I have successful test cases for every example in the "Caucus Math" document):</p> <pre><code>func test4c() { let model = Model() model.precinctDelegates = 8 model.totalAttendees = 100 model.attendeeVote2["Bennet"] = 15 model.attendeeVote2["Biden"] = 45 model.attendeeVote2["Bloomberg"] = 20 model.attendeeVote2["Booker"] = 20 let (delegates, coinToss) = model.calculateDelegates() XCTAssert(delegates["Bennet"] == 1) XCTAssert(delegates["Biden"] == 3) XCTAssert(delegates["Bloomberg"] == 1) XCTAssert(delegates["Booker"] == 1) XCTAssert(model.viabilityPercentage == 0.15) XCTAssert(model.delegateFactor(candidate: "Bennet") == 1.2) XCTAssert(model.delegateFactor(candidate: "Biden") == 3.6) XCTAssert(model.delegateFactor(candidate: "Bloomberg") == 1.6) XCTAssert(model.delegateFactor(candidate: "Booker") == 1.6) XCTAssert(coinToss == "Draw cards for 2 delegates between Biden Bloomberg Booker\n") } </code></pre> <p>And here's the model. All the "stored properties" are near the top. Everything below the "extension" is a computed property with no stored data. The delegate computation is near the bottom.</p> <pre><code>// Model.swift // CaucusReport // // Created by Darrell Root on 2/9/20. // Copyright © 2020 net.networkmom. All rights reserved. // import Foundation class Model: ObservableObject, Codable { static let nevadaCounties = ["Test","Carson City", "Churchill","Clark","Douglas","Elko","Esmeralda","Eureka","Humboldt","Lander","Lincoln","Lyon","Mineral","Nye","Pershing","Storey","Washoe","White Pine"] static let originalCandidates = ["Bennet","Biden","Bloomberg","Booker","Buttigieg","Delaney","Gabbard","Kloubuchar","Patrick","Sanders","Steyer","Warren","Williamson","Yang","Uncommitted","Write-Ins"] @Published var realMode = false @Published var county: String = "Test" @Published var precinct: String = "" @Published var precinctDelegates: Int = 2 { didSet { if precinctDelegates &lt; 2 { precinctDelegates = 2 } } } @Published var totalAttendees = 0 { didSet { if totalAttendees &lt; 0 { totalAttendees = 0 } } } @Published var totalEarlyVoters = 0 { didSet { if totalEarlyVoters &lt; 0 { totalEarlyVoters = 0 } } } @Published var candidates = Model.originalCandidates @Published var earlyVote1: [String: Int] = [:] { didSet { for key in earlyVote1.keys { if earlyVote1[key]! &lt; 0 { earlyVote1[key] = 0 } } } } @Published var attendeeVote1: [String: Int] = [:] { didSet { for key in attendeeVote1.keys { if attendeeVote1[key]! &lt; 0 { attendeeVote1[key] = 0 } } } } @Published var earlyVote2: [String: Int] = [:] { didSet { for key in earlyVote2.keys { if earlyVote2[key]! &lt; 0 { earlyVote2[key] = 0 } } } } @Published var attendeeVote2: [String: Int] = [:] { didSet { for key in attendeeVote2.keys { if attendeeVote2[key]! &lt; 0 { attendeeVote2[key] = 0 } } } } init() { for candidate in candidates { earlyVote1[candidate] = 0 attendeeVote1[candidate] = 0 earlyVote2[candidate] = 0 attendeeVote2[candidate] = 0 } } enum CodingKeys: CodingKey { case realMode case county case precinct case precinctDelegates case candidates case totalAttendees case totalEarlyVoters case earlyVote1 case earlyVote2 case attendeeVote1 case attendeeVote2 } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) realMode = try container.decode(Bool.self, forKey: .realMode) county = try container.decode(String.self, forKey: .county) precinct = try container.decode(String.self, forKey: .precinct) precinctDelegates = try container.decode(Int.self, forKey: .precinctDelegates) candidates = try container.decode([String].self, forKey: .candidates) totalAttendees = try container.decode(Int.self, forKey: .totalAttendees) totalEarlyVoters = try container.decode(Int.self, forKey: .totalEarlyVoters) earlyVote1 = try container.decode([String: Int].self, forKey: .earlyVote1) earlyVote2 = try container.decode([String: Int].self, forKey: .earlyVote2) attendeeVote1 = try container.decode([String: Int].self, forKey: .attendeeVote1) attendeeVote2 = try container.decode([String: Int].self, forKey: .attendeeVote2) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(realMode, forKey: .realMode) try container.encode(county, forKey: .county) try container.encode(precinct, forKey: .precinct) try container.encode(precinctDelegates, forKey: .precinctDelegates) try container.encode(totalAttendees, forKey: .totalAttendees) try container.encode(totalEarlyVoters, forKey: .totalEarlyVoters) try container.encode(candidates, forKey: .candidates) try container.encode(earlyVote1, forKey: .earlyVote1) try container.encode(earlyVote2, forKey: .earlyVote2) try container.encode(attendeeVote1, forKey: .attendeeVote1) try container.encode(attendeeVote2, forKey: .attendeeVote2) } } extension Model { // everything below here are computed properties, no permanent storage func saveData() { let encoder = JSONEncoder() if let encoded = try? encoder.encode(self) { let defaults = UserDefaults.standard defaults.set(encoded, forKey: "SavedModel") debugPrint("saved model") } else { debugPrint("failed to save model") } } var totalRegistrations: Int { return totalAttendees + totalEarlyVoters } var viability: Int { let doubleViability = (Double(totalAttendees + totalEarlyVoters) * viabilityPercentage).rounded(.up) return Int(doubleViability) } func align1Total(candidate: String) -&gt; Int { return (earlyVote1[candidate] ?? 0) + (attendeeVote1[candidate] ?? 0) } func align2Total(candidate: String) -&gt; Int { return (earlyVote2[candidate] ?? 0) + (attendeeVote2[candidate] ?? 0) } var early1GrandTotal: Int { var grandTotal = 0 for candidate in self.candidates { if candidate != "Uncommitted" { grandTotal = grandTotal + (earlyVote1[candidate] ?? 0) } } return grandTotal } var early2GrandTotal: Int { var grandTotal = 0 for candidate in self.candidates { if candidate != "Uncommitted" { grandTotal = grandTotal + (earlyVote2[candidate] ?? 0) } } return grandTotal } var viableCandidates: [String] { var result: [String] = [] for candidate in candidates { if viable2(candidate: candidate) { result.append(candidate) } } return result } var attendee1GrandTotal: Int { var grandTotal = 0 for candidate in self.candidates { grandTotal = grandTotal + (attendeeVote1[candidate] ?? 0) } return grandTotal } var attendee2GrandTotal: Int { var grandTotal = 0 for candidate in self.candidates { grandTotal = grandTotal + (attendeeVote2[candidate] ?? 0) } return grandTotal } var align1GrandTotal: Int { return early1GrandTotal + attendee1GrandTotal } var align2GrandTotal: Int { return early2GrandTotal + attendee2GrandTotal } var viabilityPercentage: Double { switch self.precinctDelegates { case 2: return 0.25 case 3: return 0.166667 case 4...: return 0.15 default: debugPrint("should not get here") return 0.25 } } func viable1(candidate: String) -&gt; Bool { if candidate == "Uncommitted" { return false } if align1Total(candidate: candidate) &gt;= viability { return true } else { return false } } func viable2(candidate: String) -&gt; Bool { if candidate == "Uncommitted" { return false } if align2Total(candidate: candidate) &gt;= viability { return true } else { return false } } func reset() { realMode = false county = "" precinct = "" precinctDelegates = 2 totalAttendees = 0 totalEarlyVoters = 0 candidates = Model.originalCandidates earlyVote1 = [:] attendeeVote1 = [:] earlyVote2 = [:] attendeeVote2 = [:] for candidate in candidates { earlyVote1[candidate] = 0 attendeeVote1[candidate] = 0 earlyVote2[candidate] = 0 attendeeVote2[candidate] = 0 } } //adding write-in candidates not supported /*func addCandidate(name: String) { if candidates.contains(name) { debugPrint("already added") } else { candidates.append(name) earlyVote1[name] = 0 attendeeVote1[name] = 0 earlyVote2[name] = 0 attendeeVote2[name] = 0 } }*/ var align1Tweet: String? { var output: String = "" if self.realMode { output += "#NevadaCaucus Align1\n" } else { output += "#NevadaCaucusTest Align1\n" } output += "County \(county) precinct \(precinct) Delegates \(precinctDelegates)\n" for candidate in candidates { if align1Total(candidate: candidate) == 0 { continue } output += "\(candidate) \(align1Total(candidate: candidate))" if viable1(candidate: candidate) { output += " viable\n" } else { output += "\n" } } output += "#CaucusReportApp\n" debugPrint("tweet characters \(output.count)") return output.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) } var align2Tweet: String? { var output: String = "" if self.realMode { output += "#NevadaCaucus Align2\n" } else { output += "#NevadaCaucusTest Align2\n" } output += "County \(county) Precinct \(precinct) Delegates \(precinctDelegates)\n" output += "VOTES\n" for candidate in viableCandidates { output += "\(candidate) \(align2Total(candidate: candidate))\n" } output += delegateMessage() output += "#CaucusReportApp\n" debugPrint("tweet characters \(output.count)") return output.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) } func delegateFactor(candidate: String) -&gt; Double { guard totalRegistrations &gt; 0 else { return 0.0 } return (Double(align2Total(candidate: candidate)) * Double(precinctDelegates) / Double(totalRegistrations)).rounded(toPlaces: 4) } func calculateDelegates() -&gt; (delegates: [String:Int], coinToss: String) { var usedDelegates = 0 var candidateDelegates: [String: Int] = [:] var coinToss: String = "No card draws\n" guard viableCandidates.count &gt; 0 else { coinToss = "No viable candidates" return (delegates: candidateDelegates, coinToss: coinToss) } func remainingFactor(candidate: String) -&gt; Double { return delegateFactor(candidate: candidate) - Double(candidateDelegates[candidate]!) } func findHighestRemainingFactor() -&gt; [String] { var largestFactor = -1000.0 // initially set to low value var highestCandidates: [String] = [] for candidate in viableCandidates { if remainingFactor(candidate: candidate) &gt; largestFactor { largestFactor = remainingFactor(candidate: candidate) highestCandidates = [candidate] } else if remainingFactor(candidate: candidate) == largestFactor { highestCandidates.append(candidate) } } return highestCandidates } // initially set delegates to 0 for candidate in candidates { candidateDelegates[candidate] = 0 } // all viable candidates get 1 delegate even if that // requires more delegates than assigned to precinct for candidate in viableCandidates { candidateDelegates[candidate] = candidateDelegates[candidate]! + 1 usedDelegates = usedDelegates + 1 } // keep assigning delegates to candiates until precinct is // out of delegates. precinct might already be out // of delegates if viableCandidates.count &gt;= precinctDelegates while usedDelegates &lt; precinctDelegates { let nextWinners: [String] = findHighestRemainingFactor() if nextWinners.count &lt;= (precinctDelegates - usedDelegates) { for winner in nextWinners { candidateDelegates[winner] = candidateDelegates[winner]! + 1 usedDelegates = usedDelegates + 1 } // if we have more tied winners this round than // remaining delegages, initiate a coin toss } else { //nextWinners.count &gt; remaining delegates var winnerString = "" for winner in nextWinners { winnerString = winnerString + " \(winner)" } coinToss = "Draw cards for \(precinctDelegates - usedDelegates) delegates between\(winnerString)\n" usedDelegates = precinctDelegates } }//while return (delegates: candidateDelegates, coinToss: coinToss) } func delegateMessage() -&gt; String { var result = "DELEGATES\n" let (delegates, coinToss) = calculateDelegates() for (candidate,delegateCount) in delegates { if delegateCount &gt; 0 { result += "\(candidate) \(delegateCount)\n" } } result += coinToss return result } var validResult: Bool { if viable2(candidate: "Write-ins") { return false } if align2GrandTotal &lt;= 0 { return false } if totalRegistrations &lt;= 0 { return false } return true } var invalidMessage: String { return """ INVALID DATA DETECTED Registrations on Precinct screen could be 0 Total votes in alignment 2 could be 0 Write-ins in total could be viable (if too many write-ins, need to calculate manually) """ } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T04:48:44.813", "Id": "237201", "Score": "1", "Tags": [ "swift" ], "Title": "Swift model for the Nevada Democratic Caucuses Feb 22 2020" }
237201
<p>I am sure there will be a way to make this code simpler, can someone take a look?</p> <p>Basically what it does is:</p> <ol> <li>get <code>now</code> and <code>a week ago from now</code></li> <li>then format it to utc (i.e. <code>2020-02-04T23:18:00Z</code>)</li> <li>to enter in boto3 command as parameters</li> </ol> <pre class="lang-py prettyprint-override"><code>import datetime end_time = datetime.datetime.now() start_time = end_time - datetime.timedelta(days=7) end_time = end_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ") start_time = start_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T08:55:57.883", "Id": "465044", "Score": "3", "body": "Can you explain what and why you think this could be made simpler?" } ]
[ { "body": "<p>This is already about as simple as it can get. </p>\n\n<p>The only real simplification would be to use <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat\" rel=\"nofollow noreferrer\"><code>datetime.datetime.isoformat</code></a>, and make it into a simple function (with typing, default arguments and a doc-string). To enable reusing this function by importing it in another file, you can put the rest of the code behind a <code>if __name__ == \"__main__:</code>-guard</p>\n\n<pre><code>import datetime\nimport typing\n\ndef get_timestamps(\n end_time: datetime.datetime = None,\n delta: datetime.timedelta = datetime.timedelta(days=7),\n) -&gt; typing.Tuple[str, str]:\n \"\"\" &lt; docstring&gt; \"\"\"\n if end_time is None:\n end_time = datetime.datetime.now()\n start_time = end_time - delta\n return start_time.isoformat(), end_time.iso_format()\n\nif __name__ == \"__main__:\n end_time, start_time = get_timestamps()\n</code></pre>\n\n<p>if the <code>iso_format</code> is not what you need, you can start already by making the time format into a variable:</p>\n\n<pre><code>datetime_format = \"%Y-%m-%dT%H:%M:%S.%fZ\"\nend_time = end_time.strftime(datetime_format)\nstart_time = start_time.strftime(datetime_format)\n</code></pre>\n\n<p>This serves both as an explanation what that weird-looking string is, and prevents silly typological mistakes causing different formatting of the start and end time</p>\n\n<p>BTW, this does not include the timezone info. You need to add a <code>%z</code> for that</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T10:52:42.700", "Id": "237225", "ParentId": "237202", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T05:11:37.037", "Id": "237202", "Score": "-1", "Tags": [ "python" ], "Title": "Simple python code with datetime, datetime operation and datetime formating, I would like to make it more concise" }
237202
<p>I'm having trouble with proper naming. That issue appears when i try to apply to <a href="https://www.cs.helsinki.fi/u/luontola/tdd-2009/ext/ObjectCalisthenics.pdf" rel="nofollow noreferrer"><em>first class collection</em></a> to my class and use <a href="https://sonarcloud.io/" rel="nofollow noreferrer">sonar</a> as well:</p> <pre><code>public class Units { private final List&lt;Unit&gt; units = new ArrayList&lt;&gt;(); [...] } </code></pre> <p>Here's the problem, sonar says: </p> <blockquote> <p>A field should not duplicate the name of its containing class - <a href="https://sonarcloud.io/organizations/martinfrank-github/rules?open=java%3AS1700&amp;rule_key=java%3AS1700" rel="nofollow noreferrer">java:S1700</a> </p> </blockquote> <p>What would be the <strong>proper name</strong> for the internal representation of my list? Is sonar here just picky?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:31:38.280", "Id": "465020", "Score": "0", "body": "This question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:35:27.340", "Id": "465021", "Score": "0", "body": "would it be helpful if i would provide the whole context? actually this issue raised because i got warnings in my project on my [github-project](https://github.com/martinFrank/simpleciv/blob/master/src/main/java/com/github/martinfrank/simpleciv/game/Players.java) - see [sonar](https://sonarcloud.io/project/issues?id=martinFrank_simpleciv&open=AXAJ2oI1-dJ7i5GckLop&resolved=false&types=CODE_SMELL)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:37:43.817", "Id": "465022", "Score": "0", "body": "as i ran into that issue for several time i'm not sure how to handle that best..." } ]
[ { "body": "<p>Usually naming of a field should follow a simple approach </p>\n\n<pre><code>public class Units {\n\n private final List&lt;Unit&gt; unitList = new ArrayList&lt;&gt;();\n private final Map&lt;Integer,Unit&gt; unitMap = new HashMap&lt;&gt;();\n\n}\n</code></pre>\n\n<p>suffix your field name with the type of collection to ensure better readability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:11:42.480", "Id": "465009", "Score": "1", "body": "I have to disagree with you because it is redundant: `List <Unit> unitList = new ArrayList <> ();` The word `List` appears three times with only 5 words. You also need to rename your variable if you want to change the data type - maybe someone will forget? Variable names should [avoid disinformation](https://cleancoders.com/video-details/clean-code-episode-2)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:16:44.197", "Id": "465010", "Score": "1", "body": "i'm not sure if this would not violate *[Avoid Disinformation](https://medium.com/ltunes/what-is-clean-code-naming-conventions-part-1-426d383eb85d)* - sou should not use the type of a variable for it's name (you can't change the type easily afterwards)..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:24:55.947", "Id": "465014", "Score": "0", "body": "as mentioned in link to *first class collection*: **Application of this rule is simple: any class that contains a collection should contain no other\nmember variables**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:26:11.537", "Id": "465015", "Score": "0", "body": "*hungarian notation* is not a preferred choice in java" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:26:26.813", "Id": "465017", "Score": "0", "body": "since your answer provides much helpful hints for others i'll +1 it..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T08:29:43.170", "Id": "465030", "Score": "0", "body": "(@MartinFrank should that read *provoked*?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T08:59:25.203", "Id": "465047", "Score": "0", "body": "@greybeard sometimes being a bad example is helpful for other - as does that question at all seem to be a bad idea... would it be helpful to delete that question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:05:39.137", "Id": "465051", "Score": "1", "body": "(@MartinFrank The question raises an issue I think worth discussing here in a way frowned upon as *hypethetical* (the full text being ***too** hypothetical to be meaningfully reviewed*). The question works for me.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:14:05.210", "Id": "465056", "Score": "0", "body": "@greybeard thanks for appreciating! as mentioned in my comments i do run into that issue again and again and wanted some actual help! there was no interest in an hypothetical question!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:52:38.870", "Id": "465064", "Score": "1", "body": "Wow came back to see this awesome comment conversation. This is an eye-opener for me in terms of naming something as simple as a variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T10:16:59.713", "Id": "465069", "Score": "0", "body": "thank you again for your answer =) on first glance it seem so easy ^_^ now i'm lost, ahahaha" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T06:38:58.217", "Id": "237207", "ParentId": "237205", "Score": "1" } }, { "body": "<h1>Class Names that are Plural</h1>\n\n<p>I don't know if it's a convention, but for example the <code>java.util</code> package contains two or more classes like<code>Arrays</code> and <code>Collections</code> that only provide<code>static</code> util methods.</p>\n\n<p><a href=\"https://www.cs.uct.ac.za/mit_notes/software/htmls/ch05s09.html\" rel=\"nofollow noreferrer\">UML</a> recommends that class names be written in singular.</p>\n\n<h1>Variable Scope</h1>\n\n<p>The scope of the <code>List &lt;Unit&gt; units</code> field is tied to its class and should be understood in its context.</p>\n\n<p>If you renamed it to <code>collection</code> because of the context, it is still clear that it contains all the units. It even has an advantage: If you rename your class from <code>Units</code> to <code>Chunks</code>, you do not have to touch the variable <code>collection</code> because it do not follow the <a href=\"https://blog.codinghorror.com/code-smells/\" rel=\"nofollow noreferrer\">Type Embedded in Name</a> code smell any more.</p>\n\n<hr>\n\n<p>I name my Collection-Classes with a <code>Collection</code>-suffix: <code>UnitCollection</code>. But I know that <code>Units</code> sounds and looks cooler :P</p>\n\n<p>But its only a naming problem inside one class - feel free to choose what fits best for you</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:19:46.757", "Id": "465011", "Score": "0", "body": "i guess naming it `List<Unit> collection` seems like a way to go - that let's open what kind of collection is used (open for change) and prevents naming clash..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:20:25.103", "Id": "465012", "Score": "0", "body": "could you come up with a better name for a *first class collection* for my `Units`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:26:15.847", "Id": "465016", "Score": "1", "body": "@MartinFrank i would go with `Units` or `UnitCollection`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:27:30.933", "Id": "465019", "Score": "0", "body": "thanks - i **WILL** go with `Units` now and suppress this explicit warning for sonar" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T06:59:51.677", "Id": "237209", "ParentId": "237205", "Score": "0" } } ]
{ "AcceptedAnswerId": "237209", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T05:52:42.817", "Id": "237205", "Score": "-3", "Tags": [ "java" ], "Title": "Naming insecurity" }
237205
<p>Was trying to implement and example code to smart pointer from <a href="https://sourcemaking.com/design_patterns/abstract_factory/cpp/before-after" rel="noreferrer">link</a>. Is it a good practice? To go with all unique pointers or should we use shared pointers in this case? How can i improve this ?</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;string&gt; #include&lt;memory&gt; void LOG(std::string strText) { std::cout &lt;&lt; strText &lt;&lt; std::endl; } class Widget { public: virtual void draw() = 0; }; class WindowsBtn : public Widget { public: void draw() { LOG("Windows Button"); } }; class WindowsMenu : public Widget { public: void draw() { LOG("Windows Menu"); } }; class LinuxBtn : public Widget { public: void draw() { LOG("Linux Button"); } }; class LinuxMenu : public Widget { public: void draw() { LOG("Linux Menu"); } }; /* class WidgetFactory { public: virtual Widget* CreateButton() = 0; virtual Widget* CreateMenu() = 0; }; class WindowsFactory : public WidgetFactory{ public: Widget* CreateButton() { return (new WindowsBtn); } Widget* CreateMenu() { return (new WindowsMenu); } }; class LinuxFactory : public WidgetFactory{ public: Widget* CreateButton() { return (new LinuxBtn); } Widget* CreateMenu() { return (new LinuxMenu); } }; class Client { WidgetFactory * factory; public: Client(WidgetFactory* factory) :factory(factory) {} void draw(){ Widget * wd = factory-&gt;CreateButton(); wd-&gt;draw(); display1(); display2(); } void display1() { Widget * w[] = { factory-&gt;CreateButton(), factory-&gt;CreateMenu() }; w[0]-&gt;draw(); w[1]-&gt;draw(); } void display2() { Widget * w[] = { factory-&gt;CreateMenu(), factory-&gt;CreateButton() }; w[0]-&gt;draw(); w[1]-&gt;draw(); } }; */ class SmartWidgetFactory { public: virtual std::unique_ptr&lt;Widget&gt; CreateButton() = 0; virtual std::unique_ptr&lt;Widget&gt; CreateMenu() = 0; }; class SmartWindowsFactory : public SmartWidgetFactory { public: std::unique_ptr&lt;Widget&gt; CreateButton() { return std::make_unique&lt;WindowsBtn&gt;(); } std::unique_ptr&lt;Widget&gt; CreateMenu() { return std::make_unique&lt;WindowsMenu&gt;(); } }; class SmartLinuxFactory : public SmartWidgetFactory { public: std::unique_ptr&lt;Widget&gt; CreateButton() { return std::make_unique&lt;LinuxBtn&gt;(); } std::unique_ptr&lt;Widget&gt; CreateMenu() { return std::make_unique&lt;LinuxMenu&gt;(); } }; class SmartClient { std::unique_ptr&lt;SmartWidgetFactory&gt; factory; public: SmartClient(std::unique_ptr&lt;SmartWidgetFactory&gt; oFactory) { factory = std::move(oFactory); } void draw() { std::unique_ptr&lt;Widget&gt; wd = factory-&gt;CreateButton(); wd-&gt;draw(); display1(); display2(); } void display1() { std::unique_ptr&lt;Widget&gt; w[] = { factory-&gt;CreateButton(), factory-&gt;CreateMenu() }; w[0]-&gt;draw(); w[1]-&gt;draw(); } void display2() { std::unique_ptr&lt;Widget&gt; w[] = { factory-&gt;CreateMenu(), factory-&gt;CreateButton() }; w[0]-&gt;draw(); w[1]-&gt;draw(); } }; int _tmain(int argc, _TCHAR* argv[]) { /*WidgetFactory *factory; factory = new LinuxFactory; Client *c = new Client(factory); c-&gt;draw();*/ std::unique_ptr&lt; SmartWidgetFactory &gt; oFactory = std::make_unique&lt;SmartLinuxFactory&gt;(); std::unique_ptr&lt;SmartClient&gt; oClient = std::make_unique&lt;SmartClient&gt;( std::move(oFactory) ); oClient-&gt;draw(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T12:53:23.063", "Id": "465256", "Score": "0", "body": "just found that the ctor `SmartClient(std::unique_ptr<SmartWidgetFactory> oFactory)` used value instead of reference." } ]
[ { "body": "<p>First, the <strong>big bug.</strong> Your <code>Widget</code> class has no virtual destructor! This means that every time you return a <code>unique_ptr&lt;Widget&gt;</code>, you're losing the information about what <em>kind</em> of widget needs destroying.</p>\n\n<p><a href=\"https://godbolt.org/z/cuDgyB\" rel=\"noreferrer\">Clang will actually diagnose this mistake for you.</a> No matter what compiler you use, make sure you turn on warnings via <code>-Wall -Wextra</code> (or <code>-W4</code> on MSVC).</p>\n\n<hr>\n\n<pre><code>int _tmain(int argc, _TCHAR* argv[])\n</code></pre>\n\n<p>This is a non-standard main routine. Maybe I'm a POSIX chauvinist, but at least for posting publicly, I'd think it would be more appropriate to use</p>\n\n<pre><code>int main(int, char **)\n</code></pre>\n\n<p>or even better,</p>\n\n<pre><code>int main()\n</code></pre>\n\n<p>(since you don't use either of those parameters for anything).</p>\n\n<p>Also notice that I'm using <code>char**</code> instead of <code>char*[]</code>, because in C and C++, <a href=\"https://lkml.org/lkml/2015/9/3/428\" rel=\"noreferrer\">a function parameter cannot be an array.</a> It is pointless to deceive yourself and mean to deceive others.</p>\n\n<hr>\n\n<pre><code>SmartClient(std::unique_ptr&lt;SmartWidgetFactory&gt; oFactory)\n</code></pre>\n\n<p>This constructor should be marked <code>explicit</code>. In fact, <em>every constructor you ever write</em> (except for copy constructors and move constructors) should be <code>explicit</code>. If you leave off the <code>explicit</code>, then you're enabling people to write code like</p>\n\n<pre><code>std::unique_ptr&lt;SmartWidgetFactory&gt; pf = ...;\nSmartClient sc = std::move(pf);\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>SmartClient sc = nullptr;\n</code></pre>\n\n<p>and it'll compile, and they won't realize what they did wrong until runtime. It's better to catch this kind of thing at compile time. Mark all your constructors <code>explicit</code>.</p>\n\n<hr>\n\n<pre><code>std::unique_ptr&lt;Widget&gt; CreateButton()\n</code></pre>\n\n<p>If you intended this function to override the virtual function in the base class, you should have marked it <code>override</code>. (It may <em>still</em> override the virtual function in the base class, even without <code>override</code>, if you spelled everything correctly; but don't bet your workday on it. Mark all overriding functions <code>override</code> and catch your bugs at compile time.)</p>\n\n<p>Also, consider whether it makes conceptual sense that \"creating a button\" is a <em>non-const</em> method of the factory. Maybe it does; I tend to think it doesn't. So I would write this as</p>\n\n<pre><code>std::unique_ptr&lt;Widget&gt; CreateButton() const override\n</code></pre>\n\n<hr>\n\n<pre><code>std::unique_ptr&lt;SmartClient&gt; oClient = std::make_unique&lt;SmartClient&gt;( std::move(oFactory) );\n</code></pre>\n\n<p>Why does this need to be heap-allocated?</p>\n\n<pre><code>auto oClient = SmartClient(std::move(oFactory));\n</code></pre>\n\n<p>Even if you want to keep using <code>make_unique</code> for some reason, consider replacing the cumbersome type name <code>std::unique_ptr&lt;SmartClient&gt;</code> with <code>auto</code>:</p>\n\n<pre><code>auto oClient = std::make_unique&lt;SmartClient&gt;(std::move(oFactory));\n</code></pre>\n\n<p>Notice I've also normalized the whitespace while I'm at it.</p>\n\n<hr>\n\n<pre><code>void LOG(std::string strText)\n</code></pre>\n\n<p>Pass large expensive-to-copy objects, such as <code>std::string</code>, by const reference.</p>\n\n<pre><code>void LOG(const std::string&amp; text)\n</code></pre>\n\n<p>If you are on C++17, consider replacing <code>const std::string&amp;</code> parameters with <code>std::string_view</code> parameters:</p>\n\n<pre><code>void LOG(std::string_view text)\n</code></pre>\n\n<p>Be aware that you should use <code>string_view</code> only in places where it would make equal sense to use a reference type (so, parameters, and that's it).</p>\n\n<p>Also be aware that when people see <code>LOG(\"foo\")</code> in your code, they will assume that <code>LOG</code> is a macro, because it's ALL UPPER CASE. If you mean for people to assume it's a function, call it <code>print_to_log</code> or something like that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:49:19.873", "Id": "465062", "Score": "0", "body": "I know you wrote it for effect, but *every constructor you ever write* is possibly a bit over-the-top! It's probably a good starting point, of course, and it's a shame that couldn't have been the default, with authors specifying just those cases where implicit conversion should be allowed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:10:08.957", "Id": "465117", "Score": "0", "body": "\"_every constructor you ever write_ is possibly a bit over-the-top!\" — I would actually bet (a small amount of) money that OP will never _need_ to write an implicit constructor in their life. Relatively few people ever implement `std::string(const char*)` or `BigNum(int)`, or even `Allocator<T>(const Allocator<U>&)`. We agree it's a good starting point at least. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:16:08.837", "Id": "465118", "Score": "0", "body": "Well, there's also `Size(std::size_t, std::size_t)` where adding `explicit` is noise at best - only constructors that can be called with a single argument actually *need* `explicit`. I do agree that compromising readability is less bad than a surprising conversion, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:53:52.570", "Id": "465123", "Score": "0", "body": "I'd say in that case \"adding `explicit` is noise _at worst_.\" In the average case, it's turning `new_matrix({x,y})` into a compiler error and forcing the caller to write out `new_matrix(Size(x,y))`, so it's more apparent to the reader which overload of `new_matrix` they should be looking for. In the best case https://godbolt.org/z/XgChsg (I have no idea what's happening here). Btw, I'll add `std::true_type()` to my list above — I admit I've used `std::true_type foo() { return {}; }` in preference to `auto foo() { return std::true_type{}; }` — but again OP won't implement `true_type` IRL." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T07:58:44.683", "Id": "237212", "ParentId": "237206", "Score": "7" } }, { "body": "<p>To answer your specific question:</p>\n\n<blockquote>\n <p>To go with all unique pointers or should we use shared pointers in this case?</p>\n</blockquote>\n\n<p>You're absolutely correct to return <code>std::unique_ptr</code> values. This indicates that ownership of the pointed-to object is transferred to the caller. If you were to return <code>std::shared_ptr</code>, then that would imply that the factory retained a share of the ownership (e.g. by retaining an object pool, or something).</p>\n\n<p>Remember that once the caller has a unique pointer, it is able to convert it to a shared pointer if it needs to (but the opposite conversion is obviously not possible, except via the raw pointer).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:56:39.810", "Id": "237219", "ParentId": "237206", "Score": "3" } }, { "body": "<p>I've noticed a few small things:</p>\n\n<ul>\n<li><p>You don't need to flush the stream every time you log something. A simple newline will do.</p></li>\n<li><p>A more suitable log stream provided by C++ would be <code>std::clog</code>. You may, however, need to flush this stream.</p></li>\n<li><p>Your formatting is inconsistent. You have spaces in places where you don't have spaces elsewhere, including but not limited to: in template parameters and after <code>return</code>. This makes the code slightly hard to read.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:05:55.960", "Id": "237241", "ParentId": "237206", "Score": "2" } } ]
{ "AcceptedAnswerId": "237212", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T06:25:55.667", "Id": "237206", "Score": "5", "Tags": [ "c++", "c++11", "pointers" ], "Title": "Implementing Sample Abstract Factory Pattern using Smart Pointers in C++" }
237206
<p>I have been programming in various languages for a very long time, and this was one of my first attempts to build an Android app. Apparently this was not good enough for the challengee, could somebody please point out the most major flows and oversights in my design?</p> <p>The app display a list of pets in a recyclerView and opens a webview to wikipedia when clicked. The Call and Chat button will display an alert telling if shop is open or not - placeholder for something else...</p> <p>OpenHours are parsed from a json.</p> <p>Full project: <a href="https://github.com/simonsso/Pet-Shop-Boy" rel="nofollow noreferrer">https://github.com/simonsso/Pet-Shop-Boy</a></p> <p><strong>MainActivity.kt</strong></p> <pre><code>package net.thesimson.petshopboy import android.app.AlertDialog import android.content.DialogInterface import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import androidx.annotation.UiThread import kotlinx.android.synthetic.main.activity_main.* import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.util.* class MainActivity : AppCompatActivity() { @UiThread fun displayOpenHours() { // Create an alertbox dialog val dialogBuilder = AlertDialog.Builder(this) val storeOpenGreetingMessage:String = if( ShopHours.isShopOpen(Calendar.getInstance()) ){ resources.getString(R.string.thanksshopopen) }else { resources.getString(R.string.thanksshopclosed) } dialogBuilder.setMessage(storeOpenGreetingMessage) .setCancelable(false) .setPositiveButton(resources.getString(R.string.ok), DialogInterface.OnClickListener { dialog, _id -&gt; dialog.cancel() }) val alert = dialogBuilder.create() alert.setTitle(resources.getString(R.string.alerttitle)) alert.show() } @UiThread fun updateCallButtonsVisability(){ chat_button.visibility = if (ShopHours.chatEnabled) { View.VISIBLE } else { View.GONE } call_button.visibility = if (ShopHours.callEnabled) { View.VISIBLE } else { View.GONE } workHours.text = if (ShopHours.humanReadableSign != "") { resources.getString(R.string.officehours) + " " + ShopHours.humanReadableSign } else { resources.getString(R.string.hours_not_loaded_from_config) } } @UiThread override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) call_button.setOnClickListener{displayOpenHours()} chat_button.setOnClickListener{displayOpenHours()} updateCallButtonsVisability() PawCache.requestContent( "https://simonsso.github.io/Pet-Shop-Boy/config.json") { config_json_string -&gt; // NB file is known to be malformated json finding the outermost JSONObject val config = try { JSONObject( config_json_string.substring( config_json_string.indexOf("{"), config_json_string.lastIndexOf("}") + 1 ) ) }catch (e: JSONException) { // Parsing failed return an empty object JSONObject() } // Config loaded OK, update UI! this@MainActivity.runOnUiThread { ShopHours.parseBuisinessHours(config.optString("workHours")) ShopHours.chatEnabled = config.optBoolean("isChatEnabled") ShopHours.callEnabled = config.optBoolean("isCallEnabled") updateCallButtonsVisability() } } val adapter = RecomendedPetsRecyclerViewAdapter(this, PetZoo.pets) PawCache.requestContent("https://simonsso.github.io/Pet-Shop-Boy/pets.json") {pets_json_string-&gt; // NB file is known to be malformated json finding the outermost JSONObject val temp_net_pets = try { JSONArray( pets_json_string.substring( pets_json_string.indexOf("["), pets_json_string.lastIndexOf("]") + 1 ) ) }catch (e:JSONException){ JSONArray() } this@MainActivity.runOnUiThread { PetZoo.pets.clear() for (i in 0 until temp_net_pets.length()) { // JSONArray is broken and will return len 11 but last item does not exist // This try will cactch such an exception try { if (temp_net_pets.getJSONObject(i) is JSONObject) { PetZoo.pets.add(temp_net_pets[i] as JSONObject) } }catch (e:JSONException){ } } adapter.notifyDataSetChanged() } } recycler_view.adapter = adapter adapter.notifyDataSetChanged() } } </code></pre> <p><strong>PawCache.kt</strong></p> <pre><code>package net.thesimson.petshopboy import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Handler import android.widget.ImageView import okhttp3.* import java.io.IOException import java.util.concurrent.ConcurrentHashMap import kotlin.concurrent.thread object PawCache { lateinit var client: OkHttpClient val cache = ConcurrentHashMap&lt;String, Bitmap&gt;() fun requestContent(url: String, onDataFetched:(String)-&gt;Unit ){ thread { try { val request = Request.Builder().url(url).build() client.newCall(request) .enqueue (object :Callback { override fun onResponse(call: Call, response: Response) { if (!response.isSuccessful) return onDataFetched(response.body!!.string()) } override fun onFailure(call: Call, e: IOException) { // Do nothing on failure } }) }catch (e:Exception){ println(e.message) } } } // Request image, and load it into ImageView // Errors are ignored here- a new attempt to fetch an uncached image // will be made next time UI needs it... fun requestImage(imageUrl: String, dest: ImageView) { val uiThreadHandler=Handler() if( cache.containsKey(imageUrl)){ dest.setImageBitmap(cache[imageUrl]) return } thread { try { val request = Request.Builder().url(imageUrl).build() client.newCall(request) .enqueue (object :Callback { override fun onResponse(call: Call, response: Response) { if (!response.isSuccessful) return val bm = BitmapFactory.decodeStream(response.body!!.byteStream()) uiThreadHandler.post(Runnable { cache[imageUrl]=bm dest.setImageBitmap(bm) }) } override fun onFailure(call: Call, e: IOException) { // Do nothing on failure } }) }catch (e:Exception){ println(e.message) } } } } </code></pre> <p><strong>PetRecyclerViewAdapter.kt</strong></p> <pre><code>package net.thesimson.petshopboy import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.ImageView import android.widget.LinearLayout import androidx.recyclerview.widget.RecyclerView import org.json.JSONException import org.json.JSONObject import android.content.Intent object PetZoo{ var pets = ArrayList&lt;JSONObject&gt;() } class RecomendedPetsRecyclerViewAdapter(private var context: Context, private var dataList:ArrayList&lt;JSONObject&gt;): RecyclerView.Adapter&lt;RecomendedPetsRecyclerViewAdapter.ViewHolder&gt;() { override fun getItemCount(): Int { return dataList.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(context).inflate(R.layout.pet_row_item, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { try { val curItem = dataList[position] if (curItem is JSONObject) { val petname = curItem.optString("title") holder.textView.text = petname val image_url = curItem.optString("image_url") val content_url = curItem.optString("content_url") if (image_url!=""){ PawCache.requestImage(image_url,holder.icon) } holder.top.setOnClickListener { val intent : Intent = Intent( context, PetBrowserActivity::class.java) intent.putExtra("loadurl",content_url) intent.putExtra("petname",petname) context.startActivity( intent ) } } }catch (e:JSONException){ println(e.message) } } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val textView:TextView =itemView.findViewById(R.id.petRVTextView) val icon:ImageView =itemView.findViewById(R.id.petRVImageView) val top:LinearLayout =itemView.findViewById(R.id.petRVLinearLayout) } } </code></pre> <p><strong>ShopHours.kt</strong></p> <pre><code>package net.thesimson.petshopboy import androidx.annotation.UiThread import java.util.* object ShopHours { // TODO support for weekends and work days var openAt:Int = 0 var closeAt:Int = 0 var humanReadableSign:String = "" var chatEnabled:Boolean = false var callEnabled:Boolean = false @UiThread fun parseBuisinessHours(s:String):Boolean{ // Whops, Retrieving groups by name is not supported on this platform. // Use group numbers // Days: 1 // OpenHour: 2 // OpenMinute: 4 // CloseHour: 5 // CloseMinute:7 // Live example: https://regex101.com/r/tBRHnN/1 val pattern = Regex("""([\w-]+)\s+(\d+)(:(\d+))?\s*-\s*(\d+)(:(\d+))?""") val matchResult=pattern.matchEntire(s) if (matchResult != null ){ val groups = matchResult.groups // TODO Week day/Weekend val openHour:Int = groups[2]?.value?.toIntOrNull()?:0 val openMin:Int = groups[4]?.value?.toIntOrNull()?:0 val closeHour:Int = groups[5]?.value?.toIntOrNull()?:0 val closeMin:Int = groups[7]?.value?.toIntOrNull()?:0 openAt = 60 * openHour + openMin closeAt = 60 * closeHour + closeMin humanReadableSign = s return true }else{ return false } } @UiThread fun isShopOpen(time:Calendar):Boolean{ if(time.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || time.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY ) return false return time.get(Calendar.HOUR_OF_DAY) * 60 + time.get(Calendar.MINUTE) in openAt..closeAt } } </code></pre> <p><em>Please let me know in the comments if I should post more of the files here or I should trim the code above to some problematic area.</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T08:25:12.163", "Id": "465026", "Score": "0", "body": "Please start by letting me know how to improve this question to meet the site praxis ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T08:55:20.857", "Id": "465042", "Score": "2", "body": "Have you already read [How do I ask a good question](/help/how-to-ask)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:00:49.487", "Id": "465048", "Score": "0", "body": "Had read it now I have **read** it! Slightly better already I think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:01:58.380", "Id": "465049", "Score": "0", "body": "Should I dump all code in here or will that just mess up?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:11:37.293", "Id": "465054", "Score": "2", "body": "I think the title could still be improved since you present a concrete application example. Regarding the amount of code: please paste all the code that provides *relevant* context for what you want to have reviewed. Having additional code in a GitHub repo is generally accepted here. I'm don't know kotlin well enough to be sure, but from what I can see it looks like the code has no external dependencies other than 3rd party libraries, which is good for review." } ]
[ { "body": "<h1>Use resource value itself</h1>\n\n<ul>\n<li>dialogBuilder.setMessage accepts a messageId.</li>\n<li>SetPositiveButton accepts txtId</li>\n<li>setTitle accepts titleId</li>\n - \n</ul>\n\n<h1>Use lambda's</h1>\n\n<p>setPositiveButton accepts a functional interface. due to sam-conversions, you can pass in a lambda.</p>\n\n<pre><code>setPositiveButton(\n resources.getString(R.string.ok), \n DialogInterface.OnClickListener { dialog, _id -&gt;\n dialog.cancel()\n }\n)\n</code></pre>\n\n<p>therefor becomes:</p>\n\n<pre><code>setPositiveButton(\n resources.getString(R.string.ok), \n { dialog, _id -&gt; dialog.cancel() }\n)\n</code></pre>\n\n<p>In kotlin, you can write a lmabda outside the parenthesis if they are the last argument.<br>\nThe code therefor becomes:</p>\n\n<pre><code>setPositiveButton(resources.getString(R.string.ok)){ dialog, _id -&gt; \n dialog.cancel()\n)\n</code></pre>\n\n<p>And due to the former chapter, it can be rewritten to:\n setPositiveButton(R.string.ok){ dialog, _id -> \n dialog.cancel()\n )</p>\n\n<p>. Therefor it's not needed to get the string yourself.\nI personally love to us when to make the incrementation way smaller, even if you use it for it then.</p>\n\n<h1>extension-functions</h1>\n\n<p>In Kotlin you can define functions in a way that it looks like they're part of the class.\nWe can use this to simplify the following code:</p>\n\n<pre><code>chat_button.visibility = if (ShopHours.chatEnabled) {\n View.VISIBLE\n} else {\n View.GONE\n}\n</code></pre>\n\n<p>by adding:</p>\n\n<pre><code>fun View.setVisible(visible: Boolean){\n this.visibility = if(visible) View.Visible else View.Gone\n}\n</code></pre>\n\n<p>You can write\n chat_button.setVisible(ShopHours.chatEnabled)</p>\n\n<p>You can do this with properties to:</p>\n\n<pre><code>var View.isVisible : Boolean\n get() = this.visibility == View.Visible\n set(value) {\n this.visibility = if(value) View.Visible else View.Gone\n }\n</code></pre>\n\n<p>Which allows us to write the former code as:\n chat_button.isVisible = ShopHours.chatEnabled</p>\n\n<p>This property is also provided in <a href=\"https://developer.android.com/kotlin/ktx\" rel=\"nofollow noreferrer\">kotlin-ktx</a>, Androidx.core.view to be precise.</p>\n\n<h1>strings with params</h1>\n\n<p>When you are doing it correct by using string-resources, why not go all the way?<br>\nYou can get a string with parameters in Android, see <a href=\"https://developer.android.com/guide/topics/resources/string-resource#FormattingAndStyling\" rel=\"nofollow noreferrer\">formatting</a>.<br>\nWhen you want to add a string as parameter use % + paramNumber + $S and pass the params through getString.</p>\n\n<p>example:</p>\n\n<pre><code>&lt;string name=\"sayHi\"&gt;I say %1$S %2$S. &lt;/string&gt;\ngetString(R.strings.sayHi, \"hello\", \"you\")\n</code></pre>\n\n<h1>coroutines</h1>\n\n<p>Kotlin has a concept called <a href=\"https://kotlinlang.org/docs/reference/coroutines-overview.html\" rel=\"nofollow noreferrer\">coroutines</a>.<br>\nGoogle has a tutorial <a href=\"https://codelabs.developers.google.com/codelabs/kotlin-coroutines/#0\" rel=\"nofollow noreferrer\">here</a>.<br>\nThis are lightweight threads and compiler magic.</p>\n\n<p>In pawCache you can write:</p>\n\n<pre><code>suspend fun Request.getResponse(url : String) = suspendCoroutine&lt;Response&gt; {\n client.newCall(request)\n .enqueue(object : Callback {\n override fun onResponse(call: Call, response: Response) {\n if (!response.isSuccessful) it.resume(response)\n }\n\n override fun onFailure(call: Call, e: IOException) {\n it.resumeWithException(e)\n }\n })\n}\n</code></pre>\n\n<p>And then you can rewrite your other functions:</p>\n\n<pre><code>suspend fun requestContent(url: String) = \n Request.Builder().url(url).build().getResponse()\n</code></pre>\n\n<p>This will return null for the case where you said doNothing and you have to catch the exception of OnFailure.</p>\n\n<pre><code>suspend fun requestImage(imageUrl: String, dest: ImageView) {\n val uiThreadHandler=Handler()\n if( cache.containsKey(imageUrl)){\n dest.setImageBitmap(cache[imageUrl])\n return\n }\n try {\n val response = Request.Builder().url(imageUrl).build().getResponse() ?: return\n val bm = BitmapFactory.decodeStream(response.body!!.byteStream())\n withContext(Dispatchers.Main){\n cache[imageUrl]=bm\n dest.setImageBitmap(bm)\n }\n } catch(e : Exception){\n println(e.message)\n }\n}\n</code></pre>\n\n<h1>println</h1>\n\n<p>Assuming you don't have pure-java modules, you use the <a href=\"https://developer.android.com/reference/java/util/logging/Logger\" rel=\"nofollow noreferrer\">android logger</a>.<br>\nThere is a possibility to extend this by using libraries.<br>\nThe only one I really heard of isis <a href=\"https://github.com/JakeWharton/timber\" rel=\"nofollow noreferrer\">Timber</a>( <a href=\"https://medium.com/mindorks/better-logging-in-android-using-timber-72e40cc2293d\" rel=\"nofollow noreferrer\">medium article</a> ), but most of the time I'm just using the Android logger.</p>\n\n<h1>Anko</h1>\n\n<p><a href=\"https://github.com/Kotlin/anko\" rel=\"nofollow noreferrer\">Anko</a> is old, not maintained well, but still useful.\nFor example, You wrote: </p>\n\n<pre><code>val intent : Intent = Intent( context, PetBrowserActivity::class.java)\nintent.putExtra(\"loadurl\",content_url)\nintent.putExtra(\"petname\",petname)\ncontext.startActivity( intent )\n</code></pre>\n\n<p>using <a href=\"https://github.com/Kotlin/anko/wiki/Anko-Commons-%E2%80%93-Intents\" rel=\"nofollow noreferrer\">Anko/commons</a> you can rewrite this to:</p>\n\n<pre><code>startActivity&lt;PerBrowserActivity&gt;(\n \"loadurl\" to content_url,\n \"petName\" to petname\n)\n</code></pre>\n\n<h1>architecture</h1>\n\n<p>You shoulld seperate view, logic and data code should be seperated.\nTherefor take a look <a href=\"https://developer.android.com/topic/libraries/architecture\" rel=\"nofollow noreferrer\">at Android architecture components</a>, <a href=\"https://android.jlelse.eu/architecture-components-mvp-mvvm-237eaa831096\" rel=\"nofollow noreferrer\">mvp / mvvm</a> or the <a href=\"https://badoo.github.io/MVICore/\" rel=\"nofollow noreferrer\">mviCore library</a></p>\n\n<p>Hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:44:13.593", "Id": "237299", "ParentId": "237213", "Score": "2" } } ]
{ "AcceptedAnswerId": "237299", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T08:22:26.873", "Id": "237213", "Score": "1", "Tags": [ "interview-questions", "android", "kotlin" ], "Title": "An app displaying items fetched from JSON, but I think maybe I'm not using best Android development praxis" }
237213
<p>I have a class with three similar methods. I can't consider which a pattern to use better for refactoring: template method, strategy or something else? I don't know. Can you help me?<br> Update: This code is a little exercise to be a better programmer. I'm going to add some algorithms, but it's not a production code. I would write good not smelled code for myself. I would have a beautiful code from this, if it's possible.<br> The main goal of the code : is creating a graph, breadth-first search and breadth-first traversing in graph. I've used a Cormen &amp;al. algorithms from "Introduction to Algorithms" book. The method named <code>BreadthFirstSearch</code> is search. The method named <code>CleanVertex</code> changes color of vertex after search from black to white again. The last method named Path is for traversing the hole graph. All vertexes are traversed and their order are saved in a variable and return.</p> <pre><code>public class Graph { public bool BreadthFirstSearch(int value) { if (StartingPoint == null) { return false; } var queue = new Queue&lt;Vertex&gt;(); queue.Enqueue(StartingPoint); while (queue.Count != 0) { var vertex = queue.Dequeue(); if (vertex.Index == value) { CleanVertex(); return true; } vertex.Color = Color.Black; for (int i = 0; i &lt; vertex.Neighbours.Count; i++) { var vertexNeighbour = vertex.Neighbours[i]; if (vertexNeighbour.Color == Color.White) { vertexNeighbour.Color = Color.Grey; queue.Enqueue(vertexNeighbour); } } } CleanVertex(); return false; } private void CleanVertex() { if (StartingPoint == null) { return; } StartingPoint.Color = Color.White; var queue = new Queue&lt;Vertex&gt;(); queue.Enqueue(StartingPoint); while (queue.Count != 0) { var vertex = queue.Dequeue(); for (int i = 0; i &lt; vertex.Neighbours.Count; i++) { var vertexNeighbour = vertex.Neighbours[i]; if (vertexNeighbour.Color != Color.White) { vertexNeighbour.Color = Color.White; queue.Enqueue(vertexNeighbour); } } } } public string Path() { if (StartingPoint == null) { return string.Empty; } var queue = new Queue&lt;Vertex&gt;(); queue.Enqueue(StartingPoint); var path = new StringBuilder(); while (queue.Count != 0) { var vertex = queue.Dequeue(); path.Append($"{vertex.Index} "); vertex.Color = Color.Black; for (int i = 0; i &lt; vertex.Neighbours.Count; i++) { var vertexNeighbour = vertex.Neighbours[i]; if (vertexNeighbour.Color == Color.White) { vertexNeighbour.Color = Color.Grey; queue.Enqueue(vertexNeighbour); } } } return path.ToString().Trim(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T08:45:24.067", "Id": "465038", "Score": "0", "body": "Welcome to CodeReview@SE. In the first revision of this question, code indentation is unusual & inconsistent. I found creating code blocks bracketing them with \"~~~-lines\" less accident-prone than prefixing additional blanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:26:27.353", "Id": "465119", "Score": "0", "body": "@Galina. Please try to explain what the code is used for? Are you planning to add more algorithms? Is it used often? Where it is used? All of that can influence the advice you will get" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T05:09:59.927", "Id": "465194", "Score": "0", "body": "Well, they are similar, but they are very different as well. They each return a different type and while the methods all sort of smell the same they also each have subtle differences. I guess I'd want to know what the goal is. Why are you worried about these routines? Is this a class exercise or do you have a real-world specific goal here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T08:27:30.943", "Id": "465214", "Score": "0", "body": "@greybeard I've tryed to correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T08:28:40.810", "Id": "465215", "Score": "0", "body": "@Gilad I've add an explanation in post, it's a simple home project for improoving my code skill" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T08:29:12.903", "Id": "465216", "Score": "0", "body": "@FrankMerrow It's an exercise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T00:11:42.397", "Id": "465334", "Score": "1", "body": "Others may disagree, but repeats like this appear in code from time to time. To be sure, if the \"constant code\" is complex enough that you find yourself fixing bugs in it and having to patch those bugs in multiple places, then definitely refactoring of some kind is in order. However, in this case the constant code is fairly simple and trying to factor it out will likely require some work that isn't worth in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T08:03:31.573", "Id": "465520", "Score": "0", "body": "@FrankMerrow Thank you" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T08:29:07.750", "Id": "237214", "Score": "1", "Tags": [ "c#", "design-patterns" ], "Title": "Create and traverse a graph" }
237214
<p>I'm wondering if there is a better way to write the same exact thing? I wrote it to display three different dynamic messages, but I feel like there can be a lot of improvements...</p> <p>Any help/idea would be appreciated.</p> <pre><code> .list-wrapper { width: 100%; } .list { margin: 0 auto; height: 25px; position: relative; } .list-item:nth-child(2) { -webkit-animation-delay: 4s; -moz-animation-delay: 4s; animation-delay: 4s; } .list-item:nth-child(3) { -webkit-animation-delay: 8s; -moz-animation-delay: 8s; animation-delay: 8s; } .list-item { position: absolute; top: 0; left: 0; right: 0; bottom: 0; opacity: 0; font-size: 12px; color: #33302d; line-height: 1.6px; -webkit-transition: 1s; -moz-transition: 1s; transition: 1s; padding: 6px 20px; text-align: center; -webkit-animation: Liste 12s 0s infinite; -moz-animation: Liste 12s 0s infinite; animation: Liste 12s 0s infinite; } @-webkit-keyframes Liste { 0% { opacity: 0; } 17% { opacity: 1; z-index: 3; } 25% { opacity: 1;} 40% { opacity: 0; z-index: 1; } 100% { opacity: 0; } } @-moz-keyframes Liste { 0% { opacity: 0; } 17% { opacity: 1; z-index: 3; } 25% { opacity: 1;} 40% { opacity: 0; z-index: 1; } 100% { opacity: 0; } } @keyframes Liste { 0% { opacity: 0; } 17% { opacity: 1; z-index: 3; } 25% { opacity: 1;} 40% { opacity: 0; z-index: 1; } 100% { opacity: 0; } } </code></pre> <p>And I call it with:</p> <pre><code>&lt;div class="list-wrapper"&gt; &lt;div class="list"&gt; &lt;span class="list-item list-item1"&gt;&lt;b&gt;&lt;?php echo $list['list1']?&gt;&lt;/b&gt;&lt;/span&gt; &lt;span class="list-item list-item2"&gt;&lt;b&gt;&lt;?php echo $list['list2']?&gt;&lt;/b&gt;&lt;/span&gt; &lt;span class="list-item list-item3"&gt;&lt;b&gt;&lt;?php echo $list['list3']?&gt;&lt;/b&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>If you have any improvements in mind, here is a working <a href="https://jsfiddle.net/ov1Lput0/" rel="nofollow noreferrer">fiddle</a>.</p> <p>UPDATE:</p> <p>I've put in PHP foreach for lists, looks much cleaner now.</p> <pre><code>&lt;div class="list-wrapper"&gt; &lt;div class="list"&gt; &lt;?php $i = 1; ?&gt; &lt;?php foreach ($liste as $value) : ?&gt; &lt;span class="list-item list-item&lt;?php echo $i++; ?&gt;"&gt;&lt;b&gt;&lt;?php echo $value['text']?&gt;&lt;/b&gt;&lt;/span&gt; &lt;?php endforeach; ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Does anybody else have any more ideas?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:46:40.950", "Id": "465060", "Score": "1", "body": "First what in your code you think needs to improve?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:48:44.483", "Id": "465061", "Score": "2", "body": "do you need to improve css or html/php part. for php, you can just add a loop" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:51:29.230", "Id": "465063", "Score": "1", "body": "I think there is a better way to write that CSS code, this looks ugly? @waqasMumtaz PHP loop is a good idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T06:42:28.480", "Id": "465204", "Score": "0", "body": "@waqasMumtaz Do you maybe have an idea how could I make CSS more dynamic? While now it works good only for 3 text lists, if there is -2 or 4+ then animation is screwed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T06:50:58.023", "Id": "465206", "Score": "0", "body": "Yes you can improve it. Do you have an experience of SASS ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T07:03:17.420", "Id": "465207", "Score": "0", "body": "I have in SCSS, which is basically the same. The problem is, I can't get it to work. I would have to mix PHP with it to count text lists first which I can't do with SCSS, and then by that number fill other values in." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T09:38:47.480", "Id": "237218", "Score": "0", "Tags": [ "css", "html5" ], "Title": "This is a CSS/HTML/PHP dynamic text list" }
237218
<p>I have an input like this:</p> <pre class="lang-py prettyprint-override"><code>x = '415,252,428,233,428,214,394,207,383,205,390,195' </code></pre> <p>And I want to end up with this</p> <pre class="lang-py prettyprint-override"><code>y = [(415,252),(428,233),(428,214),(394,207),(383,205),(390,195)] </code></pre> <p>The closes I got is</p> <pre class="lang-py prettyprint-override"><code>tmp = [int(i) for i in x.split(',')] y = zip(tmp[::2], tmp[1::2]) </code></pre> <p>How do I get rid of the intermediate list? I need alternative to <code>[::2]</code> that could be used on a generator.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T07:39:37.330", "Id": "465210", "Score": "1", "body": "Maybe you can use `chunked` or `sliced` from the [more-itertools](https://more-itertools.readthedocs.io/en/stable/) package?" } ]
[ { "body": "<p>To reduce memory usage you can exploit the mechanics of <code>zip</code> and <code>iter</code> / iterator / generator expression.</p>\n\n<ol>\n<li><p>Make <code>tmp</code> an <a href=\"https://docs.python.org/3/glossary.html#term-iterator\" rel=\"noreferrer\">iterator</a>.</p>\n\n<p>You can achieve this by changing the brackets from <code>[]</code> to <code>()</code>; changing it from a list comprehension to a generator expression.</p>\n\n<p>You can alternately wrap the list comprehension in an <code>iter</code> call. However that would still be using <span class=\"math-container\">\\$O(n)\\$</span> memory.</p></li>\n<li><p>In case you don't know what an iterator is, than it's a very useful <a href=\"https://en.wikipedia.org/wiki/Iterator_pattern\" rel=\"noreferrer\">design pattern</a>.</p>\n\n<p>In short the iterator contains in it some data, and a single method to get the next bit of information. In Python the <code>next</code> function calls this method.</p>\n\n<p>Take the iterator a list provides:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; my_data = iter([1, 2, 3, 4])\n&gt;&gt;&gt; next(my_data)\n1\n&gt;&gt;&gt; next(my_data)\n2\n</code></pre></li>\n<li><p>If you think of zip in terms of iterators, then you'll notice that with two input it works something like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def zip(a, b):\n while True:\n yield next(a), next(b)\n</code></pre>\n\n<p>This means if <code>a</code> and <code>b</code> are the same then zip will get the first value and second value in a tuple. Then it will get the third and fourth, until it gets all values.</p></li>\n</ol>\n\n<p>And so to improve memory usage you can change your code to:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>tmp = (int(i) for i in x.split(','))\ny = zip(tmp, tmp)\n</code></pre>\n\n<p><strong>Note</strong>: this still runs in <span class=\"math-container\">\\$O(n)\\$</span> space, as <code>x.split()</code> also makes an intermediary list. However it has cut the code from four intermediary lists to just one.</p>\n\n<hr>\n\n<p>This is a common pattern, as provided in the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"noreferrer\"><code>itertools</code> docs</a>.</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>def grouper(iterable, n, fillvalue=None):\n \"Collect data into fixed-length chunks or blocks\"\n # grouper('ABCDEFG', 3, 'x') --&gt; ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return zip_longest(*args, fillvalue=fillvalue)\n</code></pre>\n</blockquote>\n\n<pre class=\"lang-py prettyprint-override\"><code>y = grouper((int(i) for i in x.split(',')), 2)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T21:37:56.450", "Id": "465171", "Score": "0", "body": "Wow, I'm surprised it works that way. It makes sense, but I find this very counterintuitive" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T12:46:59.450", "Id": "465253", "Score": "0", "body": "May because you still think of `tmp` as a sequence, that's the mistake I made." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T10:19:31.030", "Id": "237221", "ParentId": "237220", "Score": "11" } } ]
{ "AcceptedAnswerId": "237221", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T10:09:25.700", "Id": "237220", "Score": "7", "Tags": [ "python", "python-3.x" ], "Title": "String to list of pairs" }
237220
<p><strong>Goal:</strong></p> <p>I am trying to get the hang of using MySQL connections within C# windows forms. These are such areas I am targeting:</p> <ul> <li>Loading dataGridView correctly</li> <li>Refresh dataGridView from an external form (See <code>public void RefreshGrid()</code>)</li> <li>Update query for MySQL connection</li> </ul> <p>I'd like to hear some reviews from you guys. Does the structure look good, can something be changed to, because of some irrelevant code?</p> <p>This is what I have so far:</p> <pre><code>using System; using System.Configuration; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace Final_Version { public partial class Form3 : Form { public Form3() { InitializeComponent(); } //MySQL connection variable private MySqlConnection connection; //open connection to database private bool OpenConnection() { try { connection.Open(); return true; } catch (MySqlException ex) { //When handling errors, you can your application's response based on the error number. switch (ex.Number) { case 0: MessageBox.Show("Cannot connect to server. Contact administrator"); break; default: MessageBox.Show(ex.Message); break; } return false; } } //Close connection private bool CloseConnection() { try { connection.Close(); return true; } catch (MySqlException ex) { MessageBox.Show(ex.Message); return false; } } //Adapter private MySqlDataAdapter mySqlDataAdapter; private void Form3_Load(object sender, EventArgs e) { // MySQL connection string string connString = ConfigurationManager.ConnectionStrings["Final_Version.Properties.Settings.technicalConnectionString"].ConnectionString; connection = new MySqlConnection(connString); if (this.OpenConnection() == true) { //Logic mySqlDataAdapter = new MySqlDataAdapter("select * from user", connection); DataSet DS = new DataSet(); mySqlDataAdapter.Fill(DS); dataGridView1.DataSource = DS.Tables[0]; //close connection this.CloseConnection(); } } //Refresh Data Grid from external Forms public void RefreshGrid() { // MySQL connection string string connString = ConfigurationManager.ConnectionStrings["Final_Version.Properties.Settings.technicalConnectionString"].ConnectionString; connection = new MySqlConnection(connString); if (this.OpenConnection() == true) { //Logic mySqlDataAdapter = new MySqlDataAdapter("select * from user", connection); DataSet DS = new DataSet(); mySqlDataAdapter.Fill(DS); dataGridView1.DataSource = DS.Tables[0]; //close connection this.CloseConnection(); } } //Open new form *Form 4 - Add user* private void button1_Click(object sender, EventArgs e) { var form4 = new Form4(this); form4.Show(); } //Remove user private void button2_Click(object sender, EventArgs e) { var confirmResult = MessageBox.Show("Remove this user?", "Confirm", MessageBoxButtons.YesNo); if (confirmResult == DialogResult.Yes) { if (this.dataGridView1.SelectedRows.Count &gt; 0) { string user = dataGridView1.SelectedCells[0].Value.ToString(); string connString = ConfigurationManager.ConnectionStrings["Final_Version.Properties.Settings.technicalConnectionString"].ConnectionString; MySqlConnection conn = new MySqlConnection(connString); conn.Open(); MySqlCommand comm = conn.CreateCommand(); comm.CommandText = "delete from user where username = @user"; comm.Parameters.AddWithValue("@user", user); comm.ExecuteNonQuery(); conn.Close(); MessageBox.Show("User (" + user + ") removed"); this.RefreshGrid(); } else { MessageBox.Show("Select Row"); } } else { return; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T12:01:40.020", "Id": "465087", "Score": "0", "body": "Welcome to Code Review! Can you tell us more about your table structure? For example, the result of [`EXPLAIN`](https://dev.mysql.com/doc/refman/5.7/en/using-explain.html)?" } ]
[ { "body": "<p>Don't have methods like <code>OpenConnection()</code> and <code>CloseConnection()</code>. Instead, use a <code>using</code> block:</p>\n\n<pre><code>using(var conn = new MySqlConnection(connString))\n{\n // db stuff\n}\n</code></pre>\n\n<p>Same for <code>MySqlDataAdapter</code> and <code>DataSet</code>: both implement <code>IDisposable</code> and thus should be handled properly. Instead of writing lots of code to do this yourself, use the built-in <code>using</code>.</p>\n\n<pre><code>using(var conn = new MySqlConnection(connString))\n{\n using(var mySqlDataAdapter= new MySqlDataAdapter(\"select * from user\", connection))\n {\n using(var dataSet = new DataSet())\n {\n // custom code\n }\n }\n}\n</code></pre>\n\n<p>Do not store your <code>MySqlConnection</code> at class level!</p>\n\n<hr>\n\n<p>Why do you have almost identical <code>Form3_Load</code> and <code>RefreshGrid</code> methods? Do not copy-paste code, instead move it to a method and call that.</p>\n\n<hr>\n\n<p>Store <code>ConfigurationManager.ConnectionStrings[\"Final_Version.Properties.Settings.technicalConnectionString\"].ConnectionString</code> in a dedicated class. If you ever need to change this parameter name, you need to change it in three places in this short class alone and that is just asking for problems. </p>\n\n<p>I usually have a class called <code>AppConfiguration</code> which then contains things like:</p>\n\n<pre><code> public static string ConnectionString()\n {\n return ConfigurationManager.ConnectionStrings[\"connection_string_name\"].ConnectionString;\n }\n</code></pre>\n\n<hr>\n\n<p>You're using WinForms which I'd consider \"ancient\" technology, and thus you'll likely encounter old and outdated example code. I'd urge you to look at more modern practices and consider better ways to get the same result. </p>\n\n<p>Case in point is the binding of a <code>DataSet</code> to a <code>Grid</code>: this is fairly easy, but once you need to add custom properties etc. you'll likely end up with hacky code. Instead consider moving all of your DB logic to a service class and <a href=\"https://dapper-tutorial.net/\" rel=\"nofollow noreferrer\">using Dapper</a> to return a list of data objects with properly named properties. that way you also separate your UI from your business logic.</p>\n\n<p>Also, you seem very concerned about exceptions thrown by opening or closing your db connection. IMHO it is pointless to anticipate such exceptions and capture them unless you are connecting to a very volatile database environment -- and then you should solve that problem instead of anticipating it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T13:38:36.937", "Id": "465098", "Score": "0", "body": "Thanks for this, will improve and look into my code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T11:00:09.630", "Id": "465243", "Score": "0", "body": "Hi again, I see you said you consider WinForms as ancient. What do you recommend using now? To create Desktop applications to communicate with MySQL databases?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:52:32.667", "Id": "465288", "Score": "0", "body": "@LV98 Depends on your needs: https://docs.microsoft.com/en-us/windows/apps/desktop/ . The main thing is to separate the UI from your business logic, and WinForms has a tendency to make it easy not to do so. At least apply MVVM(-like) practices, because those are things you'll see in all kinds of technologies used in modern projects." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T13:20:24.143", "Id": "237232", "ParentId": "237222", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T10:25:56.980", "Id": "237222", "Score": "1", "Tags": [ "c#", "mysql", "winforms" ], "Title": "C# MySQL connection and some queries" }
237222
<p>This was the question given to me:</p> <blockquote> <h2>Implement a function to query json_schema</h2> <p>The goal of this exercise is to implement a function that allows you to query the type of a keypath in a JSON schema.</p> <p>This function will accept a valid <a href="https://json-schema.org/specification.html" rel="nofollow noreferrer">JSON schema</a> as dict, a key_path (eg: <code>foo.bar.baz</code>) and return the type of the property.</p> <h3>Note:</h3> <ul> <li>There are only two fields in the schema you have to pay attention to: <code>properties</code> and <code>definitions</code>.</li> <li>If the dictionary associated with the field has a field named <code>$ref</code> it means that it's referring to another schema stored under the top- level schema. You have follow the link to get to the actual definition.</li> <li>For the sake of this exercise you can assume that all values for <code>$ref</code> will start with <code>#/&lt;key_path&gt;</code>.</li> <li>You should see a schema and some assert statements under "Test" section. You should NOT have to change anything under the "Test" section. If you can get our code to pass the tests, then it means your function works as expected.</li> <li>Feel free to use whatever libraries you need to use except any libraries that actually allow you to query the JSON schema.</li> </ul> </blockquote> <p>I followed it by doing this:</p> <pre><code>import json import copy schema = json.loads('''{ "$id": "https://example.com/nested-schema.json", "title": "nested-schema", "$schema": "http://json-schema.org/draft-07/schema#", "required": [ "EmploymentInformation", "EmployeePartyID", "Age" ], "properties": { "EmployeePartyID": { "type": "string", "minLength": 1, "maxLength": 3 }, "EmploymentInformation": { "$ref": "#/definitions/EmploymentInformation" }, "Age": { "type": "integer", "minimum": 16, "maximum": 80 } }, "definitions": { "EmploymentInformation": { "type": "object", "required": [ "OriginalHireDate" ], "properties": { "OriginalHireDate": { "type": "string", "format": "date" }, "Beneficiary": { "$ref": "#/definitions/DependantInformation" } } }, "DependantInformation": { "type": "object", "required": [ "Name" ], "properties": { "Name": { "type": "string", "minLength": 5 } } } }, "description": "nested-schema" }''') def resolve_ref(ref, modified_schema): ref_path = ref["$ref"].split("/")[1:] ref_obj = modified_schema for node in ref_path: ref_obj = ref_obj[node] resolve_refs(ref_obj, modified_schema) return ref_obj def resolve_refs(json_schema, modified_schema=None): if modified_schema is None: modified_schema = json_schema for k, v in json_schema.items(): if isinstance(v, dict) and "$ref" in v: json_schema[k] = resolve_ref(v, modified_schema) elif isinstance(v, dict): resolve_refs(json_schema[k], modified_schema) def get_type(key_path, json_schema): """ Recursively gets the type if it exists. :param key_path: :param json_schema: :return: """ if 'properties' in json_schema: if key_path[0] in json_schema['properties']: return get_type(key_path[1:], json_schema['properties'][key_path[0]]) else: return json_schema.get('type', None) else: return json_schema.get('type', None) completed_schema = dict() def get_complete_schema(json_schema): """ Takes the schema and solves the refs, stores in a dict so that it is computed only once. :param json_schema: :return modified schema: """ schema_str = json.dumps(json_schema, sort_keys=True) if not completed_schema.get(schema_str): modified_schema = copy.deepcopy(json_schema) resolve_refs(modified_schema) completed_schema[schema_str] = modified_schema else: modified_schema = completed_schema[schema_str] return modified_schema def get_type_for_key_path(json_schema: dict, key_path: str) -&gt; str: modified_schema = get_complete_schema(json_schema) key_path_list = key_path.split('.') key_path_type = get_type(key_path_list, modified_schema) return key_path_type assert (get_type_for_key_path(schema, "Age") == "integer") assert (get_type_for_key_path(schema, "EmploymentInformation.OriginalHireDate") == "string") assert (get_type_for_key_path(schema, "EmploymentInformation.Beneficiary.Name") == "string") assert (get_type_for_key_path(schema, "foo.bar") == None) </code></pre> <p>Would my code be good enough for a Senior Python Engineer?</p> <p>Note, they gave me the schema and the test conditions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T11:03:30.223", "Id": "465079", "Score": "0", "body": "Missing documentation comments might be such a (too) simple cause for rejection. That is code style, using smart code (existing APIs), special python constructs, data structures." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T14:12:46.677", "Id": "465448", "Score": "0", "body": "@JoopEggen Nah, the challenge is really basic. If you're using existing APIs, special Python constructs or data structures then you're being 'smarter' than the challenge is asking for." } ]
[ { "body": "<ul>\n<li><p>You have failed to apply TDD, and have over complicated the solution.<br>\nBefore reviewing your code I completed the challenge myself, which I'll walk you through after reviewing your solution.</p></li>\n<li><p>Your function <code>resolve_ref</code></p>\n\n<ul>\n<li>This should be split out into two functions, <code>get_ref</code> and <code>_resolve_ref</code>, having <code>resolve_ref</code> as a convenience to them.</li>\n<li>Since you haven't split out <code>get_ref</code>, you have to mangle the object to not contain $ref in the walk part of the function.</li>\n<li>I'm not a fan of defining <code>ref_path</code>, just place that next to the <code>in</code> in the <code>for</code> loop.</li>\n<li>You shouldn't call <code>resolve_refs</code> in <code>resolve_ref</code> it's making you walk the dictionary tons of times, and it's just plain confusing.</li>\n</ul></li>\n<li><p>Your function <code>resolve_refs</code></p>\n\n<ul>\n<li>It's merged <code>_resolve_ref</code> into it making it far more complex than it needs to be. I suggest splitting this out.</li>\n</ul></li>\n<li><p>Your function <code>get_type</code></p>\n\n<ul>\n<li>If I were marking your code and saw this function, you'd be dropped within seconds.</li>\n<li>If I'm asking for an object's type, I'm not asking for its parent's type.</li>\n<li>This should be split into two functions, <code>get_property</code> and <code>get_type</code>. The former walks the path getting the property, and the latter just uses <code>get_property(...).get('type', None)</code>.</li>\n</ul></li>\n<li><p>Your function <code>get_complete_schema</code></p>\n\n<ul>\n<li>Never mind an interview, if I were a maintainer for a JSONSchema library, and you submitted this in a pull request. I'd never accept it, whilst this function exists.</li>\n<li>You rely on a global <code>completed_schema</code> which means your function works once, and then blows up every time after that.</li>\n<li>You've been asked to get a property, not make a new schema.</li>\n<li>If we need to edit the schema after you've had you way with it, then we now have to keep track of all the references and provide an annoying interface to modify the schema. It also leads to data integrity problems if a user or the library provider messes up once.</li>\n</ul></li>\n<li><p>Your function <code>get_type_for_key_path</code></p>\n\n<ul>\n<li>This seems reasonable enough, however <code>key_path.split('.')</code> should probably be in <code>get_type</code>.</li>\n</ul></li>\n<li><p>Your naming sense is poor, I don't want to read 8 character variable names when a 4 character one is enough.</p></li>\n<li><p>You've quarter arsed your docstrings, and they're not even PEP compliant. If this is the level of documentation you'd give when you provide documentation then I'd not want you. You've given a short description on what it does, and stated what parameters it takes, but not explained the parameters. Additionally only half your code is documented.</p>\n\n<p>If you're going to do something, at least do it well.</p></li>\n</ul>\n\n<h1>How I solved this</h1>\n\n<ol>\n<li><p>Get the code working with Age.</p>\n\n<ol>\n<li><p>Make the <code>get_type_from_key_path</code>.</p>\n\n<p>Given the god awful name, we know it's a convenience function. This means we should delegate to a different function to get the property, and this should only mutate the result to pass the tests.</p></li>\n<li><p>Make <code>get_property</code>.</p>\n\n<p>This splits the provided path into segments, and walks the tree. It should be noted that each time you walk here you're walking <code>node['properties'][segment]</code> not <code>node[segment]</code>.</p></li>\n</ol>\n\n<p></p>\n\n<pre><code>def get_property(schema, path):\n node = schema\n for segment in path.split('.'):\n node = node['properties'][segment]\n return node\n\n\ndef get_type_from_key_path(schema, path):\n return get_property(schema, path)['type']\n</code></pre></li>\n<li><p>Get the code working with <code>EmploymentInformation.OriginalHireDate</code>.</p>\n\n<ol>\n<li><p>We need to add a new function to resolve references. Since this is a programming challenge we can look to the problem description to make things simple.</p>\n\n<blockquote>\n <p>For the sake of this exercise you can assume that all values for $ref will start with #/.</p>\n</blockquote>\n\n<p>This means we only need to pass the schema and walk the provided path.</p></li>\n<li><p>Change <code>get_property</code> so if \"$ref\" is in the object to change the node to the reference.</p></li>\n</ol>\n\n<p></p>\n\n<pre><code>def get_ref(schema, path):\n node = schema\n for segment in path.split('/')[1:]:\n node = node[segment]\n return node\n\n\ndef get_property(schema, path):\n node = schema\n for segment in path.split('.'):\n if '$ref' in node:\n node = get_ref(schema, node['$ref'])\n node = node['properties'][segment]\n return node\n</code></pre></li>\n<li><p>Get the code working with <code>EmploymentInformation.Beneficiary.Name</code>.<br>\nNo changes needed, it just works!</p></li>\n<li><p>Get the code working with <code>foo.bar</code>.</p>\n\n<ol>\n<li>Change the code so if <code>get_property</code> raises a key error then you return <code>None</code>.</li>\n</ol>\n\n<p></p>\n\n<pre><code>def get_type_for_key_path(schema, path):\n try:\n return get_property(schema, path)['type']\n except KeyError:\n return None\n</code></pre></li>\n</ol>\n\n<p>This nicely works with all the tests and is really short.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_ref(schema, path):\n node = schema\n for segment in path.split('/')[1:]:\n node = node[segment]\n return node\n\n\ndef get_property(schema, path):\n node = schema\n for segment in path.split('.'):\n if '$ref' in node:\n node = get_ref(schema, node['$ref'])\n node = node['properties'][segment]\n return node\n\n\ndef get_type_for_key_path(schema, path):\n try:\n return get_property(schema, path)['type']\n except KeyError:\n return None\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T13:45:10.013", "Id": "237377", "ParentId": "237224", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T10:46:34.853", "Id": "237224", "Score": "3", "Tags": [ "python", "json" ], "Title": "Query the type of a keypath in a JSON Schema" }
237224
<p>Below the text of the <a href="https://leetcode.com/problems/binary-tree-pruning/" rel="nofollow noreferrer">exercise</a>:</p> <blockquote> <p>We are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1.</p> <p>Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.</p> <p>(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)</p> <p>Note:</p> <ul> <li><p>The binary tree will have at most 100 nodes.</p></li> <li><p>The value of each node will only be 0 or 1.</p></li> </ul> </blockquote> <p>I have the following code and it does not look nice to me as too many if statements strolling around. How can I make this shorter and nice looking (more readable). Tree has nodes that contain 0 or 1 as value. I make the node null if it does not contain any node having 1 as value. </p> <pre><code>public TreeNode pruneTree(TreeNode root) { if (root == null || (root.left == null &amp;&amp; root.right == null &amp;&amp; root.val == 0)) return null; Queue&lt;TreeNode&gt; queue = new LinkedList&lt;&gt;(); queue.offer(root); while(!queue.isEmpty()) { TreeNode node = queue.poll(); if (node.left != null &amp;&amp; !containsOne(node.left)) { node.left = null; } if (node.right != null &amp;&amp; !containsOne(node.right)) { node.right = null; } if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } return root; } private boolean containsOne(TreeNode node) { if (node == null) return false; if (node.val == 1) return true; return containsOne(node.left) || containsOne(node.right); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:09:17.367", "Id": "465116", "Score": "3", "body": "Welcome to Code Review. Is this code referring to the exercise [binary tree pruning](https://leetcode.com/problems/binary-tree-pruning/) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T06:34:52.417", "Id": "465203", "Score": "2", "body": "Please add at the challenge description to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T18:04:58.010", "Id": "465308", "Score": "0", "body": "@dariosicily yes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T07:35:58.760", "Id": "465350", "Score": "1", "body": "I've edited your post adding description of the exercise." } ]
[ { "body": "<p>Note: I checked <a href=\"https://leetcode.com/problems/binary-tree-pruning/\" rel=\"nofollow noreferrer\">binary tree pruning</a> and the structure of class TreeNode is not modifiable as I expected:</p>\n\n<pre><code>public class TreeNode {\n int val;\n TreeNode left;\n TreeNode right;\n TreeNode(int x) { val = x; }\n}\n</code></pre>\n\n<p>It's possible to shorten your code with constraints of the class, your method <code>containsOne</code> is the following:</p>\n\n<blockquote>\n<pre><code>private boolean containsOne(TreeNode node) {\n if (node == null) return false;\n if (node.val == 1) return true;\n return containsOne(node.left) || containsOne(node.right);\n}\n</code></pre>\n</blockquote>\n\n<p>Because the third line will be executed when the condition <code>node.val == 1</code> is false put directly this condition in the or expression in the third line:</p>\n\n<pre><code>private static boolean containsOne(TreeNode node) {\n if (node == null) return false;\n return node.val == 1 || containsOne(node.left) || containsOne(node.right);\n}\n</code></pre>\n\n<p>About your method <code>PruneTree</code> you can shorten the following lines inside the method:</p>\n\n<blockquote>\n<pre><code>if (node.left != null &amp;&amp; !containsOne(node.left)) {\n node.left = null; \n}\nif (node.right != null &amp;&amp; !containsOne(node.right)) {\n node.right = null; \n}\nif (node.left != null) {\n queue.offer(node.left);\n}\nif (node.right != null) {\n queue.offer(node.right);\n}\n</code></pre>\n</blockquote>\n\n<p>The code can be rewritten like below, two equal blocks and not so elegant to see but the original structure in the site cannot be modified, so I haven't thought about other alternatives:</p>\n\n<pre><code>if (node.left != null) {\n if (!containsOne(node.left)) { node.left = null; }\n else { queue.offer(node.left); }\n}\n\nif (node.right != null) {\n if (!containsOne(node.right)) { node.right = null; }\n else { queue.offer(node.right); }\n}\n</code></pre>\n\n<p>I checked the code on the site passing all tests.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T11:26:41.167", "Id": "237321", "ParentId": "237229", "Score": "2" } }, { "body": "<p>Unfortunately your attempt is far too complex and LeetCode.com doesn't notice that :(</p>\n\n<p>The problem is that <code>containsOne</code> basically repeats the search for the subtrees that it already has run for in a previous iteration. </p>\n\n<p>Example: </p>\n\n<pre><code> A\n / \\\n B C\n / \\ \nD E\n</code></pre>\n\n<p>You start to search tree A which you do by searching subtrees B and C. In order to search B you search subtrees D and E. Then you move on to subtree B and repeat the search there, including repeating the searches on D and E. Next you move to subtree D and repeat the search there a third time, and so on.</p>\n\n<p>Instead by using a recursive so-called <a href=\"https://en.wikipedia.org/wiki/Tree_traversal#Post-order_(LRN)\" rel=\"nofollow noreferrer\">post-order traversal</a> where you basically start at the bottom (the leaves) of the tree, where you remove any leaves with the value <code>0</code>, you get a much simpler solution:</p>\n\n<pre><code>public TreeNode pruneTree(TreeNode node) {\n\n if (node == null) {\n return null;\n }\n\n node.left = pruneTree(node.left);\n node.right = pruneTree(node.right);\n\n if (node.left == null &amp;&amp; node.right == null &amp;&amp; node.val == 0) {\n return null;\n }\n\n return node;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T11:12:52.133", "Id": "237829", "ParentId": "237229", "Score": "0" } } ]
{ "AcceptedAnswerId": "237321", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T12:40:41.457", "Id": "237229", "Score": "1", "Tags": [ "java", "tree", "binary" ], "Title": "Binary tree pruning with BFS" }
237229
<p>Hi i needed to find the max int of a list using recursion, I have done it this way I'd like to know if you think is a good way, and I have a couple of questions:</p> <pre><code>int trovaMassimo(node_t *head){ int e; if(head == NULL){//this can happen just the first time right? printf("Lista vuota\n"); exit(1); } if(head-&gt;next == NULL) return head-&gt;val; e = trovaMassimo(head-&gt;next); //what will be assigned to e? doing this way doesn't e get modified all times till the last value? if yes isn't useless that if right under? if ( e &lt; head-&gt;val ) return head-&gt;val; else return e; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:02:40.460", "Id": "465127", "Score": "0", "body": "May I ask why it has to be recursive? Good rule of thumb is to avoid recursion." } ]
[ { "body": "<p>You have a portability bug, because names ending in <code>_t</code> are reserved for future Standard Library types. Rename <code>node_t</code>, perhaps to <code>Node</code>.</p>\n\n<hr>\n\n<p>This kind of recursion is problematic, because it can't be transformed into iterative form by the compiler. It needs to keep each call's <code>e</code> value until all the inner recursive calls have completed, before it can do the comparison.</p>\n\n<p>If you can, strive to make your function <em>tail-recursive</em>, which means that it's in the form:</p>\n\n<pre><code>ResultType function(args) {\n ...\n return function(other_args);\n}\n</code></pre>\n\n<p>To make a non-tail recursive function into a tail-recursive one, you generally need to pass the current state into the recursive call.</p>\n\n<p>Here, I'd actually split the function into two: a recursive function to find the <code>node_t</code> with largest value (or <code>NULL</code> if the list is empty), and a wrapper function to call it with the right parameters, extract the result, and handle errors:</p>\n\n<pre><code>/* untested */\n\nstatic const Node *find_node_max(Node *list, Node *best_so_far)\n{\n if (!list) {\n return best_so_far;\n }\n if (!best_so_far || list-&gt;val &gt; best_so_far-&gt;val) {\n best_so_far = list;\n }\n return find_node_max(list-&gt;next, best_so_far);\n}\n\nint trovaMassimo(const Node *head) {\n const Node *n = find_node_max(head, NULL);\n if (!n) {\n /* empty list - N.B. message to stderr, not stdout */\n fputs(\"Lista vuota\\n\", stderr);\n exit(1); /* not good in library code */\n }\n return n-&gt;val;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T13:22:52.203", "Id": "237233", "ParentId": "237231", "Score": "2" } }, { "body": "<p>By</p>\n\n<blockquote>\n <p>doesn't e get modified all times</p>\n</blockquote>\n\n<p>I think you are asking why <code>e</code> retains its original value even after it gets changed by recursive calls.</p>\n\n<p>Part of the misunderstanding is the way <code>e</code> is defined:</p>\n\n<pre><code>int e;\n</code></pre>\n\n<p>If you had instead said:</p>\n\n<pre><code>static int e;\n</code></pre>\n\n<p>then yes, every time the value gets changed in a recursive call, the value in the calling function will also get changed.\nWith static storage there is only a single instance of <code>e</code>.\nDefining it that way would indeed have produced incorrect results.</p>\n\n<p>If you had instead said:</p>\n\n<pre><code>auto int e;\n</code></pre>\n\n<p>then no, the recursive calls will not affect the value in the calling function.\nEach invocation of the function causes storage to be <em>auto</em>matically allocated on the stack for another instance of <code>e</code>.\nIf it recurses a thousand times, at the deepest level there will be a thousand distinct instances of <code>e</code> on the stack.\nAnd at each level, the function can see only its own copy.</p>\n\n<p>Now C has a history of letting programmers be lazy (one of its major faults), and if one omits the word \"auto\" or \"static\" the compiler notices the context and decides what you really meant.</p>\n\n<p>In this case, it did the right thing (it almost always does) and knew that you really meant \"auto\", and allocated a separate storage location for each invocation.</p>\n\n<p>Most programmers <em>do</em> omit the keyword <code>auto</code>, but I prefer to always use it, both to remind me that it <em>isn't</em> static, global, external, or (in older versions) block common, and to make it easier to find when I'm searching for definitions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:48:29.427", "Id": "237245", "ParentId": "237231", "Score": "1" } } ]
{ "AcceptedAnswerId": "237233", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T12:56:40.070", "Id": "237231", "Score": "0", "Tags": [ "c99" ], "Title": "Find the max of a list using recursion" }
237231
<p>My code in MS project VBA, in theory, doesn't do anything major.<br> It compares the tasks with each other, but it runs super slow.</p> <p>One run through <code>Temp</code> lasts 15 secs. Try that with 1500-2000 tasks and the macro takes hours.</p> <pre><code>Sub Laczona() Application.Calculation = xlManual Application.ScreenUpdating = False Dim Temp, Temp2 As Integer For Temp = 1 To ActiveProject.Tasks.Count For Temp2 = 1 To ActiveProject.Tasks.Count If ActiveProject.Tasks(Temp).Text30 = ActiveProject.Tasks(Temp2).Text30 Then If Temp &lt;&gt; Temp2 Then ActiveProject.Tasks(Temp).Flag5 = 1 End If End If Next Temp2 MsgBox "Praca: " &amp; Temp Next Temp MsgBox "Prace Laczone Uzupelnione" Application.ScreenUpdating = True Application.Calculation = xlAutomatic End Sub </code></pre> <p>Addidional explanation:<br> The code runs in MS Project 2013. Its purpose is to check whether two tasks have the same text in field Text30. If that is the case, the code sets flag5 to 1.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T14:15:45.543", "Id": "465101", "Score": "3", "body": "You have two loops, so 1500 * 1500 or 2000 * 2000 = 2,250,000 to 4,000,000 iterations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T14:17:29.353", "Id": "465102", "Score": "0", "body": "Indeed, but shouldn't 4mil operations be a breeze for a 2,4 ghz processor?" } ]
[ { "body": "<p>An immediately obvious improvement would be to start the inner loop from Temp+1.</p>\n\n<pre><code>Sub Laczona()\n Application.Calculation = xlManual\n Application.ScreenUpdating = False\n Dim Temp, Temp2 As Integer\n Dim text30 As String\n For Temp = 1 To ActiveProject.Tasks.Count\n If ActiveProject.Tasks(Temp).Flag5 &lt;&gt; 1 Then\n text30 = ActiveProject.Tasks(Temp).Text30;\n For Temp2 = Temp + 1 To ActiveProject.Tasks.Count\n If ActiveProject.Tasks(Temp2).Flag5 &lt;&gt; 1\n And text30 = ActiveProject.Tasks(Temp2).Text30 Then\n ActiveProject.Tasks(Temp).Flag5 = 1\n ActiveProject.Tasks(Temp2).Flag5 = 1\n End If\n Next Temp2\n End If\n 'MsgBox \"Praca: \" &amp; Temp\n Next Temp\n MsgBox \"Prace Laczone Uzupelnione\"\n Application.ScreenUpdating = True\n Application.Calculation = xlAutomatic\nEnd Sub\n</code></pre>\n\n<p>Still quadratic complexity. <strong>Sorting on Text30</strong> would really improve the speed,\nbut whether that is feasible; you would need an extra index etcetera I do not know.</p>\n\n<p>Above I checked Flag5 too, as that might be faster - or just as likely not.</p>\n\n<p>MsgBox in a loop probably was only for testing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T14:55:18.777", "Id": "237238", "ParentId": "237235", "Score": "3" } }, { "body": "<p>If I understand correctly, you are testing to see if there are any duplicate entries in Text30 and if you find a duplicate setting flag 5 to 1.</p>\n\n<p>In this case you are duplicating at least half of the tests that you are conducting because Task(1).Text(30) = Task(2).Text30 is the same comparison as Tasks(2).Text30 = Task(1).Text30.</p>\n\n<p>So you can cut down on the number of tests that you do by eliminating tests that you have already performed. This is done by starting the inner loop at the current value of the outer loop.</p>\n\n<p>e.g. </p>\n\n<pre><code>For Temp2 = 1 To ActiveProject.Tasks.Count\n</code></pre>\n\n<p>should be revised to</p>\n\n<pre><code>For Temp2 = Temp To ActiveProject.Tasks.Count\n</code></pre>\n\n<p>However an even quicker way would be to use a Scripting.Dictionary. I don't have project installed on my PC but even so if the code below doesn't work it should at least point you in the right direction</p>\n\n<pre><code>Sub Lacunza()\n\n Dim myUniqueText30 As Scripting.Dictionary\n Set myUniqueText30 = New Scripting.Dictionary\n\n Dim myTask As Long\n For myTask = 1 To ActiveProject.Tasks.Count\n\n With ActiveDocument.Tasks(myTask)\n\n If myUniqueText30.Exists(.Text30) Then\n\n .Flag5 = 1\n\n Else\n\n myUniqueText30.Add Key:=.Text30, Item:=myTask\n\n End If\n\n Next\n\n ' As this point you have a scripting dictionary which will return the task id\n ' where the first occurence of a particular Text30 value was found.\n\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T14:56:39.687", "Id": "237239", "ParentId": "237235", "Score": "7" } }, { "body": "<p>I am not familiar with Project VBA, but wouldn't it be much faster to use filters and iterate that instead? </p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/office/vba/api/project.filter\" rel=\"nofollow noreferrer\">Filters object</a></p>\n\n<p>IOW, don't try to brute-solve it. Learn the object model and find the object/method that will help you do it since their implementation will be much faster than any loops you come up with, on average.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:18:39.890", "Id": "237242", "ParentId": "237235", "Score": "3" } }, { "body": "<p>In a slightly different implementation from @FreeFlow's answer, this code also uses a <code>Dictionary</code> but it builds a list of duplicate tasks for each <code>Text30</code> value. Then uses that task list to set <code>Flag5</code>. Tested on a very large project (>1100 tasks) it runs in less than 15 seconds.</p>\n\n<pre><code>Option Explicit\n\nSub CheckForDuplicates()\n\n Application.Calculation = pjManual\n Application.ScreenUpdating = False\n\n Dim text30values As Dictionary\n Set text30values = New Dictionary\n\n Dim taskList As String\n With ActiveProject\n '--- for each of the text30 values, create a list of tasks that contain\n ' each value. For example, if \"abc\" appears in tasks 17,18,23, and 50\n Dim i As Long\n For i = 1 To .Tasks.Count\n If .Tasks(i).Text30 &lt;&gt; vbNullString Then\n If text30values.Exists(.Tasks(i).Text30) Then\n taskList = text30values(.Tasks(i).Text30) &amp; \",\" &amp; i\n text30values(.Tasks(i).Text30) = taskList\n Else\n text30values.Add Key:=.Tasks(i).Text30, Item:=i\n End If\n End If\n Next i\n\n '--- now run through each entry and set the flag field for the duplicates\n ' entries with duplicates will be CSV lists, so we're looking for a comma\n For i = 0 To text30values.Count - 1\n taskList = text30values.Items(i)\n If InStr(1, taskList, \",\") &gt; 0 Then\n Dim theTasks As Variant\n theTasks = Split(taskList, \",\")\n Dim j As Long\n For j = LBound(theTasks) To UBound(theTasks)\n .Tasks(CLng(theTasks(j))).Flag5 = 1\n Next j\n End If\n Next i\n End With\n\n Application.Calculation = pjAutomatic\n Application.ScreenUpdating = True\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T12:08:39.110", "Id": "465553", "Score": "0", "body": "Works! Nice thank You." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:46:08.680", "Id": "237244", "ParentId": "237235", "Score": "2" } }, { "body": "<p>I would like to refresh the topic a little bit.\nThe problem is that using Visual Basic inside my MSProject I constantly get 91 Run-time error.\nI've even copied the solutions above to check if the exactly same code also doesn't work and I've got also the 91 Run-time error.\nI've marked that it happens always when I want to use a task number from For loop like:</p>\n<pre><code> With ActiveProject\n For i = 1 To ActiveProject.Tasks.Count\n If .Tasks(i).Text13 &lt;&gt; &quot;&quot; Then\n If text13values.Exists(ActiveProject.Tasks(i).Text13) Then\n taskList = text13values(ActiveProject.Tasks(i).Text13) &amp; &quot;,&quot; &amp; i\n text13values(ActiveProject.Tasks(i).Text13) = taskList\n Else\n text13values.Add Key:=ActiveProject.Tasks(i).Text13, Item:=i\n End If\n End If\n Next i\n\n End With\n</code></pre>\n<p>&quot;If .Tasks(i).Text13 &lt;&gt; &quot;&quot; Then&quot; is highlited and gives &quot;Object variable or With block variable not set&quot;. No matter how simple is the code, it doesn't work with this kind of For loop.\nPS. MSProject is in version 2016.\nMany thanks for any advise!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T17:25:32.517", "Id": "506157", "Score": "0", "body": "This doesn't seem to be a review of the code in the question. Could you clarify which part of the code you're addressing, and what should be changed?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-23T15:50:42.453", "Id": "256380", "ParentId": "237235", "Score": "-1" } } ]
{ "AcceptedAnswerId": "237244", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T14:07:46.890", "Id": "237235", "Score": "3", "Tags": [ "performance", "vba" ], "Title": "Find duplicated text for tasks in MS Project" }
237235
<p>I am working on an implementation of <a href="https://github.com/xbarin02/x-compressor" rel="nofollow noreferrer">the minimalist compression method</a>. The method is based on context modeling, followed by a simple entropy coder (<a href="https://codereview.stackexchange.com/questions/236965/minimalist-golomb-rice-coder">Golomb-Rice coder</a>). The context model uses a single previous byte in the uncompressed symbol stream to predict the next byte. At the moment, my implementation works quite well. However, I wonder if it is possible to make it faster or more concise. Basically, any suggestions for improvement are welcome.</p> <h2>Prerequisites</h2> <p>The implementation uses the following data structure:</p> <pre><code>struct context { size_t freq[256]; /* char -&gt; frequency */ unsigned char sorted[256]; /* index -&gt; char */ unsigned char order[256]; /* char -&gt; index */ } table[256]; </code></pre> <p>The functions <code>bio_open</code>, <code>bio_write_gr</code>, <code>bio_read_gr</code>, and <code>bio_close</code> implement the entropy (Golomb-Rice) coding.</p> <p>Moreover, the function <code>void update_model(unsigned char delta)</code> updates the entropy model according to the newly encoded byte <code>delta</code> (not the subject of this review).</p> <h2>Code</h2> <p>I use several two auxiliary functions:</p> <pre><code>static void swap_symbols(struct context *context, unsigned char c, unsigned char d) { assert(context != NULL); unsigned char ic = context-&gt;order[c]; unsigned char id = context-&gt;order[d]; assert(context-&gt;sorted[ic] == c); assert(context-&gt;sorted[id] == d); context-&gt;sorted[ic] = d; context-&gt;sorted[id] = c; context-&gt;order[c] = id; context-&gt;order[d] = ic; } static void increment_frequency(struct context *context, unsigned char c) { assert(context != NULL); unsigned char ic = context-&gt;order[c]; size_t freq_c = ++(context-&gt;freq[c]); unsigned char *pd; for (pd = context-&gt;sorted + ic - 1; pd &gt;= context-&gt;sorted; --pd) { if (freq_c &lt;= context-&gt;freq[*pd]) { break; } } unsigned char d = *(pd + 1); if (c != d) { swap_symbols(context, c, d); } } </code></pre> <p>The main entry functions are defined as follows:</p> <pre><code>void init() { opt_k = 3; for (int p = 0; p &lt; 256; ++p) { for (int i = 0; i &lt; 256; ++i) { table[p].sorted[i] = i; table[p].freq[i] = 0; table[p].order[i] = i; } } } void *compress(void *iptr, size_t isize, void *optr) { struct bio bio; unsigned char *end = (unsigned char *)iptr + isize; struct context *context = table + 0; bio_open(&amp;bio, optr, BIO_MODE_WRITE); for (unsigned char *iptrc = iptr; iptrc &lt; end; ++iptrc) { unsigned char c = *iptrc; /* get index */ unsigned char d = context-&gt;order[c]; bio_write_gr(&amp;bio, opt_k, (uint32_t)d); assert(c == context-&gt;sorted[d]); /* update context model */ increment_frequency(context, c); /* update Golomb-Rice model */ update_model(d); context = table + c; } /* EOF symbol */ bio_write_gr(&amp;bio, opt_k, 256); bio_close(&amp;bio, BIO_MODE_WRITE); return bio.ptr; } void *decompress(void *iptr, void *optr) { struct bio bio; struct context *context = table + 0; bio_open(&amp;bio, iptr, BIO_MODE_READ); unsigned char *optrc = optr; for (;; ++optrc) { uint32_t d = bio_read_gr(&amp;bio, opt_k); if (d == 256) { break; } assert(d &lt; 256); unsigned char c = context-&gt;sorted[d]; *optrc = c; increment_frequency(context, c); update_model(d); context = table + c; } bio_close(&amp;bio, BIO_MODE_READ); return optrc; } </code></pre>
[]
[ { "body": "<h2>Symbolic Constants</h2>\n<p>This code could use some symbolic constants:</p>\n<pre><code>struct context {\n size_t freq[256]; /* char -&gt; frequency */\n unsigned char sorted[256]; /* index -&gt; char */\n unsigned char order[256]; /* char -&gt; index */\n} table[256];\n\nvoid init()\n{\n opt_k = 3;\n\n for (int p = 0; p &lt; 256; ++p) {\n for (int i = 0; i &lt; 256; ++i) {\n table[p].sorted[i] = i;\n table[p].freq[i] = 0;\n table[p].order[i] = i;\n }\n }\n}\n</code></pre>\n<p>The use of symbolic constants would make this code easier to write and maintain. For example if there was a symbolic constant for <code>256</code> the size of the table and the loop controls could be changed with a single line edit.</p>\n<h2>Global Variables</h2>\n<p>In the function <code>init()</code> above, it is obvious that global variables are being used, <code>table</code> is on global variable and <code>opt_k</code> is another global variable.</p>\n<p>Global variables are generally considered a bad programming practice, they make the code hard to write, debug and maintain. They also make it very easy to introduce bugs.</p>\n<p>In the C programming language if the program consists of multiple files, it is possible that global variables can cause the program not to link if they are declared in multiple files.</p>\n<h2>Using <code>assert()</code> in C</h2>\n<p>If at some point the code is going to be compiled for release using the optimizing feature of the compiler, then the <code>assert()</code> statements will be optimized away. If the error checking provided by the asserts is required it will be better to replace the asserts with if statements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T21:00:34.260", "Id": "465169", "Score": "1", "body": "OP is explicitly using any `unsigned char` as an index. A good substitute for 256 would be `size_t freq[UCHAR_MAX +1u];`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:02:42.333", "Id": "237247", "ParentId": "237236", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T14:08:44.753", "Id": "237236", "Score": "4", "Tags": [ "performance", "c", "compression" ], "Title": "Minimalist context compressor" }
237236
<p>This program finds the 100th member of the <a href="https://oeis.org/A005150" rel="nofollow noreferrer">"look and say" sequence</a>:</p> <blockquote> <ul> <li>1</li> <li>11 (one 1)</li> <li>21 (two 1's)</li> <li>1211 (one 2 and one 1)</li> <li>111221 (one 1, one 2, two 1's)</li> <li>312211 etc.</li> </ul> </blockquote> <pre class="lang-py prettyprint-override"><code>from itertools import groupby, chain def _look_and_say(seq: str): return ''.join(f"{len(list(g))}{k}" for k, g in groupby(seq)) a = '1' for i in range(100): a = _look_and_say(a) print(a) </code></pre> <hr> <p>Obviously I need to replace the loop with proper code.</p> <p>I was trying to use <code>functools.reduce</code></p> <pre class="lang-py prettyprint-override"><code>reduce(lambda x, count: _look_and_say(x), chain('1', range(30))) </code></pre> <p>but that doesn't look good.</p> <p>Also is there a better way to do this: <code>len(list(g)</code> if g is an iterator?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:48:59.923", "Id": "465122", "Score": "0", "body": "This is what I'm doing, I was generalizing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:53:54.787", "Id": "465124", "Score": "2", "body": "It Is not at all obvious why for loop Is not a \"proper code\" And why you need to replace it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:27:45.123", "Id": "465132", "Score": "0", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T06:33:15.537", "Id": "465202", "Score": "0", "body": "@slepic I think OP is looking for an FP approach." } ]
[ { "body": "<p>I think iterators are amazing. However not everything should be an iterator, or use comprehensions.\nStatements like:</p>\n\n<blockquote>\n <p>Obviously I need to replace the loop with proper code.</p>\n</blockquote>\n\n<p>Only make me see short-sighted snobbishry. Which I only see in the FP vs OOP part of the programming world. Iterators and comprehensions can't and shouldn't be jammed into everything.</p>\n\n<hr>\n\n<ul>\n<li>The function <code>_look_and_say</code> looks pretty good.</li>\n<li>Rather than assigning <code>i</code> and never using it, it's commonly accepted to use <code>_</code> as a throw away variable.</li>\n<li><p>Python has a style guide, which a large amount of users follow. This style guide suggests putting two empty lines around top level functions and classes.</p>\n\n<p>I would recommend you do this too, so that your code looks like everyone elses. Which improves readability for everyone.</p></li>\n<li><p>It's best not to have code run in the global scope, just wrap it up in a <code>main</code>.</p></li>\n<li>You should wrap your code in a <code>if __name__ == '__main__':</code>, making your code only run if you run the file. As opposed to importing it.</li>\n</ul>\n\n<p>Which results in the following <em>proper code</em>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import groupby, chain \n\n\ndef _look_and_say(seq: str):\n return ''.join(f\"{len(list(g))}{k}\" for k, g in groupby(seq))\n\n\ndef main():\n a = '1'\n for _ in range(100):\n a = _look_and_say(a)\n print(a)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<hr>\n\n<p>I would prefer <code>_look_and_say</code> to return all look and say numbers, and for main to stop <code>_look_and_say</code> when it has reached the number it wants.</p>\n\n<p>To do this I would move the for loop into <code>_look_and_say</code> as a <code>while True:</code> loop. Change it so you <code>yield</code> from the function. And then finally use <code>itertools.islice()</code> to extract the desired number, with the <code>nth</code> recipe.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\n\n\ndef look_and_say():\n value = '1'\n while True:\n yield value\n value = ''.join(f\"{len(list(g))}{k}\" for k, g in itertools.groupby(value))\n\n\ndef nth(iterator, n, default=None):\n return next(itertools.islice(iterator, n , None), default)\n\n\ndef main():\n print(nth(look_and_say(), 100 - 1))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T13:05:38.450", "Id": "465257", "Score": "0", "body": "I'm not saying loops shouldn't be used, I wanted to replace this one. I just find `x = f(x)` as an only expression in a loop weird." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T13:12:03.523", "Id": "465260", "Score": "0", "body": "@Kazz Ok. I found your question highly unclear in that regard, and given that in both your questions you've pretty much asked \"please make this only use iterators\" the perception you gave off didn't help. (And yes you did in this one, as you provided that second piece of code that only used iterators). Good code is no code; `x = f(x)` is no code, so good code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T17:13:15.943", "Id": "237252", "ParentId": "237240", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:05:39.750", "Id": "237240", "Score": "-4", "Tags": [ "python", "python-3.x" ], "Title": "Generate the 100th \"look and say\" number" }
237240
<p>I have implemented a function <code>mcollect</code> which is effectively <code>mconcat</code> only for applicative monoids:</p> <pre><code>mcollect :: Applicative f =&gt; Monoid (f a) =&gt; [a] -&gt; f a mcollect = mconcat . fmap pure </code></pre> <p>However I am not overly keen on the name <code>mcollect</code>, an alternative name in the spirit of <code>mconcat</code> is <code>amconcat</code> which I am not keen on either. Looking on Hoogle there does not appear to be anything like this in any libraries, that I can find. Does something like this exist somewhere already, I've just missed it? Is there a better name for this function?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:41:39.430", "Id": "465137", "Score": "0", "body": "could you clarify why lifting applicative monoids into `Ap` as already supported by `mconcat` is not sufficient for your purposes?" } ]
[ { "body": "<p>I wouldn't give this a name. It is equal to <code>foldMap pure</code> and feels to me like it might be refactored away with more context.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T13:09:24.973", "Id": "237292", "ParentId": "237243", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:38:44.753", "Id": "237243", "Score": "1", "Tags": [ "haskell", "functional-programming" ], "Title": "Name for mconcat implementation for applicative monoid" }
237243
<h3><a href="https://codeforces.com/problemset/problem/331/C3" rel="nofollow noreferrer">Challenge</a></h3> <blockquote> <p>An integer is provided as an input. In each step, we have to subtract a number from the input which already exists as a digit of the input. In this way, we have to make the input equal to zero(<code>0</code>). The problem is to output the minimum number of such steps.</p> </blockquote> <h3>Code</h3> <pre><code>n=int(input()) count=0 while n: l=list(int(i) for i in str(n)) n=n-max(l) count+=1 if n == 0: break print (count) </code></pre> <hr> <p>The code outputs the correct results; but on larger input it exceeds the time limits. That is, for every input memory consumption increases and the time limit is reached up until the 30th test case.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:58:09.410", "Id": "465125", "Score": "1", "body": "Please could you provide the exact wording of the error, \"but shows runtime error for larger inputs\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:02:01.890", "Id": "465126", "Score": "0", "body": "@Peilonrayz edited my question. Sorry for the wrong word. It'll be time limit error. After the 29th input, code forces shows time limit exceeded ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:07:13.440", "Id": "465129", "Score": "2", "body": "Please could you include a description of the challenge. Questions and answers on the Stack Exchange network should be self-contained, as you never know when another site is going to 404, or if our users are behind a firewall that blocks it. Please could you also include the exact error description too. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:13:14.680", "Id": "465130", "Score": "0", "body": "@Peilonrayz I've added the description..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:33:50.640", "Id": "465134", "Score": "0", "body": "It would also help including the memory and time constraints, and some test cases, most importantly the one that fails for you. How big is that number? I couldn't tell without creating an account on that site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:39:38.477", "Id": "465135", "Score": "0", "body": "@gazoh time limit per test:2 seconds,memory limit per test:256 megabytes...the memory is gradually consumed and it stalls for test case no 30:1278564645" } ]
[ { "body": "<ol>\n<li>You don't need to actually build a whole list of the digits. It's unnecessary memory consumption. You can pass a generator to max. </li>\n<li>use python's -= syntax when subtracting from a variable. </li>\n<li>The break is unnecessary as it's covered by the while condition </li>\n</ol>\n\n<p>Final code:</p>\n\n<pre><code>n=int(input()) \ncount=0\n\nwhile n:\n n -= max(int(i) for i in str(n))\n count += 1\n\nprint (count)\n</code></pre>\n\n<p>This code would be fairly difficult to improve much further for efficiency. You could really penny pinch performance on the generator by building a generator that will stop iteration after it encounters a 9, as it knows it cannot ever get a number bigger than that. You could also use modulo and integer division logic to extract digits to avoid having to go from int -> str -> int. </p>\n\n<hr>\n\n<p>Okay. This is now straying pretty far from the original question, but I liked the challenge and @Mast in the comments expired me by mentioning memoization. </p>\n\n<p>To utilize memoization the problem needed to be formulated in a recursive way where I can store the result of intermediate calls to avoid re-computation of things already computed. The strategy was to define the recursive function \"compute_count(previous_max, rest)\", where previous_max is initially called with 0, and rest as the entire number. </p>\n\n<p>The idea is that a max, num pair uniquely identifies a solution, so every time we end up with the same max, num pair we can use the precomputed result. Formulating the problem in this way led to writing a fairly complicated function, but on the example you provided in the comments it returns instantly. The memoization table ends up with 293 entries, so it's well within your 256MB limit. </p>\n\n<p>Anyway, here's the final code:</p>\n\n<pre><code>memoization_table = {}\n\ndef compute_count(previous_max, rest):\n global memoization_table \n original_rest = rest\n\n if (previous_max, rest) in memoization_table:\n return memoization_table[(previous_max, rest)] \n\n num_digits = len(str(rest))\n\n if num_digits == 1:\n memoization_table[(previous_max, original_rest)] = 1, min(0, rest-previous_max) \n return 1, min(0, rest-previous_max) \n\n sum_count = 0\n while rest &gt; 0:\n s = str(rest).zfill(num_digits)\n new_max = max(previous_max, int(s[0])) \n new_rest = int(s[1:])\n count, leftover = compute_count(new_max, new_rest) \n\n sum_count += count \n rest -= new_rest\n rest += leftover\n\n memoization_table[(previous_max, original_rest)] = sum_count, rest\n return sum_count, rest\n\nprint(compute_count(0, 1278564645)[0])\nprint(len(memoization_table))\n</code></pre>\n\n<p>I imported the length of the memoization table just to see the memory implications of the solution, and it turned out to be very reasonable. Obviously remove this from any submitted solutions.</p>\n\n<p>Here's the output of the run:</p>\n\n<pre><code>$ python compute_count.py \n154026551\n293\n</code></pre>\n\n<hr>\n\n<p>Example:</p>\n\n<p>For calculating 24, these are the function calls made: </p>\n\n<pre><code>compute_count(0,24)\ncompute_count(2,4)\ncompute_count(2,0)\ncompute_count(1,8)\ncompute_count(1,0)\ncompute_count(0,9)\n</code></pre>\n\n<p>To calculate compute_count(0, 24):</p>\n\n<ol>\n<li><p>get new previous_max, which is the max of 0 and 2. </p></li>\n<li><p>do a compute_count on 2,4. Since this is a single digit number, it's our base case, and we return that we can get to 0 with a single move (as is the case with all single digit numbers). </p></li>\n<li><p>Since we did a compute_count(2,4) which told us it did a single computation, we need to subtract the number computed for (4) from our running number (24). This gives us a remainder of 20, and a running count of 1. </p></li>\n<li><p>The new previous_max is still 2, as our remainder is 20.</p></li>\n<li><p>do a compute_count on 2,0. This one is a special case. Getting from 0 to 0 should technically take no moves, but we have additional logic for these cases because the previous max is 2. Which means this isn't <em>really</em> a single digit number, and I need to return the \"leftover\" which is -2 so the caller can account for the underflow of the subtraction. So this function returns a count of 1, and a leftover of -2</p></li>\n<li><p>Since we passed 0 to compute_count, we subtract 0 from our 20 which keeps us at 20. But because a leftover of -2 was returned, we also have to add that to our 20 which gives us a total of 18 for this iteration. </p></li>\n<li><p>The above process continues in kind until our remaining is 0 or less and we've summed all the counts. </p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:40:00.477", "Id": "465136", "Score": "0", "body": "will it run faster?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:41:56.680", "Id": "465138", "Score": "0", "body": "@NehalSamee It should take less memory as it doesn't have to actually create a list, and definitely takes less memory. But it's fairly minor. I added a bit at the bottom of how you could get more efficiency out of it. It's a little trickier." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:43:53.780", "Id": "465139", "Score": "0", "body": "well I tried using the modulo method with vector in c++ ... it was more efficient than python, but was not sufficient to pass all the test cases" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:44:31.693", "Id": "465140", "Score": "0", "body": "How is the timing enforced? Do you submit it remotely, or run it locally?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T17:30:52.457", "Id": "465143", "Score": "0", "body": "remotely from my pc..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T17:55:07.773", "Id": "465148", "Score": "2", "body": "@NehalSamee Perhaps you need to use a smarter algorithm. Like, say the number is 9123123123, then you can actually subtract `9 * ceil(123123123 / 9)` immediately, because you know the 9 won't change until the 123123123 has been subtracted causing the 9 to become an 8" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T18:56:19.493", "Id": "465153", "Score": "1", "body": "That's probably part of the trick indeed, excluding calculations based on calculations you've already done in the past. Got something to do with Memoization I think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T19:02:47.543", "Id": "465155", "Score": "0", "body": "@Mast It's pretty tricky to do much memoization on the problem. Like, what could you memoize? Store a lookup table of the \"answers\" for the last n digits, to skip many calculations, but those answers change based on what numbers are earlier in the number. This is actually feels fairly non-trivial to optimize. I reckon the 9 trick I mentioned should give ~10% speed up, but I'm not sure what else you can do. You can't do that with 8, because with 8 you'll get sporadic 9s that pop up in the lower significance digits when you're trying to cheat. Perhaps I'm missing something" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T19:09:47.447", "Id": "465157", "Score": "0", "body": "Yea, I feel we're both missing something here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T19:55:57.720", "Id": "465160", "Score": "1", "body": "@Mast I managed to do it! Thanks for the suggestion. See the edit. This is a huge rabbithole from the original question, but I believe this is what they're expecting for optimal efficiency." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T19:57:27.287", "Id": "465161", "Score": "0", "body": "@NehalSamee See my edit. Does this pass your challenge now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T16:11:22.540", "Id": "465295", "Score": "0", "body": "okay...so I can't understand which part is doing what" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T16:23:25.707", "Id": "465298", "Score": "0", "body": "@NehalSamee So, the relationship is defined recursively. That is, compute_count(x, y) is a continued compute_count on the remaining part after substringing the first digit off of y, until we have a number less than or equal to 0. It's contrived, but by building the relationship recursively it allows us to store the answer to sub problems. It twisted my brain to write the code, and it's certainly not easy to understand" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T16:37:51.513", "Id": "465299", "Score": "0", "body": "@NehalSamee I added an edit to try and explain it. I ran through an example for compute_count(0,24)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T18:05:18.190", "Id": "465309", "Score": "0", "body": "Thanks ! It worked ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T18:35:10.400", "Id": "465315", "Score": "0", "body": "And it would be helpful if you explained it for a larger number like 183...you see I'm new to python as well as memoization techniques of dynamic programming. So what the memoization saves is important for me to know ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T18:43:07.947", "Id": "465316", "Score": "0", "body": "@NehalSamee [You can generate the recursive calls readably](https://tio.run/##nVPbjoIwEH3nKyY@0RUNxJeNCfsjriGoRZuUlpSiuxK@nZ22yEXMbrJ9KEnnzJlzZobiW1@k2LRtTnPJ7qlmUiQ6PXAKMdSN551oBkeZF5WmyVFWQvuFolcmqzLJ068AFC11AALv5EQLfYlDsvUAT6EYghd1M82um6BuyGKdSZWnGP/Ui7chO4A5OyGW78zlIeUw12mjUrEzEylPTAZKNx/PRlgGLyQTYGLO5ZSbo6iu1AvE7hXXHlwpUeXJCXXoEhVwKvxSK7@z8NAyxsQQDRX/LDWxiDUxO4CcCT90MlZjOIFnK7@DLbpEbXZKyB3al9uFYYdtTz8gHMQag7259T1jnPuDM9LjBL2ZAojG@8mPWY9yF@7JSKvBdxN04Wi7H9istgA7m2l5pQpB093qqgU9zXgxl9HD5tTqMna844ahgFXcs0wDy7gX4Oj@Mbi@uhuGNxrTc8hz/9HUKA4xet8Q07wubrZtJgTXrm1/AA)" } ], "meta_data": { "CommentCount": "17", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T16:34:15.287", "Id": "237249", "ParentId": "237246", "Score": "3" } } ]
{ "AcceptedAnswerId": "237249", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T15:52:26.457", "Id": "237246", "Score": "0", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "The Great Julya Calendar" }
237246
<p>My (simple) game engine has one big fragment shader for the whole scene. Right now, with multiple objects, collision detection and bloom post-processing (4 linear passes) I get frame times of ~18ms at 1080p on my AMD RX550 (2GB) - which is quite okay for me.</p> <p>But I think that I can squeeze more fps out of my setup. Since increasing the window size dramatically influences the frame times, I figure that the issue might be the fragment shader.</p> <p>It works a little bit like this:</p> <pre><code>main() { outputcolor = objectbasecolor; // from uniform if(switchForTextureDiffuse &gt; 0) // &gt;0 means "use a texture" { outputcolor *= texture(uniformTexture, vTextureCoords); } // the same goes for normal map, specular map and emissive map // with the needed calculations only being done if a switch // (i.e. switchForNormalMapping &gt; 0) is set to 1. for(int i = 0; i &lt; lightcount; i++) // lightcount is a uniform as well { // do light calculations (dot product, use light color, calculate falloff, etc.) // and add the illumination to the color output } } </code></pre> <p>Now, I know that if/else is no good idea, especially in a fragment shader. But I do not want to rebuild this shader completely from scratch only to find out that the ifs/elses did no harm to my frame times at all.</p> <p>From your experiences, what really makes the frame times be better?</p> <ol> <li>Use texture compression (like DXT1, DXT5) instead of just uncompressed bitmaps?</li> <li>Get rid of all ifs and elses by creating a lot of different shaders (like one for only diffuse and normal maps and another shader for using diffuse, normal and specular maps?</li> <li>Reduce the number of frame buffers for bloom effect (right now I have the normal framebuffer, one for vertical blur and one for horizontal blur) by creating more texture attachments for only one framebuffer?</li> </ol> <p>Point 2 would be a really great heap of work, so I need to be sure that this really has an effect on my frame times. Also, I would have to switch GL programs a lot, because not all of my models have normal or specular maps. And I read that switching render programs also takes a lot of time.</p> <p>Cheers and thanks for your inputs!</p> <p>P.S.: I know deferred lighting would also be a huge performance increase if there are many light sources in the scene, but the number of lights will not be > 3.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:28:58.663", "Id": "465236", "Score": "2", "body": "The details of your light calculation are important as well," } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T17:12:09.670", "Id": "237251", "Score": "1", "Tags": [ "c#", "performance", "opengl", "shaders" ], "Title": "OpenGL fragment shader optimization questions" }
237251
<p>Since I haven't really used Python's new async features yet, I took some older code of mine, which took all of my answers here on Code Review and generated a word cloud from them, and updated it to fetch the pages in an asynchronous way.</p> <p>This script uses the <a href="https://pypi.org/project/py-stackexchange/" rel="nofollow noreferrer"><code>py-stackexchange</code></a> package for the API (don't forget to <a href="https://meta.stackexchange.com/q/261829/342577">get your API key</a> in order to increase the number of requests you can make to 10k). There are other packages for the API out there, but this one is easy to use IMO, especially for getting all questions/answers of one particular user. However, unfortunately (or luckily for me) it does not support getting the body of an answer (only of a question). So that part is done with <a href="https://pypi.org/project/aiohttp/" rel="nofollow noreferrer"><code>aiohttp</code></a> and <a href="https://pypi.org/project/beautifulsoup4/" rel="nofollow noreferrer"><code>BeautifulSoup</code></a>, which is where the asynchronous part comes in. The text is split into words using <a href="https://pypi.org/project/nltk/" rel="nofollow noreferrer"><code>nltk</code></a> and the word cloud is generated via <a href="https://pypi.org/project/wordcloud/" rel="nofollow noreferrer"><code>wordcloud</code></a>.</p> <p>To install everything:</p> <pre class="lang-bsh prettyprint-override"><code>$ pip install aiohttp bs4 lxml matplotlib nltk py-stackexchange wordcloud $ python &gt;&gt;&gt; import nltk &gt;&gt;&gt; nltk.download('punkt') </code></pre> <p>Any and all feedback, especially on the use of the async stuff, is welcome. Maybe I should've split up fetching the page and processing it more? Maybe I missed some important performance trick?</p> <pre><code>import aiohttp import asyncio from bs4 import BeautifulSoup, SoupStrainer from itertools import chain import matplotlib.pyplot as plt from nltk.tokenize import word_tokenize import stackexchange from wordcloud import WordCloud API_KEY = '**redacted**' # https://meta.stackexchange.com/q/261829/342577 CR = stackexchange.Site("CodeReview", API_KEY) STRAINER = SoupStrainer( 'div', attrs={'class': ['answer', 'answer accepted-answer']}) async def fetch(session, url, answer_id): async with session.get(url) as response: page = await response.text() soup = BeautifulSoup(page, "lxml", parse_only=STRAINER) try: answer_text = soup.select_one( f'div#answer-{answer_id} div.post-text').text except AttributeError: print("Failure:", url) return [] else: print("Success:", url) return word_tokenize(answer_text) async def fetch_all(urls, answer_ids): async with aiohttp.ClientSession() as session: jobs = [fetch(session, url, answer_id) for url, answer_id in zip(urls, answer_ids)] results = await asyncio.gather(*jobs) return results if __name__ == "__main__": user = CR.user(98493) # that's me user.answers.fetch() # needed to initialize it... urls = (answer.url.replace(CR.domain, "codereview.stackexchange.com") for answer in user.answers) answer_ids = (answer.id for answer in user.answers) loop = asyncio.get_event_loop() words = list(chain.from_iterable( loop.run_until_complete(fetch_all(urls, answer_ids)))) plt.figure() wordcloud = WordCloud(width=480, height=480, colormap="Blues") wordcloud = wordcloud.generate(" ".join(words)) plt.imshow(wordcloud, interpolation="bilinear") plt.axis("off") plt.margins(x=0, y=0) plt.show() </code></pre> <p>The image produced by this code looks something like this. Seems like I define, and talk about, a lot of functions...</p> <p><a href="https://i.stack.imgur.com/vA6vu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vA6vu.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T17:32:18.993", "Id": "465145", "Score": "2", "body": "Nice image. Unfortunately I don't speak python." } ]
[ { "body": "<h1>Quick bits</h1>\n\n<p>You have some issues that some linters would pick up:</p>\n\n<ul>\n<li>I would suggest moving your main code into a function. So that it doesn't pollute the global namespace.</li>\n<li>You've got some trailing whitespace.</li>\n<li>Add some docstrings to your code. Even something basic like \"Fetch words in answers.\"</li>\n<li>Your imports are kinda all over the place. I can't make any sense of them, and so I think they're just randomly placed there as and when you needed them.</li>\n<li>I don't think <code>print</code> is the best tool for logging. I would suggest using <code>logging</code>.</li>\n</ul>\n\n<h1>Async</h1>\n\n<p>I'm not a fan of your current <code>fetch</code> and <code>fetch_all</code> functions. I would prefer it if <code>fetch</code> only called <code>session.get</code>. This may seem strange, but it means that you can change your code to allow for caching of objects or easier logging.</p>\n\n<p>Given that I've not done any of this I've left it returning just a plain RequestContextManager. However if I were to expand on this I would change it to my own custom class. This is because then you can keep the data you want / need such as the page body in a cache. Using your own class also means that can guarantee values will exist, and hide ones you can't guarantee.</p>\n\n<p>Moving the content of the old <code>fetch</code> into a <code>fetch_all_words</code> allows almost the exact same code, and allows us to build the word list without the use of a convoluted <code>itertools</code> and <code>asyncio</code> one-liner.</p>\n\n<p>Interestingly since the majority of the content of the <code>fetch_all_words</code> function is not async code, there is little to no performance difference between using <code>asyncio.as_completed</code> and <code>asyncio.gather</code>. In a small test function I found that <code>asyncio.as_completed</code> performs as well or better than <code>asyncio.gather</code>.</p>\n\n<p>Finally I make <code>main</code> an async function, as calling <code>asyncio.run(main())</code> is simpler than building a loop and running until completion.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"\"\"Stack Exchange word cloud generator.\"\"\"\nimport asyncio\nimport logging\nimport itertools\nimport operator\n\nimport aiohttp\nimport bs4\nimport nltk.tokenize\nimport matplotlib.pyplot as plt\nimport stackexchange\nimport wordcloud\n\nAPI_KEY = '**redacted**'\nCR = stackexchange.Site(\"CodeReview\", API_KEY)\n\nSTRAINER = bs4.SoupStrainer(\n 'div',\n attrs={'class': ['answer', 'answer accepted-answer']}\n)\n\n\nasync def fetch(session, url):\n return url, await session.get(url)\n\n\nasync def fetch_all(urls):\n async with aiohttp.ClientSession() as session:\n tasks = [fetch(session, url) for url in urls]\n for task in asyncio.as_completed(tasks):\n yield await task\n\n\nasync def fetch_all_words(answers):\n words = []\n async for url, resp in fetch_all(answers):\n answer_id = answers[url]\n\n async with resp as response:\n page = await response.text()\n soup = bs4.BeautifulSoup(page, \"lxml\", parse_only=STRAINER)\n answer = soup.select_one(f'div#answer-{answer_id} div.post-text')\n try:\n answer_text = answer.text\n except AttributeError:\n logging.error(url)\n answer_words = []\n else:\n logging.info(url)\n answer_words = nltk.tokenize.word_tokenize(answer_text)\n words.extend(answer_words)\n return words\n\n\nasync def main():\n \"\"\"Main code.\"\"\"\n logging.getLogger().setLevel(logging.INFO)\n\n user = CR.user(42401)\n user.answers.fetch()\n\n answers = {\n answer.url.replace(CR.domain, \"codereview.stackexchange.com\"): answer.id\n for answer in user.answers\n }\n words = await fetch_all_words(answers)\n\n plt.figure()\n wc = wordcloud.WordCloud(width=480, height=480, colormap=\"Blues\")\n wc = wc.generate(\" \".join(words))\n plt.imshow(wc, interpolation=\"bilinear\")\n plt.axis(\"off\")\n plt.margins(x=0, y=0)\n plt.show()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n</code></pre>\n\n<h1>Additional comments</h1>\n\n<ul>\n<li><p>The code heavily violates the SRP principle. Given that this is, I assume, an untested one-off script this doesn't matter much.</p>\n\n<p>However in the future I think the changes to <code>fetch_all</code> makes <code>fetch_all_words</code> easier to split up to achieve this.</p></li>\n<li><p>I have butchered your style.<br>\nThis may be hard to believe but I rewrote the code around three times. I've not changed much, but I don't think much needs to be changed. I mostly focused on trying to get <code>fetch_all</code> and <code>fetch</code> a way I like.</p>\n\n<p>Whilst I like my style more, it's not intended to be some subtle hint yours is bad.</p></li>\n<li><p>You have a bug apparently \"n't\", \"ll\", \"n't use\" and \"ca n't\" are words I commonly say.<br>\nAlso, \"n't\" appears on your image too.</p></li>\n<li><p>Thanks for posting this, it was a fun little puzzle. First time I'd really looked into <code>asyncio</code> too!</p></li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/FcOiO.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/FcOiO.png\" alt=\"Peilonrayz&#39; wordmap\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T00:30:09.837", "Id": "465336", "Score": "0", "body": "I've been a bit nosy and looked at some other users posts. And found some funny ones like \"li li\" and \"td td\" without \"li\" or \"td\" being listed. Interestingly I've yet to find \"wouldn't\" or \"don't\" only lots of \"n't\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T16:02:23.100", "Id": "465382", "Score": "0", "body": "To be honest I didn't investigate the word splitter a lot. I just wanted to use something slightly more sophisticated than `str.split` so that at least punctuation is treated separately, especially to combine `PEP8` and `PEP8,`. Regarding the imports, they are just alphabetically sorted, and the second group are the non-standard ones (for me, although I agree that that distinction is not very clean)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T22:11:36.547", "Id": "237311", "ParentId": "237253", "Score": "6" } } ]
{ "AcceptedAnswerId": "237311", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T17:21:02.800", "Id": "237253", "Score": "10", "Tags": [ "python", "python-3.x", "asynchronous", "beautifulsoup", "natural-language-processing" ], "Title": "Wordcloud from all answers of a user here on CR" }
237253
<p>For a course I following and my code is approved I had to make some code that finds the person with the biggest loss where the input is a string[] </p> <p>The string arrray looks like this : </p> <pre><code>{ "Tom, 1, 3, -1", "Gillie, 2, 3, 1", "Thor, 1000, 1001, 1002" }; </code></pre> <p>I solved it this way but it's not a clean way. I must say we were not allowed to use classes. that will be the next chapter of the course. </p> <p>My solution looks now like this : </p> <pre><code> public static string FindPersonWithBiggestLoss(string[] peopleAndBalances) { if (IsInValidInput(peopleAndBalances)) { return InValidOutput; } var highestLossEver = decimal.MinValue; var personWithHighestLoss = new StringBuilder(); for (int i = 0; i &lt;= peopleAndBalances.Length - 1; i++) { var currentPersonData = peopleAndBalances[i].Split(','); var allAmounts = currentPersonData[1..]; // calculateLoss if (allAmounts.Length &lt;= 1) { return InValidOutput; } for (int j = 0; j &lt; allAmounts.Length - 1; j++) { try { var amount1 = decimal.Parse(allAmounts[j], NumberStyles.Currency | NumberStyles.Number); var amount2 = decimal.Parse(allAmounts[j + 1], NumberStyles.Currency | NumberStyles.Number); var lossForCurrentPerson = amount1 - amount2; //check if loss is greater then the current highest loss if (lossForCurrentPerson &gt; highestLossEver) { highestLossEver = lossForCurrentPerson; personWithHighestLoss.Clear(); personWithHighestLoss.Append(currentPersonData[0]); } } catch (FormatException ex) { Console.WriteLine($"there is not a valid character in the database. Reason{ex}"); break; } } } if (personWithHighestLoss.ToString().Contains(',')) { ReplaceCommaWithAnd(personWithHighestLoss); } return $"{personWithHighestLoss} lost the most money. -¤{highestLossEver}."; } </code></pre> <p>it works but also I need a lot of nested control statements to make it work. Is there a cleaner way to make this work ?</p>
[]
[ { "body": "<p>A few things I noticed:</p>\n\n<p>Using the range option of the array index(<code>var allAmounts = currentPersonData[1..];</code>) doesn't really help here. All that's needed is to use the appropriate indexes of the original array.</p>\n\n<p>It's quite inefficient to use a <code>try</code> block to test if a string is a valid number. Using the <code>tryParse</code> method is much more efficient.</p>\n\n<p>A hard coded currency symbol means that your output might not format properly on someone else's machine. I would suggest using the format overload of the <code>ToString</code> method with the currency format.</p>\n\n<p>I appears you're using a <code>StringBuilder</code> to change the name of whichever person has the highest loss. If I'm not mistaken this will copy the string you already have. I would suggest just use the string array itself. This will be assigned by reference and won't require recopying the string.\nThis:</p>\n\n<pre><code>if (personWithHighestLoss[0].Contains(','))\n{\n ReplaceCommaWithAnd(personWithHighestLoss);\n}\n</code></pre>\n\n<p>doesn't really make much sense. The <code>Split</code> method already removes the commas. If you're worried about extra commas use the <code>StringSplitOptions.RemoveEmptyEntries</code> option of the <code>Split</code> method.</p>\n\n<p>Here's what the modified code could look like:</p>\n\n<pre><code>public static string FindPersonWithBiggestLoss(string[] peopleAndBalances)\n{\n if (IsInValidInput(peopleAndBalances))\n {\n return InValidInput;\n }\n\n var highestLossEver = decimal.MinValue;\n string[] personWithHighestLoss = new string[] { \"\" };\n\n for (int i = 0; i &lt;= peopleAndBalances.Length - 1; i++)\n {\n var currentPersonData = peopleAndBalances[i].Split(',',StringSplitOptions.RemoveEmptyEntries);\n\n // calculateLoss\n\n if (currentPersonData.Length &lt; 4)\n {\n return InValidInput;\n }\n\n for (int j = 1; j &lt; currentPersonData.Length - 1; j++)\n {\n var amount1 = 0.0M;\n var amount2 = 0.0M;\n if (!(decimal.TryParse(currentPersonData[j], NumberStyles.Currency | NumberStyles.Number, null, out amount1) &amp;&amp;\n decimal.TryParse(currentPersonData[j + 1], NumberStyles.Currency | NumberStyles.Number, null, out amount2)))\n {\n Console.WriteLine($\"there is not a valid character in the database\");\n }\n\n var lossForCurrentPerson = amount1 - amount2;\n\n //check if loss is greater then the current highest loss\n if (lossForCurrentPerson &gt; highestLossEver)\n {\n highestLossEver = lossForCurrentPerson;\n personWithHighestLoss = currentPersonData;\n }\n }\n\n }\n return $\"{personWithHighestLoss[0]} lost the most money. -{highestLossEver.ToString(\"C\")}.\";\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T02:01:11.600", "Id": "237268", "ParentId": "237254", "Score": "1" } }, { "body": "<p>I wrote this code with a simpler version. \nAt first I created a class to store parsed information.</p>\n\n<pre><code>public class PersonWithMinLoss\n{\n public string Name { get; set; }\n public decimal MaxLoss { get; set; }\n private readonly List&lt;decimal&gt; Amounts;\n\n public PersonWithMinLoss(string currentPersonData)\n {\n var parts = currentPersonData.Split(',');\n this.Amounts = parts[1..]\n .Select(_ =&gt; decimal.Parse(_, NumberStyles.Currency | NumberStyles.Number)).ToList();\n this.Name = parts[0];\n this.MaxLoss = GetMaxLoss();\n }\n\n private decimal GetMaxLoss()\n {\n decimal maxLoss = int.MinValue;\n\n for (int i = 0; i &lt; Amounts.Count - 1; i++)\n {\n var loss = Amounts[i] - Amounts[i + 1];\n if (loss &gt; maxLoss) maxLoss = loss;\n }\n\n return maxLoss;\n }\n}\n</code></pre>\n\n<p>After that we just have to do several <code>Linq</code> queries. For this case</p>\n\n<pre><code>public static string FindPersonWithBiggestLoss(string[] peopleAndBalances)\n {\n var personsWithMaxLoss = peopleAndBalances.Select(_ =&gt; new PersonWithMinLoss(_));\n var maxValue = personsWithMaxLoss.Max(_ =&gt; _.MaxLoss);\n var personWithMaxLoss = personsWithMaxLoss.Where(x =&gt; (x.MaxLoss - maxValue) &lt; 0.0001m).First();\n\n return $\"{personWithMaxLoss.Name} lost the most money. -¤{personWithMaxLoss.MaxLoss}.\";\n }\n</code></pre>\n\n<p>I stored amounts in <code>List&lt;decimal&gt; Amounts</code> so that we can use it after other operations(Not needed for this specific case).\nAnd in <code>var personWithMaxLoss = personsWithMaxLoss.Where(x =&gt; (x.MaxLoss - maxValue) &lt; 0.0001m).First();</code>, we can use <code>.ToList()</code> instead of <code>.First()</code> to find all the persons with max loss. </p>\n\n<p>In this way, complexity is <code>O(n*m)</code> where n is number of person and m is the number of values each person has.</p>\n\n<p>Alternatively we also can use aggregate funtion to find person of max loss.</p>\n\n<pre><code>var personsWithMaxLoss = peopleAndBalances.Select(_ =&gt; new PersonWithMinLoss(_));\nvar personWithMaxLoss = personsWithMaxLoss.Aggregate((cur, next) =&gt; (cur == null || cur.MaxLoss &lt; next.MaxLoss) ? next : cur);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T08:30:39.167", "Id": "465217", "Score": "0", "body": "Welcome and thanks for your time to come up with a solution. However this solution sadly is not within the constraints of OP. The OP stated \"I must say we were not allowed to use classes.\" in his question which invalidates this solution.\nIf you think you can still come up with a better solution, which doesn't use classes, please feel free to update your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T08:07:23.617", "Id": "237279", "ParentId": "237254", "Score": "1" } }, { "body": "<p>A few things can be noted.</p>\n\n<ol>\n<li>Find the largest value by using <code>Max()</code> which is a <code>LINQ</code> extension.</li>\n<li>Don't initialize integers variables with <code>MinValue</code> or <code>MaxValue</code> such as <code>decimal.MinValue</code>. Use a default value of <code>0</code> or <code>-1</code> (which are the common used ones` for better code management).</li>\n<li><code>IsInValidInput</code> is not presented in your post, but I assume it's a method where you have validate the input based on your business needs, I just hoped that would be present as well to make the picture clearer. </li>\n<li>Using <code>Try/Catch</code> block inside this method is unnecessary. The <code>Try/Catch</code> should be outside this scope.</li>\n<li>Parsing string, then returning a string is a bad practice. You always need to parse once, and work through the parsed typed, then use <code>ToString()</code> whenever needed, this would create a string while keeping the actual source untouched. Using the current solution means that you're parsing the values in every step in the application. If you see multiple parsing to the same data, try to unify it to make it parsed once, and let the application uses the actual types, then convert it to string whenever needed (like, sending it to database or over web request ..etc). </li>\n<li>Use <code>decimal.TryParse</code> instead of <code>decimal.Parse</code> as you don't know what values are passed to the method, so validate these values before parse them. Also, use <code>string.IsNullOrEmpty</code> since you're working with <code>string</code>. It's minor changes, but it would avoid invalid inputs. Even if it's already validated in <code>IsInValidInput</code>, as long as the method is exposed, you should always consider the implement the method validation process. </li>\n<li>Make use of generic classes such as <code>IEnumerable</code>. instead of accepting <code>string[]</code> you could converted to <code>IEnumerable&lt;string&gt;</code> which would extend your acceptable collections types, and would work with any collection that implements <code>IEnumerable&lt;string&gt;</code>. This would make your method flixable and adaptable to other classes out-of-the-box.</li>\n<li>using <code>StringBuilder</code> is a good choice in your case, but you're misused it when you added a string at the return statement. What you need to do is to keep using the <code>StringBuilder</code> save the results inside it, and then call <code>ToString()</code> on the return statement.</li>\n</ol>\n\n<p>for the current work, where you get a string's array and output one string containing the person information who has the biggest loss. You can simplify it to :</p>\n\n<pre><code>public static string FindPersonWithBiggestLoss(string[] peopleAndBalances)\n{\n if (IsInValidInput(peopleAndBalances)) { return InValidOutput; }\n\n decimal max = 0;\n\n var personWithHighestLoss = new StringBuilder();\n\n for (int x = 0; x &lt; peopleAndBalances.Length; ++x)\n {\n // convert string to array\n var data = peopleAndBalances[x].Split(',');\n\n // since index 0 would hold the person name, then we can start with index 1 to get balances\n for (int i = 1; i &lt; data.Length; i++)\n {\n if (decimal.TryParse(data[i], out decimal amount) &amp;&amp; amount &gt; max)\n {\n personWithHighestLoss.Clear();\n personWithHighestLoss\n .Append(data[0])\n .Append(\" lost the most money. -¤\")\n .Append(amount)\n .Append('.');\n\n max = amount;\n }\n }\n }\n\n return personWithHighestLoss.ToString();\n}\n</code></pre>\n\n<p>if you want a better version which would be more practical in actual work environment, then you would need to do something like this : </p>\n\n<pre><code>// Make use of `IEnumerable` and `KeyValuePair&lt;string, decimal&gt;`\npublic static IEnumerable&lt;KeyValuePair&lt;string, decimal&gt;&gt; FindPersonWithBiggestLoss(IEnumerable&lt;string&gt; peopleAndBalances)\n{\n if (IsInValidInput(peopleAndBalances)) { return InValidOutput; }\n\n foreach (var person in peopleAndBalances)\n {\n decimal max = 0;\n\n // check the string array\n if (!string.IsNullOrEmpty(person))\n {\n // convert string to array\n var data = person.Split(',');\n\n // since index 0 would hold the person name, then we can start with index 1 to get balances\n for (int i = 1; i &lt; data.Length; i++)\n {\n // check the string and validate if it's an integer\n // if not valid, just ignore and get the next value.\n if (decimal.TryParse(data[i], out decimal amount) &amp;&amp; amount &gt; max)\n {\n max = amount;\n }\n }\n\n yield return new KeyValuePair&lt;string, decimal&gt;(data[0], max);\n }\n }\n}\n</code></pre>\n\n<p>this can be simplified using <code>Linq</code> to this : </p>\n\n<pre><code>public static IEnumerable&lt;KeyValuePair&lt;string, decimal&gt;&gt; FindPersonWithBiggestLoss(IEnumerable&lt;string&gt; peopleAndBalances)\n{\n if (IsInValidInput(peopleAndBalances)) { return InValidOutput; }\n\n foreach (var person in peopleAndBalances)\n {\n var data = person.Split(',');\n\n yield return new KeyValuePair&lt;string, decimal&gt;(\n data[0], // you can use Array.Find(data, x =&gt; !decimal.TryParse(x, out _)) as well.\n data.Where(x =&gt; decimal.TryParse(x, out _)).Max(x =&gt; decimal.Parse(x))\n );\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T12:54:59.317", "Id": "237290", "ParentId": "237254", "Score": "1" } }, { "body": "<p>I would rather use the LINQ Query Syntax for simplicity and readability</p>\n\n<pre><code>var input = new List&lt;string&gt; { \"Tom, 1, 3, -1\", \"Gillie, 2, 3, 1\", \"Thor, 1000, 1001, 1002\" };\n\nvar personsWithLoss =\n from pl in input\n let splitted = pl.Split(\",\")\n let person = splitted[0]\n let maxLoss = splitted.Skip(1).OrderByDescending(x=&gt;x).First()\n select new {person,maxLoss};\n\nvar personWithMaxLoss = personsWithLoss.OrderBy(x=&gt;x.maxLoss).First();\nConsole.WriteLine($\"{personWithMaxLoss.person} - {personWithMaxLoss.maxLoss}\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T23:04:27.183", "Id": "237348", "ParentId": "237254", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T17:35:39.107", "Id": "237254", "Score": "4", "Tags": [ "c#" ], "Title": "Finding the person with the biggest loss" }
237254
<p>I know you can calculate if an element is overlapping another by comparing the top|bottom|right|left properties within the getBoundingClientRect method. However, you need to loop through the elements to do so. I'm curious to know what is the performant way of checking to see if an element is overlapping any other element. For example, checking to see if label one is overlaying any other element. Then checking to see if label two is overlapping any other element including label one without using a loop each time, or is this the only way? Currently I'm just checking one element against the previous.</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>// dismiss -- just creating less CSS const randomColor = "#" + ((1 &lt;&lt; 24) * Math.random() | 0).toString(16); document.querySelectorAll('.label').forEach((x, i) =&gt; { document.querySelectorAll('.label')[i].style.background = "#" + ((1 &lt;&lt; 24) * Math.random() | 0).toString(16); }); //function to check for overlapping function overlayCheck() { let points = document.querySelectorAll('.label'); let rightPos = (elem) =&gt; elem.getBoundingClientRect().right; let leftPos = (elem) =&gt; elem.getBoundingClientRect().left; let topPos = (elem) =&gt; elem.getBoundingClientRect().top; let btmPos = (elem) =&gt; elem.getBoundingClientRect().bottom; for (let i = 1; i &lt; points.length; i++) { if (!( rightPos(points[i]) &lt; leftPos(points[i - 1]) || leftPos(points[i]) &gt; rightPos(points[i - 1]) || btmPos(points[i]) &lt; topPos(points[i - 1]) || topPos(points[i]) &gt; btmPos(points[i - 1]) )) { points[i].innerHTML = `${points[i].innerHTML} C`; } if (i === points.length - 1) { return } } } overlayCheck();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.parent { position: relative; display: flex; } .label { height: 75px; left: 0; width: 100px; margin-left: 10px; background-color: orange } .cover { width: 220px; position: absolute; left: 0; height: 50px; bottom: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="parent"&gt; &lt;div class="label cover"&gt;Label 1&lt;/div&gt; &lt;div class="label"&gt;Label 2&lt;/div&gt; &lt;div class="label"&gt;Label 3&lt;/div&gt; &lt;div class="label"&gt;Label 4&lt;/div&gt; &lt;div class="label"&gt;Label 5&lt;/div&gt; &lt;div class="label"&gt;Label 6&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T08:43:46.503", "Id": "465222", "Score": "0", "body": "Does your code work correctly? It does not detect that “Label 1” overlaps with “Label 3”. Or am I misunderstanding the task?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:26:20.883", "Id": "465277", "Score": "0", "body": "Voted to close. The code you provided does not do what you want it to do." } ]
[ { "body": "<p>I figured out a way thru trial and error. I'll post this here for anyone else who could use it.</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>// dismiss -- just creating less CSS\nconst randomColor = \"#\" + ((1 &lt;&lt; 24) * Math.random() | 0).toString(16);\ndocument.querySelectorAll('.label').forEach((x, i) =&gt; {\n document.querySelectorAll('.label')[i].style.background = \"#\" + ((1 &lt;&lt; 24) * Math.random() | 0).toString(16);\n});\n\n//function to check for overlapping\nfunction overlayCheck() {\n let points = document.querySelectorAll('.label');\n let rightPos = (elem) =&gt; elem.getBoundingClientRect().right;\n let leftPos = (elem) =&gt; elem.getBoundingClientRect().left;\n let topPos = (elem) =&gt; elem.getBoundingClientRect().top;\n let btmPos = (elem) =&gt; elem.getBoundingClientRect().bottom;\n\n for (let i = 0; i &lt; points.length; i++) {\n for (let j = 0; j &lt; points.length; j++) {\n let isOverlapping = !(\n rightPos(points[i]) &lt; leftPos(points[j]) ||\n leftPos(points[i]) &gt; rightPos(points[j]) ||\n btmPos(points[i]) &lt; topPos(points[j]) ||\n topPos(points[i]) &gt; btmPos(points[j])\n );\n\n if (isOverlapping &amp;&amp; j !== i) {\n points[i].innerHTML = `${points[i].innerHTML} C`;\n }\n }\n }\n}\noverlayCheck();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.parent {\n position: relative;\n display: flex;\n}\n\n.label {\n height: 75px;\n left: 0;\n width: 100px;\n margin-left: 10px;\n background-color: orange\n}\n\n.cover {\n width: 220px;\n position: absolute;\n left: 0;\n height: 50px;\n bottom: 0;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"parent\"&gt;\n &lt;div class=\"label cover\"&gt;Label 1&lt;/div&gt;\n &lt;div class=\"label\"&gt;Label 2&lt;/div&gt;\n &lt;div class=\"label\"&gt;Label 3&lt;/div&gt;\n &lt;div class=\"label\"&gt;Label 4&lt;/div&gt;\n &lt;div class=\"label\"&gt;Label 5&lt;/div&gt;\n &lt;div class=\"label\"&gt;Label 6&lt;/div&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T16:25:14.503", "Id": "237303", "ParentId": "237255", "Score": "2" } } ]
{ "AcceptedAnswerId": "237303", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T18:18:44.103", "Id": "237255", "Score": "4", "Tags": [ "javascript", "ecmascript-6" ], "Title": "Most performant way to check if elements are overlapping" }
237255
<p>I was struggling with this question for many times, and I have solved it every time, because I understand the concept. but I can never get to a good concise solution which is easy to follow.</p> <p>In a coding interview I always choke when I see this question.</p> <p>This is the best solution I was able to come up with.</p> <p>Can the code be written even more simple and easier to follow?</p> <pre><code>using GraphsQuestions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TreeQuestions { /// &lt;summary&gt; /// https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/625/ /// &lt;/summary&gt; /// check the iterative version with a stack as well /// https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/625/discuss/32112/Learn-one-iterative-inorder-traversal-apply-it-to-multiple-tree-questions-(Java-Solution) [TestClass] public class IsValidBSTtest { // 2 // / \ // 1 3 [TestMethod] public void ValidTree() { TreeNode root = new TreeNode(2); root.left = new TreeNode(1); root.right = new TreeNode(3); IsValidBSTclass temp = new IsValidBSTclass(); Assert.IsTrue(temp.IsValidBST(root)); } [TestMethod] public void NotValidTree() { TreeNode root = new TreeNode(5); root.left = new TreeNode(1); root.right = new TreeNode(4); root.right.left = new TreeNode(3); root.right.right = new TreeNode(6); IsValidBSTclass temp = new IsValidBSTclass(); Assert.IsFalse(temp.IsValidBST(root)); } /* * 10 * / \ * 5 15 * /\ * 6 20 */ [TestMethod] public void NotValidTree2() { TreeNode root = new TreeNode(10); root.left = new TreeNode(5); root.right = new TreeNode(15); root.right.left = new TreeNode(6); root.right.right = new TreeNode(20); IsValidBSTclass temp = new IsValidBSTclass(); Assert.IsFalse(temp.IsValidBST(root)); } } public class IsValidBSTclass { public bool IsValidBST(TreeNode root) { return Helper(root, null, null); } public bool Helper(TreeNode root, TreeNode minNode, TreeNode maxNode) { if (root == null) { return true; } if (minNode != null &amp;&amp; root.val &lt;= minNode.val || maxNode != null &amp;&amp; root.val &gt;= maxNode.val) { return false; } return Helper(root.left, minNode, root) &amp;&amp; Helper(root.right, root, maxNode); } } } </code></pre>
[]
[ { "body": "<p>For the most part I agree with your code. However there are a couple of things:</p>\n\n<p><code>IsValidBST</code> I think is redundant. Anyone running this method already knows it applies to a BST. I think just <code>IsValid</code> would be better.</p>\n\n<p><code>Helper</code> should have a better name, I think an <code>IsValid</code> overload would work and it should be private.</p>\n\n<p>It doesn't make much sense to me to make an instance of this class. The methods don't rely on anything internal to the class. I would suggest making the methods <code>static</code>.</p>\n\n<p>It could look something like this:</p>\n\n<pre><code>public class IsValidBSTclass\n{\n public static bool IsValid(TreeNode root)\n {\n return IsValid(root, null, null);\n }\n private static bool IsValid(TreeNode root, TreeNode minNode, TreeNode maxNode)\n {\n if (root == null)\n {\n return true;\n }\n if (minNode != null &amp;&amp; root.val &lt;= minNode.val || maxNode != null &amp;&amp; root.val &gt;= maxNode.val)\n {\n return false;\n }\n\n return IsValid(root.left, minNode, root) &amp;&amp; IsValid(root.right, root, maxNode);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T02:27:30.830", "Id": "237269", "ParentId": "237259", "Score": "2" } }, { "body": "<p>The main validation logic doesn't need \"min node\" and \"max node\",\nonly the values.\nPassing the nodes as parameters adds complexity,\nbecause you have to handle <code>null</code> values,\nwhich would not be the case with simple integers.\nBeing an unnecessary complexity (since nodes are not really needed),\nI suggest to eliminate it, for example:</p>\n\n<pre><code>public static bool IsValid(TreeNode root)\n{\n if (root == null)\n {\n return true;\n }\n\n return IsValid(root.left, long.MinValue, root.val)\n &amp;&amp; IsValid(root.right, root.val, long.MaxValue);\n}\n\nprivate static bool IsValid(TreeNode node, long minVal, long maxVal)\n{\n if (node == null)\n {\n return true;\n }\n\n if (node.val &lt;= minVal || maxVal &lt;= node.val)\n {\n return false;\n }\n\n return IsValid(node.left, minVal, node.val)\n &amp;&amp; IsValid(node.right, node.val, maxVal);\n}\n</code></pre>\n\n<p>Notice that I renamed the variable in the second method from <code>root</code> to <code>node</code>,\nsince in this method the node is never the root.\nI would do the same in the original code,\neven though there it's sometimes really the <code>root</code>,\nbut since that won't be the average case,\nI think that not calling it root may eliminate some confusion.</p>\n\n<p>Lastly, making the helper method use <code>long</code> is necessary to support the (perhaps a bit naughty) input:</p>\n\n<pre><code>[-2147483648,null,2147483647]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T20:24:44.453", "Id": "237339", "ParentId": "237259", "Score": "2" } }, { "body": "<p>I don't like classes named <code>…class</code>. In languages including C#, it leads to expressions like <code>new IsValidBSTclass()</code>, <em>not</em> yielding a <em>class</em>.<br>\nI'd prefer <code>BSTChecker</code> over <code>BSTValidator</code> for the foreseeable <code>bstValidator.isValid()</code>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T11:10:52.350", "Id": "465437", "Score": "0", "body": "Decoration in C# does not seem so easy." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T10:14:07.410", "Id": "237368", "ParentId": "237259", "Score": "1" } } ]
{ "AcceptedAnswerId": "237339", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-13T20:15:23.437", "Id": "237259", "Score": "4", "Tags": [ "c#", "programming-challenge", "tree" ], "Title": "LeetCode: Validate Binary Search Tree C#" }
237259
<p>I decided it would be fun to implement <a href="https://en.wikipedia.org/wiki/Conway&#39;s_Game_of_Life" rel="nofollow noreferrer">Conway's Game of Life</a> (CGOL) in Emacs Lisp as my first elisp script.</p> <p>My goals for the implementation were pretty simple</p> <ul> <li>Transform current buffer into the next generation of CGOL</li> <li>Just use max height/width of the current buffer (don't worry about overflowing the space, keep it bounded)</li> <li>Be able to specify which character means "alive", assume all others are dead</li> </ul> <p>To implement this, I came up with the following</p> <pre class="lang-lisp prettyprint-override"><code>(defun conway-current-buffer (alive-char) (interactive "cAlive-charater: ") (defun key (x y) (concat (number-to-string x) "-" (number-to-string y))) (defun pair-to-key (p) (concat (number-to-string (car p)) "-" (number-to-string (cadr p)))) (defun neighbors (x y) (list (list (+ x 1) (+ y 1)) (list (+ x 1) (- y 1)) (list (- x 1) (- y 1)) (list (- x 1) (+ y 1)) (list (+ x 1) y) (list (- x 1) y) (list x (- y 1)) (list x (+ y 1)))) (defun alive-neighbor-count (x y state) (progn (setq alive-neighbors 0) (dolist (neighbor (neighbors x y)) (if (gethash (pair-to-key neighbor) state) (setq alive-neighbors (+ 1 alive-neighbors)))) alive-neighbors)) (defun lives-on (x y state) (let ((alive-ns (alive-neighbor-count x y state)) (alive (gethash (key x y) state nil))) (or (eq alive-ns 3) (and alive (eq alive-ns 2))))) (defun clear-buffer () (kill-region (point-min) (point-max))) (defun render (height width state) (progn (clear-buffer) (setq y 0) (while (&lt; y height) (progn (setq x 1) (while (&lt;= x width) (if (gethash (key x y) state) (insert (char-to-string alive-char)) (insert " ")) (setq x (+ 1 x))) (setq y (+ 1 y)) (if (&lt; y height) (insert "\n")))))) (defun next-state (height width state) (progn (setq next (make-hash-table :test #'equal)) (setq y 0) (while (&lt; y height) (progn (setq x 0) (while (&lt; x width) (if (lives-on x y state) (puthash (key x y) t next)) (setq x (+ 1 x))) (setq y (+ 1 y)))) next)) (let ((text (buffer-string)) (state (make-hash-table :test #'equal))) (progn (setq lines (split-string text "\n")) (setq width 0) (setq height (length lines)) (setq y 0) (dolist (line lines) (progn (setq width (max width (length line))) (setq x 0) (dolist (c (split-string line "")) (progn (if (eq alive-char (string-to-char c)) (puthash (key x y) t state)) (setq x (+ 1 x)))) (setq y (+ 1 y))) ) (render height width (next-state height width state))))) </code></pre> <h1>What I'm Looking For in a Review</h1> <ul> <li><p>Please point out any beginner mistakes</p></li> <li><p>Am I scoping correctly (esp. with <code>setq</code>s and nested <code>defun</code>s)?</p></li> <li><p>Non-idiomatic code, easier functions to use</p></li> <li><p>Performance concerns - though I didn't necessarily strive for optimized, any tips are appreciated</p></li> <li><p>General suggestions</p></li> </ul> <h1>"Bonus Points"</h1> <p>I know CR SE's not a Q&amp;A site as much, so feel free to skip these, but</p> <ul> <li>Is this "good enough" to distribute as a package (i.e. is <code>interactive</code> all it takes?)</li> <li>Given I'm using spacemacs, where would I included this to be able to use it?</li> <li>How would one define a hash <code>:test</code> that uses <code>(x . y)</code> pairs instead of strings (e.g. <code>"x-y"</code>)?</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T01:28:33.360", "Id": "237266", "Score": "2", "Tags": [ "elisp" ], "Title": "Conway's Game of Life in Emacs Lisp" }
237266
<p>Last year I tried to implement a micro service architecture in Rust. It was asked as a homework question in an employment interview process to be completed in a few days. The imagined use case was a small izakaya-shop where digital orders could be given to the kitchen tracked or deleted.</p> <p>Looking for feedback both on my coding style and architecture, any comments which I could learn from is appreciated.</p> <p><a href="https://github.com/simonsso/teketeke" rel="nofollow noreferrer">https://github.com/simonsso/teketeke</a></p> <p><strong>Some sketches of the use cases</strong> <img src="https://raw.githubusercontent.com/simonsso/teketeke/master/docs/SetupShop.png" alt="usecase1" /> <img src="https://raw.githubusercontent.com/simonsso/teketeke/master/docs/UseCase.png" alt="usecase2" /></p> <p>and the code</p> <p><strong>main.rs</strong></p> <pre><code>#[macro_use] extern crate serde_derive; extern crate hyper; extern crate hyper_staticfile; extern crate serde_json; use std::error::Error; use futures::{future, Future, Stream}; use hyper::{Body, Request, Response, Server, StatusCode}; use hyper::error::Error as hyper_errors; use hyper::service::service_fn; use lazy_static::lazy_static; use regex::Regex; use futures::task::spawn; use futures_locks::RwLock; use hyper_staticfile::FileChunkStream; use tokio::fs::File; #[derive(Copy, Deserialize, Clone, Serialize)] enum States { PENDING, DELIVERD, EMPTY, } #[derive(Deserialize, Clone, Serialize)] struct Record { itemname: String, id: usize, state: States, qty: i32, eta: u64, } struct Datastore { vault: Vec&lt;RwLock&lt;Vec&lt;Record&gt;&gt;&gt;, } #[derive(Deserialize, Clone, Serialize)] struct TableRequestVec { tab: Vec&lt;TableRequest&gt;, } #[derive(Deserialize, Clone, Serialize)] struct TableRequest { itemname: String, qty: i32, eta: u64, } fn datastore_rw_lock(num: usize) -&gt; RwLock&lt;Datastore&gt; { let mut v: Vec&lt;RwLock&lt;Vec&lt;Record&gt;&gt;&gt; = Vec::with_capacity(100); for _ in 0..num { v.push(RwLock::new(Vec::new())) } let d: Datastore = Datastore { vault: v }; RwLock::new(d) } lazy_static! { // TODO verify the correctness of regexp in tests static ref RE_TABLE_NUM: Regex = Regex::new(r&quot;^/table/(\d+)(/(.*))?$&quot;).unwrap(); static ref RE_TABLE: Regex = Regex::new(r&quot;^/table/?&quot;).unwrap(); static ref RE_DOWNLOAD_FILE:Regex = Regex::new(r&quot;^/(index.html|button.js)$&quot;).unwrap(); static ref STORAGE:RwLock&lt;Datastore&gt; =datastore_rw_lock(101); //init with tables upto 100 // TODO this should be done on demand instead static ref ITEMNUM:RwLock&lt;usize&gt; =RwLock::new(0); // Global uniq order num } fn get_global_num() -&gt; usize { let mut retval = 0; let lock = ITEMNUM.write().map(|mut cnt| { *cnt += 1; retval = *cnt; }); match spawn(lock).wait_future() { Ok(_x) =&gt; {} Err(_) =&gt; {} } retval } // Encapsulate response for hyper fn microservice_handler( req: Request&lt;Body&gt;, ) -&gt; Box&lt;Future&lt;Item = Response&lt;Body&gt;, Error = std::io::Error&gt; + Send&gt; { let uri: String = req.uri().to_string(); let method = req.method().to_string(); if let None = RE_TABLE.captures(&amp;uri) { return serve_file(&amp;uri); } // Parse request URL with stored Regexp let (table, path): (Option&lt;usize&gt;, Option&lt;String&gt;) = match RE_TABLE_NUM.captures(&amp;uri) { Some(m) =&gt; { // this is checked to be an integer let tbl = m.get(1).unwrap().as_str().parse::&lt;usize&gt;().unwrap(); match m.get(3) { Some(argument) =&gt; (Some(tbl), Some(argument.as_str().to_string())), None =&gt; (Some(tbl), None), } } None =&gt; (None, None), }; match (method.as_ref(), table, path) { (&quot;GET&quot;, Some(table), None) =&gt; { // GET all items for table t let table = table as usize; match table_get_all(table) { ApiResult::Ok(s) =&gt; Box::new(future::ok( Response::builder().status(200).body(Body::from(s)).unwrap(), )), ApiResult::Err(code, s) =&gt; Box::new(future::ok( Response::builder() .status(code) .body(Body::from(s)) .unwrap(), )), } } (&quot;GET&quot;, None, None) =&gt; { // Get all items let comma: String = &quot;,&quot;.to_string(); let lock = STORAGE.read(); let v = &amp;spawn(lock).wait_future().unwrap().vault; //Reusing get from table code let mut bodychunks: Vec&lt;String&gt; = Vec::new(); bodychunks.push(&quot;{\&quot;tables\&quot;:{&quot;.to_string()); for i in 0..v.len() { match table_get_all(i) { ApiResult::Ok(s) =&gt; { let headerstring = format!(&quot;\&quot;{}\&quot;:&quot;, i); bodychunks.push(headerstring); bodychunks.push(s); bodychunks.push(comma.clone()) } ApiResult::Err(code, msg) =&gt; { //TODO This should not occour println!(&quot;Enexpected error fetcing all data {} {} {}&quot;, i, code, msg); } } } if bodychunks.last() == Some(&amp;comma) { bodychunks.pop(); } bodychunks.push(&quot;}}&quot;.to_string()); let stream = futures::stream::iter_ok::&lt;_, ::std::io::Error&gt;(bodychunks); let body = Body::wrap_stream(stream); let resp = Response::builder().status(200).body(body).unwrap(); Box::new(future::ok(resp)) } (&quot;POST&quot;, None, None) =&gt; { let resp = Response::builder() .status(501) .body(req.into_body()) .unwrap(); Box::new(future::ok(resp)) } (&quot;POST&quot;, Some(table), None) =&gt; { let lock = STORAGE.read(); let tablelist = &amp;spawn(lock).wait_future().unwrap().vault; match tablelist.get(table as usize) { //TODO replace None case and Some case here Some(_) =&gt; { // Sic TODO: this finds the tables vector and then does not use it let boxedresult = table_add_items(req.into_body(), table); let f = boxedresult.map_err(teketeke_to_stdio_err).map(move |s| { match s { Ok(s) =&gt; Response::builder().status(200).body(Body::from(s)), Err(TeketekeError::InternalError(s)) =&gt; { Response::builder().status(417).body(Body::from(s)) } _ =&gt; Response::builder() .status(418) .body(Body::from(&quot;Unknown error&quot;)), } .unwrap() }); Box::new(f) } None =&gt; { let err = &quot;I am a tea pot Error: this table is not allocated - build a bigger restaurant&quot;; let response = Response::builder() .status(418) .body(Body::from(err)) .unwrap(); Box::new(future::ok(response)) } } } (&quot;DELETE&quot;, Some(table), Some(path)) =&gt; { // Remove something from table t //Todo find a way to identify items in table tab... maybe with id let table = table as usize; match table_remove_item(table, path) { ApiResult::Ok(s) =&gt; Box::new(future::ok( Response::builder().status(200).body(Body::from(s)).unwrap(), )), ApiResult::Err(code, s) =&gt; Box::new(future::ok( Response::builder() .status(code) .body(Body::from(s)) .unwrap(), )), } } (&quot;UPDATE&quot;, Some(_t), Some(_path)) =&gt; { // Change some object for instance when it is deliverd to table // Fall throu default response let ans = &quot;Not implemented&quot;; let resp = Response::builder() .status(501) .body(Body::from(ans)) .unwrap(); Box::new(future::ok(resp)) } _ =&gt; { // Unsupported operation // Fall throu default response let ans = &quot;Not implemented&quot;; let resp = Response::builder() .status(501) .body(Body::from(ans)) .unwrap(); Box::new(future::ok(resp)) } } } #[derive(Debug)] enum ApiResult&lt;T&gt; { Ok(T), Err(u16, String), } fn table_get_all(table: usize) -&gt; ApiResult&lt;String&gt; { let lock = STORAGE.read(); let v = &amp;spawn(lock).wait_future().unwrap().vault; match v.get(table) { Some(x) =&gt; { // let vec_lock:RwLock&lt;Vec&lt;Record&gt;&gt; = *x; let read_lock = (*x).read(); let x1 = spawn(read_lock).wait_future().unwrap(); //sic! let table_vec: Vec&lt;Record&gt; = x1.to_vec(); let bodytext: String = serde_json::to_string(&amp;table_vec).unwrap(); ApiResult::Ok(bodytext) } None =&gt; ApiResult::Err( 418, &quot;I am a tea pot Error: this table is not allocate - build a bigger restaurant&quot; .to_string(), ), } } // Magic tranform of one kind of error to other fn other&lt;E&gt;(err: E) -&gt; std::io::Error where E: Into&lt;Box&lt;std::error::Error + Send + Sync&gt;&gt;, { std::io::Error::new(std::io::ErrorKind::Other, err) } // Magic tranform of one kind of error to other fn to_stdio_err(e: hyper::Error) -&gt; std::io::Error { std::io::Error::new(std::io::ErrorKind::Other, e) } enum TeketekeError&lt;E&gt; where E: Into&lt;Box&lt;std::error::Error + Send + Sync&gt;&gt;, { ExternalError(E), InternalError(String), } fn intoTeketekeError&lt;E&gt;(err: E) -&gt; TeketekeError&lt;E&gt; where E: Into&lt;Box&lt;std::error::Error + Send + Sync&gt;&gt;, { TeketekeError::ExternalError(err) } fn teketeke_to_stdio_err(e: TeketekeError&lt;std::io::Error&gt;) -&gt; std::io::Error { match e { TeketekeError::ExternalError(err) =&gt; err, _ =&gt; { let not_found = std::io::ErrorKind::NotFound; std::io::Error::from(not_found) } } } fn table_add_items( body: Body, table: usize, ) -&gt; Box&lt; Future&lt; Item = Result&lt;String, TeketekeError&lt;std::io::Error&gt;&gt;, Error = TeketekeError&lt;std::io::Error&gt;, &gt; + Send, &gt; { let res = body .concat2() .map(move |chunks| { serde_json::from_slice::&lt;TableRequestVec&gt;(chunks.as_ref()) .map(|t| table_store_new_items(table, t.tab)) .map_err(other) .map_err(|e| intoTeketekeError::&lt;std::io::Error&gt;(e)) .and_then(|x| { if x == 0 { Err(TeketekeError::InternalError(&quot;Nothing modified&quot;.to_string())) } else { Ok(x.to_string()) } }) }) .map_err(other) .map_err(|e| intoTeketekeError::&lt;std::io::Error&gt;(e)); Box::new(res) } fn table_remove_item(table: usize, path: String) -&gt; ApiResult&lt;String&gt; { let removethis = match path.parse::&lt;usize&gt;() { Ok(x) =&gt; x, Err(_x) =&gt; return ApiResult::Err(503, &quot;Illegal table number&quot;.to_string()), }; let outerlock = STORAGE.read().map(|outer| { // range check done is outside let innerlock = (*outer).vault[table as usize].write().map(|mut inner| { // *inner is now the handle for table vector match (*inner).iter().position(|c| (*c).id == removethis) { Some(x) =&gt; { (*inner).remove(x); } None =&gt; {} } }); spawn(innerlock).wait_future() }); match spawn(outerlock).wait_future() { Ok(_) =&gt; 0, Err(_) =&gt; 0, }; ApiResult::Ok(&quot;&quot;.to_string()) } fn table_store_new_items(table: usize, v: Vec&lt;TableRequest&gt;) -&gt; u32 { let mut target: Vec&lt;Record&gt; = Vec::with_capacity(v.len()); for i in v { target.push(Record { itemname: i.itemname, id: get_global_num(), qty: i.qty, state: States::PENDING, eta: i.eta, }) } let retval = target.len(); // Get lock for data store let outerlock = STORAGE.read().map(|outer| { // range check done is outside let innerlock = (*outer).vault[table as usize].write().map(|mut inner| { (*inner).append(&amp;mut target); }); spawn(innerlock).wait_future() }); match spawn(outerlock).wait_future() { Ok(_) =&gt; retval as u32, Err(_) =&gt; 0, } } fn serve_file(path: &amp;str) -&gt; Box&lt;Future&lt;Item = Response&lt;Body&gt;, Error = std::io::Error&gt; + Send&gt; { // Only serv the hard coded files needed for this project if let Some(cap) = RE_DOWNLOAD_FILE.captures(path) { let filename = format!(&quot;client/{}&quot;, cap.get(1).unwrap().as_str()); let open_file = File::open(filename); let body = open_file.map(|file| { let chunks = FileChunkStream::new(file); Response::new(Body::wrap_stream(chunks)) }); Box::new(body) } else { let ans = &quot;Thou shalt not read forbidden files&quot;; let resp = Response::builder() .status(403) .body(Body::from(ans)) .unwrap(); Box::new(future::ok(resp)) } } fn main() { let portnum = 8888; println!( &quot;Starting server port at http://localhost:{}/index.html&quot;, portnum ); let addr = ([127, 0, 0, 1], portnum).into(); let server = Server::bind(&amp;addr).serve(|| service_fn(move |req| microservice_handler(req))); let server = server.map_err(drop); hyper::rt::run(server); } #[cfg(test)] mod tests { use super::*; // TODO/Note add unit test on handler level, when there is time to add // a request struct and check the response struct. Have to figure out // how to achive this. // // For now this must be tested at system level by usage. #[test] fn check_post_ans() { let chunks = vec![&quot;hello&quot;, &quot; &quot;, &quot;world&quot;]; let stream = futures::stream::iter_ok::&lt;_, ::std::io::Error&gt;(chunks); let body = Body::wrap_stream(stream); let table: usize = 1; let ans = table_add_items(body, table); let ans = spawn(ans).wait_future(); match ans { Err(_) =&gt; {} Ok(_) =&gt; assert!(true, &quot;should have failed&quot;), _ =&gt; assert!(true, &quot;test case took unexpected path&quot;), } //assert!(r.status() == 422); let order = r#&quot;{&quot;tab&quot;:[{&quot;itemname&quot;: &quot;Edamame&quot;,&quot;qty&quot; : 100 ,&quot;eta&quot;:100 },{&quot;itemname&quot;: &quot;Nama biru&quot;,&quot;qty&quot; : 5 ,&quot;eta&quot;:200} ]}&quot;#; let chunks = vec![order]; let stream = futures::stream::iter_ok::&lt;_, ::std::io::Error&gt;(chunks); let body = Body::wrap_stream(stream); let table: usize = 1; let ans = table_add_items(body, table); let ans = spawn(ans).wait_future(); match ans { Err(_) =&gt; assert!(true, &quot;should not have failed&quot;), Ok(Ok(x)) =&gt; assert_eq!(x, 2.to_string()), _ =&gt; assert!(true, &quot;test case took unexpected path&quot;), } } #[test] fn check_store_values() { let mut v: Vec&lt;TableRequest&gt; = Vec::new(); v.push(TableRequest { itemname: &quot;Something&quot;.to_string(), qty: 1, eta: 100, }); let table_get_all_res = match table_get_all(10) { ApiResult::Ok(x) =&gt; x, _ =&gt; panic!(), }; let before: Vec&lt;Record&gt; = serde_json::from_slice(table_get_all_res.as_bytes()).unwrap(); let storednum = table_store_new_items(10, v); assert_eq!(1, storednum); let table_get_all_res = match table_get_all(10) { ApiResult::Ok(x) =&gt; x, _ =&gt; panic!(), }; let after: Vec&lt;Record&gt; = serde_json::from_slice(table_get_all_res.as_bytes()).unwrap(); // Should be one more entry assert!(after.len() - before.len() == 1); table_remove_item(10, &quot;1&quot;.to_string()); let table_get_all_res = match table_get_all(10) { ApiResult::Ok(x) =&gt; x, _ =&gt; panic!(), }; let _after: Vec&lt;Record&gt; = serde_json::from_slice(table_get_all_res.as_bytes()).unwrap(); //TODO Should be back where we started but item ide can not be guessed as they are world uniq now //assert_eq!(after.len(),before.len()); } #[test] fn check_regexp() { let ans = RE_TABLE_NUM.captures(&quot;/table/100&quot;); match ans { Some(m) =&gt; { assert_eq!(m.get(1).map_or(&quot;Unknown&quot;, |m| m.as_str()), &quot;100&quot;); } _ =&gt; { assert!(false); } } match RE_TABLE_NUM.captures(&quot;/table/100/open&quot;) { Some(m) =&gt; { assert_eq!(m.get(1).map_or(&quot;Unknown&quot;, |m| m.as_str()), &quot;100&quot;); assert_eq!(m.get(2).map_or(&quot;Unknown&quot;, |m| m.as_str()), &quot;/open&quot;); } _ =&gt; { assert!(false); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T04:53:35.193", "Id": "465193", "Score": "0", "body": "please let me know here if there is anything needed to make this a better question..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T08:37:37.267", "Id": "465219", "Score": "0", "body": "Have you seen (or used) this question in an interview? Otherwise [tag:interview-question] does not apply here (see also the tag description)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T08:54:29.000", "Id": "465224", "Score": "0", "body": "I was given it as a homework does that not count? Or is the tag for the short lighting coding questions which solved a stupid problem in 5 minutes if you have the correct idea or 5 hours otherwise?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:15:37.673", "Id": "465233", "Score": "0", "body": "If you want a definitive answer, you can either wait until some of the more veteran users join in or ask on [meta]. [tag:interview-question] and [tag:homework] are commonly used to give reviewers a hint what kind of tools where available to you while writing the code and how much they should tell you to not \"spoil\" the possibility to learn on your own. If that does not apply to your question, just don't use those tags." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T02:07:05.743", "Id": "467523", "Score": "0", "body": "Maybe some day a understimualated rust guru will pass by here and have a look at this code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-07-30T16:09:50.783", "Id": "524503", "Score": "1", "body": "Make it asynchronous" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T01:41:36.110", "Id": "237267", "Score": "4", "Tags": [ "interview-questions", "rust" ], "Title": "Implement a micro service in Rust" }
237267
<p>I'm working on a feature for work that requires me to combine a set number of memory streams based on specific conditions.</p> <p><strong>Previous Code</strong></p> <p>Before based on documentation/examples online. In order to create a PDF to print, you have to create a Memory Stream and save that document into a Memory Stream. Here lies my old code.</p> <pre><code> PdfDocument testDocument1 = new PdfDocument(testParametersToDesignUniquePDF1); PdfDocument testDocument2 = new PdfDocument(testParametersToDesignUniquePDF2); PdfDocument testDocument3 = new PdfDocument(testParametersToDesignUniquePDF3); MemoryStream testDocument1Stream = new MemoryStream(); MemoryStream testDocument2Stream = new MemoryStream(); MemoryStream testDocument3Stream = new MemoryStream(); testDocument1.Save(testDocument1Stream); testDocument2.Save(testDocument2Stream); testDocument3.Save(testDocument3Stream); Stream[] source = { testDocument1, testDocument2}; if (testCondition) { source = { testDocument1Stream, testDocument2Stream, testDocument3Stream} } </code></pre> <p>As you can see its only a matter of time before my code gets chunkier as for every PdfDocument, I create I have to create a new memory stream. There's also a limitation of having a static array that I have to keep initializing a new array as more condition applies. I fixed this code with the following below.</p> <p><strong>New Code</strong></p> <p>My Code Refactor is to create a dynamic List that I can add x number of streams based on x conditions. Then convert back to a static size array after I'm done. It saves a lot of extra code creating memory streams and saving my documents on it.</p> <pre><code> List&lt;MemoryStream&gt; memoryStreams = new List&lt;MemoryStream&gt;(); memoryStreams.Add(ConvertToMemoryStream(new PdfDocument(testParametersToDesignUniquePDF1))); memoryStreams.Add(ConvertToMemoryStream(new PdfDocument(testParametersToDesignUniquePDF2))); if (testCondition) { memoryStreams.Add(ConvertToMemoryStream(new PdfDocument(testParametersToDesignUniquePDF3))); } //Convert dynamic linked list back to an array of steam. Stream[] source = memoryStreams.ToArray(); </code></pre> <p>Method to convert PdfDocument to a stream.</p> <pre><code> private MemoryStream ConvertToMemoryStream(PdfDocument document) { MemoryStream stream = new MemoryStream(); document.Save(stream); return stream; } </code></pre> <p>I tested this code to have the same performance and output as the original code. However, the code has more flexibility adding more conditions and PDF's. It is also a lot more readable than the previous code. However, I am worried about a few things.</p> <ol> <li>Deallocation - I might not be taking care of disposing my streams if I manipulate it this way.</li> <li>Time of Deallocation - I'm worried that since I don't have a reference to my streams that it might get disposed on its own before actually using it when I Print the PDF's showing a blank PDF.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T05:39:19.913", "Id": "465199", "Score": "2", "body": "Curious, why do you iterate through the list to create an array instead of using `List<T>.ToArray()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T15:47:47.150", "Id": "465293", "Score": "0", "body": "Great point! I changed it into one line of code =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T18:21:21.117", "Id": "465387", "Score": "0", "body": "Do you really need a collection of streams? If their only purpose is to print, you could use a temporary stream inside a Print() method of a class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T00:43:19.063", "Id": "465415", "Score": "1", "body": "@JeromeViveiros The PdfDocumentBase.Merge method requires a static array of stream of pdfs to merge all my required arrays based on conditions. I needed a collection to dynamically add pdfs based on conditions. I don't store it anywhere, I simply gather all the pdfs I need, collect them in a dynamic list as above, revert it to a static array of stream, and print." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T05:42:50.803", "Id": "465503", "Score": "1", "body": "@Mochi Well, that's a pity. I'd consider reusing streams then, via something like https://github.com/microsoft/Microsoft.IO.RecyclableMemoryStream. Also, in the one answer below, be careful with the ToMemoryStream method, which looks like it will return a disposed stream." } ]
[ { "body": "<p>You might need to create a class handler that would handle the <code>PdfDocument</code> and <code>MemoryStream</code>, which will make things easier to handle and disposed as well. Then, you can just adjust the handler to your application requirements. here is an example : </p>\n\n<pre><code>public class PdfDocumentManager\n{\n // Use Dictionary to keep both PdfDocument and MemoryStream paired.\n // Also, this means, you'll only save unique PdfDocuments and work on them. \n // if you want to save a PdfDocument multiple times (say different copy of the original copy)\n // use List&lt;KeyValuePair&lt;PdfDocument, MemoryStream&gt;&gt; instead.\n private readonly Dictionary&lt;PdfDocument, MemoryStream&gt; _storage = new Dictionary&lt;PdfDocument, MemoryStream&gt;();\n\n public PdfDocumentManager() { }\n\n public void Add(PdfDocument document)\n {\n // don't forget to validate \n\n _storage.Add(document, ToMemoryStream(document));\n }\n\n public void AddRange(IEnumerable&lt;PdfDocument&gt; documents)\n {\n foreach(var document in documents)\n {\n // validate each document before adding it. \n Add(document);\n }\n }\n\n public void Remove(PdfDocument document)\n {\n // code to remove the saved stream.\n // choose MemoryStream or PdfDocument or Both if you want.\n }\n\n private MemoryStream ToMemoryStream(PdfDocument document)\n {\n using (MemoryStream stream = new MemoryStream())\n {\n document.Save(stream);\n return stream;\n }\n }\n\n private PdfDocument ToPDFDocument(MemoryStream stream)\n {\n // code to convert back to memory stream.\n // just search the values to return its key.\n // if there is no match, then create a new PdfDocument along with MemoryStream, then return it back.\n }\n\n public IEnumerable&lt;PdfDocument&gt; GetAvailableDocuments()\n {\n return _storage.Keys;\n }\n\n public IEnumerable&lt;MemoryStream&gt; GetAvailableStreams()\n {\n return _storage.Values;\n }\n\n\n}\n</code></pre>\n\n<p>simple add usage : </p>\n\n<pre><code>// initiate \nvar pdfManager = new PdfDocumentManager();\n\n// add single document \npdfManager.Add(new PdfDocument(testParametersToDesignUniquePDF1));\npdfManager.Add(new PdfDocument(testParametersToDesignUniquePDF2));\n\n// add multiple PdfDocument\nvar pdfDocumentList = new List&lt;PdfDocument&gt;\n{\n new PdfDocument(testParametersToDesignUniquePDF1),\n new PdfDocument(testParametersToDesignUniquePDF2)\n}\n\npdfManager.AddRange(pdfDocumentList);\n</code></pre>\n\n<p>The methods in this class are just for demonstration purpose only. You can bind the idea to your actual needs. With this handler, you can even make it a singleton class or make <code>_storage</code> static to have only one storage for the duration of the application ..etc. You can also move some related conditions inside the class to validate the documents (for instance, if you check if that document existed or not ..etc). This would give you also an easier way to handle the disposable objects. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T11:15:58.727", "Id": "237319", "ParentId": "237270", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T04:25:04.343", "Id": "237270", "Score": "1", "Tags": [ "c#", "performance", "xamarin" ], "Title": "Designing a dynamic array of Memory Streams" }
237270
<p>Given a group of functions that all take similar arguments, eg.</p> <pre><code>void a(Item&amp; item, int line, std::string const&amp; message); bool b(Item&amp; item, int line, float adjustment); </code></pre> <p>(And for other reasons) It's tempting to wrap these into a parameter-structure:</p> <pre><code>struct ItemLine { Item&amp; item; int const line; // note that the const member and the reference both result in a deleted // operator=, so this can only be constructed, not assigned. this is inconvenient // and will be fixed below -- but it would be nice if C++ had a concept of // "const except in operator=" since even though in practice this is overwriting the // storage in-place, logically it is replacing one whole object with another. constexpr ItemLine(Item&amp; item_, int line_) noexcept : item(item_), line(line_) {} }; void a(ItemLine itemLine, std::string const&amp; message); bool b(ItemLine itemLine, float adjustment); </code></pre> <p>Buuut, sometimes you want the <code>Item</code> to be <code>const</code>:</p> <pre><code>int c(Item const&amp; item, int line); </code></pre> <p>This can be done by making a copy of <code>ItemLine</code> that declares <code>Item const&amp; item</code> instead (and a similar change to the constructor).</p> <p>This quickly gets unwieldy however if there's more than one ref/pointer type (so you get more possible combinations of cv-qualification). Also if you want to define additional operations inside the struct that would make sense for both the const-qualified and unqualified cases.</p> <p>"I know, I'll make a template!"</p> <pre><code>/// ItemLine.hpp template&lt;typename T&gt; struct BasicItemLine { // not strictly necessary, due to the explicit instantiation, but doesn't hurt static_assert(std::is_same_v&lt;std::remove_const_t&lt;T&gt;, Item&gt;); T&amp; item; int line; constexpr BasicItemLine(T&amp; item_, int line_) noexcept : item(item_), line(line_) {} // this is to let the Mutable version be passed to something expecting a Const template&lt;typename = std::enable_if_t&lt;!std::is_const_v&lt;T&gt;&gt;&gt; constexpr BasicItemLine(BasicItemLine&lt;T const&gt; const&amp; other) noexcept : item(other.item), line(other.line) {} [[nodiscard]] int Calculate(int foo) const; }; // these are used both because I don't want to define the body of Calculate in // the header and to ensure that it can't be used with any unexpected types. extern template struct BasicItemLine&lt;Item const&gt;; extern template struct BasicItemLine&lt;Item&gt;; using ItemLineConst = BasicItemLine&lt;Item const&gt;; using ItemLineMutable = BasicItemLine&lt;Item&gt;; /// ItemLine.cpp template struct BasicItemLine&lt;Item const&gt;; template struct BasicItemLine&lt;Item&gt;; // the bodies have to be defined twice int ItemLineConst::Calculate(int foo) const { ... } int ItemLineMutable::Calculate(int foo) const { ... } </code></pre> <p>This does work, but it's a bit messy, and still doesn't scale very well if there's more than one value you want to select the const-ness for.</p> <p>I did also consider tuples, which seem a bit tidier (apart from one quirk):</p> <pre><code>struct ItemLineMutable final : std::tuple&lt;Item*, int&gt; { using tuple::tuple; constexpr ItemLineMutable(Item&amp; item_, int line_) : tuple(&amp;item_, line_) {} [[nodiscard]] constexpr Item&amp; item() const noexcept { return *std::get&lt;0&gt;(*this); } [[nodiscard]] constexpr int line() const noexcept { return std::get&lt;1&gt;(*this); } [[nodiscard]] int Calculate(int foo) const; }; struct ItemLineConst final : std::tuple&lt;Item const*, int&gt; { using tuple::tuple; constexpr ItemLineConst(Item const&amp; item_, int line_) : tuple(&amp;item_, line_) {} [[nodiscard]] constexpr Item const&amp; item() const noexcept { return *std::get&lt;0&gt;(*this); } [[nodiscard]] constexpr int line() const noexcept { return std::get&lt;1&gt;(*this); } [[nodiscard]] int Calculate(int foo) const; }; </code></pre> <p>Here, <code>tuple</code> takes care of the storage, and also (via the inherited constructor) appears to magically take care of the implicit conversion from <code>ItemLineMutable</code> to <code>ItemLineConst</code>. The field access is a little more annoying since it requires using getter methods instead of plain fields (or the abomination that is accessing by index), but presumably the compiler will inline these away to nothing in the end anyway.</p> <p>It still requires implementing <code>Calculate</code> twice, but now also requires declaring it twice as well (which can get annoying if you want to define many of these). And it's still almost as tricky to scale this to more than one optionally-const type (though this does take better care of the conversions for you, so you're less likely to miss one than doing it manually -- and it's cleaner than using extern templates).</p> <p>Note that I had to make the tuple hold a pointer rather than a reference, for two reasons. The first is that for some mysterious reason tuple-with-<code>Item&amp;</code> requires <code>Item</code> to be fully defined (not merely a forward reference; due to some internal type trait inspection), which is unacceptable to me. The second is that I wanted <code>operator=</code> to still work. Using <code>reference_wrapper</code> would have been nice (since it does the same thing for much the same reason), but sadly that's not <code>constexpr</code>. (This has the slightly undesired side effect of allowing construction from a pointer as well as a reference, but I consider that relatively harmless (apart from stray <code>nullptr</code>s, but then that's their own fault). It could be fixed by omitting the inherited <code>tuple</code> constructor, but then the mutable-to-const conversion would have to be made explicitly again.)</p> <p>Is there any way to further improve on this whole concept?</p> <blockquote> <p>As an aside: <code>constexpr</code> methods make me sad. Ideally the compiler should not require any methods to be declared <code>constexpr</code> or not -- it should figure out at the point of declaring a <code>constexpr</code> variable whether everything involved in its initialisation can be called at compile time or not, without special annotation on the methods (since by definition it must have the full implementation visible or it's an error anyway). The current system leads to methods that would otherwise be completely fine as constexpr being uncallable because someone forgot to annotate it.</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T07:50:52.120", "Id": "465212", "Score": "2", "body": "I'm not the downvoter, but currently your code is borderline hypothetical code because of generic names like `Item` or `a` `b` `c`. You can make your question on-topic (and also make your code more useful) is to support any type, not just `Item`, by making the type a template parameter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T11:34:52.713", "Id": "465248", "Score": "0", "body": "Is this code that is currently working in a project or are you looking for opinions of what is best? Please see the code review guidelines at https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/dont-ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T22:51:29.807", "Id": "465330", "Score": "0", "body": "This is extracted from real code, I've just changed the names to protect the guilty. And it's not sensible to make the Item type a template parameter (albeit it already kinda is) because the whole point is to give it a specific field name and some associated interesting helper methods. If I wanted something purely generic, I could just use `tuple`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T06:17:18.877", "Id": "237274", "Score": "0", "Tags": [ "c++", "design-patterns", "c++17" ], "Title": "Making a parameter struct that preserves const" }
237274
<p>I made a prototype for a task processing systems. </p> <h2>Architecture</h2> <ul> <li>Worker - is a entity that is processing one-by-one tasks for the same processor.</li> <li>Processor - (also: executable, app) executable file (language agnostic) that getting input from STDIN and returning result to STDOUT with optional logs to STDERR. Return code 0 means success, otherwise - fail.</li> <li>Task - single processing unit that contains saved file as STDIN for the processor</li> </ul> <blockquote> <p>Briefly - worker gets file from <code>tasks</code> directory, feeds it to STDIN of executable.</p> <p>On success (ret code 0) - saves STDOUT to result dir and remove task file.</p> <p>On fail - moves task file to <code>requeue</code> directory. It will be later moved back to <code>tasks</code> directory</p> </blockquote> <p>Logic is quite straight forward and could be described by one diagram</p> <p><img src="https://user-images.githubusercontent.com/6597086/74507235-c464f380-4f36-11ea-8237-0665c7096a81.png" alt="flow"></p> <p>Task states</p> <p><img src="https://user-images.githubusercontent.com/6597086/74504852-7ea52c80-4f30-11ea-9487-b11e383f26c6.png" alt="states"></p> <p>I would like to kindly ask community to review <a href="https://github.com/reddec/retask" rel="noreferrer">the github code</a>. Please advise me how to make better/faster/more idiomatic (C Linux style). I will very appreciate it.</p> <p><strong>worker.h</strong></p> <pre class="lang-c prettyprint-override"><code>/** * Definition of worker in a directory. * Single directory should be handled by single worker */ typedef struct worker_t { char *root; // root directory char *name; // worker ID/name - base name of root directory char *tasks_dir; // directory with files that will be fed to the application as STDIN (tasks) char *requeue_dir; // directory where failed tasks will be added for later re-processing char *progress_dir; // directory where stdout of application will be stored and used as result (on success) char *complete_dir; // directory where stdout of successful tasks execution will be stored char *bin_dir; // directory where application should be stored (first executable file) } worker_t; /** * Initialize worker. Function uses malloc internally to allocate and set worker structure. * Allocated worker should be destroyed by `worker_destroy` * @param worker pointer to worker * @param root_dir root directory that will be used as parent for all nested dirs (tasks, progress, ..) */ void worker_init(worker_t *worker, const char *root_dir); /** * Free all allocated resource in worker * @param worker pre-initialized by `worker_init` instance */ void worker_destroy(worker_t *worker); /** * Prepare environment for worker: creates directories (however, root directory should be already created), * clean old files and so on. * @param worker initialized instance of worker * @return 0 on success, otherwise print error to stderr and return related code */ int worker_prepare(const worker_t *worker); /** * Run all queue tasks: sequentially execute `worker_run_one` for each file in tasks dir, sorted alphabetically. * Fail-tolerant: print error if tasks failed but do not stop next executions. * Mostly error could return if no executable found in bin-dir * @param worker initialized instance of worker * @return 0 on success, otherwise print error to stderr and return related code */ int worker_run_all(const worker_t *worker); /** * Execute only one task identified by name (base name of task file in tasks dir). * In case of failure - task will be automatically re-queued, in case of successful (return code 0) execution - * stdout will be stored in complete-dir with same name as task. * @param worker initialized instance of worker * @param task_name name of task (base name of task file in tasks dir) * @return 0 on success, otherwise print error to stderr and return related code */ int worker_run_one(const worker_t *worker, const char *task_name); /** * Initialize inotify subsystem to watch tasks directory. * @param worker initialized instance of worker * @param listener reference to where inotify file descriptor will be put * @return 0 on success, otherwise print error to stderr and return related code */ int worker_create_listener(const worker_t *worker, int *listener); /** * Wait or inotify events * @param worker initialized instance of worker * @param listener inotify file descriptor (commonly from `worker_create_listener`) * @return 0 on success, otherwise print error to stderr and return related code */ int worker_listen(const worker_t *worker, int listener); /** * Check files in re-queue directory for expired tasks and move them back to tasks dir * @param worker initialized instance of worker * @param expiration_sec expiration time in seconds * @return 0 on success, otherwise print error to stderr and return related code */ int worker_requeue_check(const worker_t *worker, __time_t expiration_sec); </code></pre> <p><strong>worker.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &lt;dirent.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; #include &lt;sys/inotify.h&gt; #include &lt;sys/time.h&gt; #include &lt;unistd.h&gt; #include &lt;errno.h&gt; #include &lt;stdlib.h&gt; #include "task.h" #include "utils.h" void worker_init(worker_t *worker, const char *root_dir) { char *bin_dir = filepath_join(root_dir, "app"); worker-&gt;root = strdup(root_dir); worker-&gt;name = strdup(filepath_basename(root_dir)); worker-&gt;bin_dir = bin_dir; worker-&gt;progress_dir = filepath_join(worker-&gt;root, "progress"); worker-&gt;requeue_dir = filepath_join(worker-&gt;root, "requeue"); worker-&gt;tasks_dir = filepath_join(worker-&gt;root, "tasks"); worker-&gt;complete_dir = filepath_join(worker-&gt;root, "complete"); } void worker_destroy(worker_t *worker) { if (!worker) { return; } free(worker-&gt;root); free(worker-&gt;name); free(worker-&gt;progress_dir); free(worker-&gt;requeue_dir); free(worker-&gt;tasks_dir); free(worker-&gt;complete_dir); free(worker-&gt;bin_dir); } static const mode_t dir_mode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH; int worker_create_dirs(const worker_t *worker) { int ret; ret = mkdir(worker-&gt;tasks_dir, dir_mode); if (ret != 0 &amp;&amp; errno != EEXIST) { perror("retask: create task dir"); return ret; } ret = mkdir(worker-&gt;progress_dir, dir_mode); if (ret != 0 &amp;&amp; errno != EEXIST) { perror("retask: create progress dir"); return ret; } ret = mkdir(worker-&gt;requeue_dir, dir_mode); if (ret != 0 &amp;&amp; errno != EEXIST) { perror("retask: create requeue dir"); return ret; } ret = mkdir(worker-&gt;complete_dir, dir_mode); if (ret != 0 &amp;&amp; errno != EEXIST) { perror("retask: create complete dir"); return ret; } ret = mkdir(worker-&gt;bin_dir, dir_mode); if (ret != 0 &amp;&amp; errno != EEXIST) { perror("retask: create bin dir"); return ret; } return 0; } int worker_clean_progress(const worker_t *worker) { DIR *dp; struct dirent *ep; dp = opendir(worker-&gt;progress_dir); if (!dp) { fprintf(stderr, "retask: open progress dir %s: %s\n", worker-&gt;progress_dir, strerror(errno)); return errno; } while ((ep = readdir(dp))) { if (ep-&gt;d_type == DT_DIR) { continue; } char *path = filepath_join(worker-&gt;progress_dir, ep-&gt;d_name); int ret = remove(path); if (ret != 0) { fprintf(stderr, "retask: remove progress file %s: %s\n", path, strerror(errno)); } free(path); } closedir(dp); return 0; } int worker_prepare(const worker_t *worker) { int ret; ret = worker_create_dirs(worker); if (ret != 0) { return ret; } ret = worker_clean_progress(worker); if (ret != 0) { return ret; } return 0; } int worker_run_all(const worker_t *worker) { struct dirent **namelist; int n = scandir(worker-&gt;tasks_dir, &amp;namelist, NULL, alphasort); if (n == -1) { perror("retask: scandir for tasks"); return -1; } for (int i = 0; i &lt; n; ++i) { struct dirent *entry = namelist[i]; if (entry-&gt;d_type == DT_DIR) { continue; } int ret = worker_run_one(worker, entry-&gt;d_name); if (ret != 0) { fprintf(stderr, "retask: task %s failed with code %i\n", entry-&gt;d_name, ret); } free(entry); } free(namelist); return 0; } int worker_run_one(const worker_t *worker, const char *task_name) { task_t task; int ret = task_init(&amp;task, worker, task_name); if (ret != 0) { return ret; } ret = task_run(&amp;task); task_destroy(&amp;task); fprintf(stderr, "retask: task %s executed with code %i\n", task_name, ret); return ret; } int worker_create_listener(const worker_t *worker, int *listener) { int fd = inotify_init(); if (fd == -1) { fprintf(stderr, "retask: failed to add watcher on directory %s: %s\n", worker-&gt;tasks_dir, strerror(errno)); return -1; } int rc = inotify_add_watch(fd, worker-&gt;tasks_dir, IN_MOVED_TO | IN_CLOSE_WRITE); if (rc == -1) { fprintf(stderr, "retask: failed to add watcher on directory %s: %s\n", worker-&gt;tasks_dir, strerror(errno)); close(fd); return -1; } *listener = fd; return 0; } int worker_listen(const worker_t *worker, int listener) { const struct inotify_event *event; char *ptr; char buf[4096] __attribute__ ((aligned(__alignof__(struct inotify_event)))); ssize_t len = read(listener, buf, sizeof(buf)); if (len == -1 &amp;&amp; errno != EAGAIN) { fprintf(stderr, "retask: failed to listen events on directory %s: %s\n", worker-&gt;tasks_dir, strerror(errno)); return -1; } for (ptr = buf; ptr &lt; buf + len; ptr += sizeof(struct inotify_event) + event-&gt;len) { event = (const struct inotify_event *) ptr; if (event-&gt;len) fprintf(stderr, "retask: detected %s", event-&gt;name); if (event-&gt;mask &amp; IN_ISDIR) fprintf(stderr, " [directory]\n"); else fprintf(stderr, " [file]\n"); } return 0; } int worker_requeue_check(const worker_t *worker, __time_t expiration_sec) { DIR *dp; struct dirent *ep; struct stat info; struct timeval now; int ret = gettimeofday(&amp;now, NULL); if (ret != 0) { fprintf(stderr, "retask: get current date/time: %s\n", strerror(errno)); return ret; } dp = opendir(worker-&gt;requeue_dir); if (!dp) { ret = errno; fprintf(stderr, "retask: open requeue dir %s: %s\n", worker-&gt;requeue_dir, strerror(errno)); return ret; } while ((ep = readdir(dp))) { if (ep-&gt;d_type == DT_DIR) { continue; } char *src = filepath_join(worker-&gt;requeue_dir, ep-&gt;d_name); ret = stat(src, &amp;info); if (ret != 0) { fprintf(stderr, "retask: stat queued file %s: %s\n", src, strerror(errno)); free(src); continue; } if (info.st_ctim.tv_sec + expiration_sec &gt; now.tv_sec) { continue; } char *dst = filepath_join(worker-&gt;tasks_dir, ep-&gt;d_name); ret = rename(src, dst); if (ret != 0) { fprintf(stderr, "retask: failed move queued file %s to tasks %s: %s\n", src, dst, strerror(errno)); } else { fprintf(stderr, "retask: re-queued file %s due to expiration time\n", src); } free(dst); free(src); } closedir(dp); return 0; } </code></pre> <p><strong>task.h</strong></p> <pre class="lang-c prettyprint-override"><code>#include "worker.h" /** * Definition of single task inside worker. Worker should not be destroyed before task. */ typedef struct task_t { char *name; // task name (basename of task file) char *file; // task file. The file will be used as STDIN for the executable char *progress_file; // temp file for STDOUT of the executable char *result_file; // destination of progress file in case of successful execution (ret code 0) char *requeue_file; // destination for task file in case of failed execution (for re-queue) char *executable; // executable (first file marked as executable inside bin dir) const worker_t *worker; // reference to parent worker instance } task_t; /** * Initialize internal resource for task, allocate paths, detect executable in a bin dir. * Paths will be allocated by malloc. * @param task reference to task that will be initialized * @param worker initialized instance of worker * @param task_name task name (basename of file in tasks dir) * @return 0 on success, otherwise print error to stderr and return related code */ int task_init(task_t *task, const worker_t *worker, const char *task_name); /** * Destroy (free) allocated resource (worker ref will not be touched) * @param task initialized instance of task */ void task_destroy(task_t *task); /** * Run executable and process result files (re-queue or move to complete). This function internally runs fork and fill * following environment variables: WORKER_ID, WORKER_ROOT_DIR, WORKER_BIN_DIR, WORKER_TASKS_DIR, TASK_ID, TASK_EXECUTABLE. * Task file will be used as STDIN and progress file as STDOUT. STDERR will be mapped as parent process. * @param task initialized instance of task * @return 0 on success, otherwise print error to stderr and return related code */ int task_run(const task_t *task); </code></pre> <p><strong>task.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;errno.h&gt; #include &lt;string.h&gt; #include &lt;sys/wait.h&gt; #include &lt;sys/prctl.h&gt; #include "../include/utils.h" #include "../include/task.h" int __run_app(const task_t *task, int stdin_file, int stdout_file); int task_init(task_t *task, const worker_t *worker, const char *task_name) { char *executable = find_executable(worker-&gt;bin_dir); if (!executable) { return -1; } task-&gt;name = strdup(task_name); task-&gt;file = filepath_join(worker-&gt;tasks_dir, task_name); task-&gt;progress_file = filepath_join(worker-&gt;progress_dir, task_name); task-&gt;result_file = filepath_join(worker-&gt;complete_dir, task_name); task-&gt;requeue_file = filepath_join(worker-&gt;requeue_dir, task_name); task-&gt;executable = executable; task-&gt;worker = worker; return 0; } void task_destroy(task_t *task) { free(task-&gt;file); free(task-&gt;progress_file); free(task-&gt;result_file); free(task-&gt;requeue_file); free(task-&gt;executable); free(task-&gt;name); } int task_run_app(const task_t *task) { FILE *progress = fopen(task-&gt;progress_file, "w"); if (!progress) { fprintf(stderr, "retask: create progress file %s: %s", task-&gt;progress_file, strerror(errno)); return 1; } FILE *source = fopen(task-&gt;file, "r"); if (!source) { fprintf(stderr, "retask: read task file %s: %s", task-&gt;file, strerror(errno)); fclose(progress); return 2; } int ret = __run_app(task, fileno(source), fileno(progress)); fclose(source); fclose(progress); return ret; } int __run_app(const task_t *task, int stdin_file, int stdout_file) { pid_t pid = 0; pid = fork(); if (pid == 0) { dup2(stdin_file, STDIN_FILENO); dup2(stdout_file, STDOUT_FILENO); prctl(PR_SET_PDEATHSIG, SIGTERM); setenv("WORKER_ID", task-&gt;worker-&gt;name, 1); setenv("WORKER_ROOT_DIR", task-&gt;worker-&gt;root, 1); setenv("WORKER_BIN_DIR", task-&gt;worker-&gt;bin_dir, 1); setenv("WORKER_TASKS_DIR", task-&gt;worker-&gt;tasks_dir, 1); setenv("TASK_ID", task-&gt;name, 1); setenv("TASK_EXECUTABLE", task-&gt;executable, 1); execl(task-&gt;executable, task-&gt;executable, (char *) NULL); _exit(1); } int status; if (waitpid(pid, &amp;status, 0) == -1) { perror("waitpid() failed"); return 1; } if (WIFEXITED(status)) { return WEXITSTATUS(status); } return status; } int task_complete(const task_t *task, int ret_code) { if (ret_code != 0) { remove(task-&gt;progress_file); return rename(task-&gt;file, task-&gt;requeue_file); } ret_code = rename(task-&gt;progress_file, task-&gt;result_file); if (ret_code != 0) { return ret_code; } return remove(task-&gt;file); } int task_run(const task_t *task) { int ret_code = task_run_app(task); ret_code = task_complete(task, ret_code); return ret_code; } </code></pre> <p><strong>utils.h</strong></p> <pre class="lang-c prettyprint-override"><code>/** * Concat root dir and child with respect of root dir ending (with / or without). * It is caller responsible to free returned memory. * @param root_dir parent directory * @param child child directory * @return joined path */ char *filepath_join(const char *root_dir, const char *child); /** * Find first file with executable flag. * It is caller responsible to free returned memory. * @param bin_dir directory to scan * @return full path on success, otherwise print error to stderr and return NULL */ char *find_executable(const char *bin_dir); /** * Get basename (last part after /). There is no memory allocation here. * @param root_dir path to scan * @return ref to the first symbol in root_dir var */ const char *filepath_basename(const char *root_dir); </code></pre> <p><strong>utils.c</strong></p> <pre class="lang-c prettyprint-override"><code> #include &lt;dirent.h&gt; #include &lt;string.h&gt; #include &lt;stdio.h&gt; #include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; #include &lt;errno.h&gt; #include "../include/utils.h" char *find_executable(const char *bin_dir) { DIR *dirp; struct dirent *direntp; dirp = opendir(bin_dir); if (dirp == NULL) { fprintf(stderr, "can't detect executable in %s: %s\n", bin_dir, strerror(errno)); return NULL; } for (;;) { direntp = readdir(dirp); if (direntp == NULL) { break; } if (direntp-&gt;d_type == DT_DIR) { continue; } char *path = filepath_join(bin_dir, direntp-&gt;d_name); if (access(path, X_OK) != -1) { closedir(dirp); return path; } free(path); } closedir(dirp); fprintf(stderr, "there is no executable file in %s\n", bin_dir); return NULL; } char *filepath_join(const char *root_dir, const char *child) { size_t child_len = strlen(child); size_t root_len = strlen(root_dir); size_t n = root_len + child_len + 1; char need_slash = 0; if (root_len &gt; 0 &amp;&amp; root_dir[root_len - 1] != '/') { ++n; need_slash = 1; } char *data = (char *) malloc(n); memcpy(data, root_dir, root_len); if (need_slash) { data[root_len] = '/'; } memcpy(&amp;data[root_len + need_slash], child, child_len); data[n - 1] = '\0'; return data; } const char *filepath_basename(const char *root_dir) { size_t len = strlen(root_dir); if (len == 0) { return root_dir; } for (ssize_t i = len - 1; i &gt;= 0; --i) { if (root_dir[i] == '/') { return &amp;root_dir[i + 1]; } } return root_dir; } </code></pre> <p><strong>main.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &lt;unistd.h&gt; #include &lt;stdlib.h&gt; #include &lt;sys/prctl.h&gt; #include &lt;stdio.h&gt; #include &lt;wait.h&gt; #include &lt;string.h&gt; #include &lt;errno.h&gt; #include &lt;stdnoreturn.h&gt; #include "worker.h" static const long DEFAULT_REQUEUE_INTERVAL = 5; static const char DEFAULT_LOCATION[] = "."; static const char REQUEUE_PROCESS[] = "requeue"; noreturn void run_requeue(worker_t *worker, long requeue_interval) { long wait_seconds = requeue_interval / 2; if (wait_seconds &lt; 1) { wait_seconds = 1; } for (;;) { int ret = worker_requeue_check(worker, requeue_interval); if (ret != 0) { fprintf(stderr, "retask: requeue failed with code %i\n", ret); } sleep(wait_seconds); } } int run_worker(worker_t *worker) { int ret; int listener; ret = worker_create_listener(worker, &amp;listener); if (ret != 0) { return ret; } for (;;) { ret = worker_run_all(worker); if (ret != 0) { break; } ret = worker_listen(worker, listener); if (ret != 0) { break; } } close(listener); return 0; } int launch(worker_t *worker, long requeue_interval) { int ret = worker_prepare(worker); if (ret != 0) { return ret; } if (fork() == 0) { // sub process to manage requeue process size_t name_len = strlen(worker-&gt;name); char *process_name = (char *) malloc(name_len + 1 + sizeof(REQUEUE_PROCESS)); memcpy(process_name, worker-&gt;name, name_len); process_name[name_len] = '/'; memcpy(&amp;process_name[name_len + 1], REQUEUE_PROCESS, sizeof(REQUEUE_PROCESS)); prctl(PR_SET_NAME, process_name, 0, 0, 0); prctl(PR_SET_PDEATHSIG, SIGTERM); free(process_name); run_requeue(worker, requeue_interval); _exit(EXIT_FAILURE); } return run_worker(worker); } void usage() { fprintf(stderr, "Executor for tasks from filesystem\n"); fprintf(stderr, "\n"); fprintf(stderr, "Author: Baryshnikov Aleksandr &lt;owner@reddec.net&gt;\n"); fprintf(stderr, "\n"); fprintf(stderr, "retask [flags]\n"); fprintf(stderr, " -c &lt;directory&gt; [default=.] use specified directory as work dir\n"); fprintf(stderr, " -r &lt;seconds&gt; [default=%li] interval for requeue\n", DEFAULT_REQUEUE_INTERVAL); } int main(int argc, char *argv[]) { int opt; const char *location = DEFAULT_LOCATION; long requeue_sec = DEFAULT_REQUEUE_INTERVAL; while ((opt = getopt(argc, argv, "c:r:")) != -1) { switch (opt) { case 'r': { requeue_sec = strtol(optarg, NULL, 10); if (errno == EINVAL || errno == ERANGE) { fprintf(stderr, "invalid value for requeue interval: %s\n", optarg); usage(); exit(EXIT_FAILURE); } break; } case 'c': { location = optarg; break; } default: /* '?' */ usage(); exit(EXIT_FAILURE); } } worker_t worker; worker_init(&amp;worker, location); int ret = launch(&amp;worker, requeue_sec); worker_destroy(&amp;worker); return ret; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T11:07:53.807", "Id": "465356", "Score": "1", "body": "I didn't examine all the code, but could there be multiple workers competing for the same type of tasks? If so, what would happen if two workers simultaneously selected the same task? If that can happen, you might want to avoid this using some atomic primitive (e.g. `rename(2)` or `flock(2)`) to claim a task." } ]
[ { "body": "<p>It's a good idea for <code>worker.c</code> to include <code>\"worker.h\"</code>, preferably as the very first line. That ensures that the declarations are consistent and that the header has no missing includes of its own. (So, in <code>task.c</code> move the <code>task.h</code> include to the top spot, and similarly with <code>utils.h</code> in <code>utils.c</code>.)</p>\n\n<p>I recommend adding include-guards on all your header files. I know there's no intention to multiply-include any of them, but it can easily happen, particularly when they include each other.</p>\n\n<p>Your error-checking on I/O operations is commendable - well done. However, I noticed an unchecked <code>malloc()</code> in <code>filepath_join()</code> that should be addressed (in passing, it also has a pointless cast). All the callers of <code>filepath_join()</code> need to be prepared for that, too.</p>\n\n<p>There's a similar unchecked <code>malloc()</code> and pointless cast in <code>main()</code>, where we initialise <code>process_name</code>.</p>\n\n<p>In <code>main()</code>, we shouldn't assume that <code>errno</code> is unset when we call <code>strtol()</code> - if it's successful, then <code>errno</code> may be left unchanged.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:23:46.033", "Id": "465234", "Score": "1", "body": "Thank you a lot! Do you mean that malloc should be checked for a NULL return in case of exception? Is it an almost impossible case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:29:03.620", "Id": "465237", "Score": "5", "body": "Yes, `malloc()` can return a null pointer, and a program like this should certainly check for that - as a long-running process, there's more to lose than in a short utility that's easily re-run. Also, this kind of program is more likely to be run in a container or other environment with reduced `ulimit` values, so allocation failure might be more likely than you're used to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:50:27.933", "Id": "465240", "Score": "0", "body": "Thanks! It is a very valuable review. Updated in a repo" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T16:02:02.700", "Id": "465381", "Score": "1", "body": "The current recommendation of what to do when `malloc()` returns `NULL` is to crash, but not everybody's on board with that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T08:34:23.727", "Id": "465524", "Score": "0", "body": "@Joshua, I certainly don't think that's a good choice in a long-running server like this. It's almost tolerable in a small utility that could simply be re-started easily, but server processes randomly crashing would certainly give a poor impression. Not something I could recommend with a clear conscience!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T15:42:32.077", "Id": "465587", "Score": "0", "body": "@TobySpeight: Do you disable OOM and overcommit? If you don't disable both, you will get random processes killed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T15:51:53.110", "Id": "465588", "Score": "0", "body": "@Joshua: I don't disable those on every system, but certainly on quite a few servers. I tend more to rely on setting `ulimit -v` appropriately for known troublemakers." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:13:32.693", "Id": "237281", "ParentId": "237275", "Score": "16" } }, { "body": "<h1>Make sure Doxygen picks up comments after struct members</h1>\n\n<p>It's good to add a comment after each member in a struct declaration to describe what that member does. To make Doxygen pick up the <a href=\"http://www.doxygen.nl/manual/docblocks.html#memberdoc\" rel=\"noreferrer\">member documentation</a> as well, use <code>//!&lt;</code> or <code>///&lt;</code> instead of <code>//</code> to start the comments with.</p>\n\n<h1>Use \"filename\" or \"path\", not \"file\" describe filenames</h1>\n\n<p>You will be dealing with both file handles (either a <code>FILE *</code> or something like <code>int fd</code>) as well as filenames in your code. To distinguish between the two, be consistent and name variables that hold names of files \"filename\", \"filepath\" or \"path\", so you can use \"file\" consistently to denote a handle to a file.</p>\n\n<p>Similarly, use \"dirname\", \"dirpath\", or \"path\" for variables holding directory names, to not get confused with a <code>DIR *</code> handle.</p>\n\n<h1>Move <code>launch()</code> and related functions into <code>worker.c</code></h1>\n\n<p>Some worker-related functionality is in <code>main.c</code> instead of in <code>worker.c</code>. It's best to keep all the worker-related functionality together, and expose as little as possible of its internal workings. In <code>main()</code> I see:</p>\n\n<pre><code>worker_t worker;\nworker_init(&amp;worker, location);\nint ret = launch(&amp;worker, requeue_sec);\nworker_destroy(&amp;worker);\n</code></pre>\n\n<p>Unless there is a reason to split running the worker into three functions, I think it would be simpler if you could just write:</p>\n\n<pre><code>int ret = worker_launch(location, requeue_sec);\n</code></pre>\n\n<p>The function <code>worker_launch()</code> should live in <code>worker.c</code>, and basically do the same as <code>worker_init()</code>, <code>launch()</code> and <code>worker_destroy()</code>.</p>\n\n<p>Then in principle only <code>worker_launch()</code> has to be declared in <code>worker.h</code>, and the rest of the functions could be made <code>static</code>.</p>\n\n<p>I see a similar pattern with tasks inside <code>worker_run_once()</code>. Perhaps you can do the same and just have <code>task_run()</code> call <code>task_init()</code> and <code>task_destroy()</code> internally?</p>\n\n<h1>Consider having the worker <code>chdir()</code> to the worker root</h1>\n\n<p>You are keeping track of a lot of directory names, and have to do a lot of path joining. It might make sense to just <code>chdir(root_dir)</code> in <code>worker_init()</code>. Then you don't have to store any of the directory names in <code>worker_t</code>.</p>\n\n<p>Of course, you have to be careful that this does not violate assumptions in other parts of your program. However, since starting the worker is the only thing you do in <code>main()</code>, this seems fine.</p>\n\n<h1>Why does <code>worker_requeue_check()</code> need to run as a separate process?</h1>\n\n<p>I don't see why you need to run a separate process to requeue tasks. You can do this deterministically. Run <code>worker_requeue_check()</code> after every call to <code>worker_run_once()</code> inside the loop in <code>worker_run_all()</code>. If you want to avoid rescanning the directory so often, you can just check the time and avoid calling it if the last time you called it is less than <code>requeue_interval / 2</code>. You also have to call it once with a <code>requeue_interval</code> of <code>0</code> after the loop, to ensure that if the task directory is empty and <code>worker_run_all()</code> would exit, that it immediately requeues the failed tasks.</p>\n\n<p>Alternatively, instead of rescanning <code>requeue_dir</code> every so often, you can keep a linked list of failed tasks along with the timestamp of failing. Then you just have to compare the timestamp of the first entry in the list to the current time to see if there is anything to requeue.</p>\n\n<h1>Don't use variable or function names starting with underscores</h1>\n\n<p>Identifiers starting with an underscore are reserved for use by the standard library. Not all combinations are reserved, but it's best to just not declare anything yourself that starts with one. So instead of <code>__run_app()</code>, just write <code>run_app()</code>.</p>\n\n<p>If you want to hide a symbol, the simplest way is to make it <code>static</code>. If it needs to be visible to other object files, but if you want to somehow indicate that some symbol is private, use underscores as a suffix.</p>\n\n<h1>Consider using <code>posix_spawn()</code> instead of <code>fork()</code>+<code>execl()</code></h1>\n\n<p>The function <a href=\"http://man7.org/linux/man-pages/man3/posix_spawn.3.html\" rel=\"noreferrer\"><code>posix_spawn()</code></a> is made to start a new executable, and it can do a lot of housekeeping necessary to ensure the new process starts with a fresh environment. There are helper functions, like <code>posix_spawn_file_actions_adddup2()</code>, that allow you to redirect I/O.</p>\n\n<h1>Consider using <code>asprintf()</code> to build strings</h1>\n\n<p>You are already using a lot of Linux-specific functions, so consider using <code>asprintf()</code> to build a new string instead of doing a lot of low-level string manipulation. For example, <code>filepath_join()</code> can be rewritten as:</p>\n\n<pre><code>#define _GNU_SOURCE\n#include &lt;stdio.h&gt;\n...\nchar *filepath_join(const char *root_dir, const char *child) {\n char *data = NULL;\n asprintf(&amp;data, \"%s/%s\", root_dir, child);\n return data;\n}\n</code></pre>\n\n<p>Having two consecutive slashes in a filename is not a problem, so I wouldn't waste code on trying to remove an extraneous slash after <code>root_dir</code>.</p>\n\n<h1>Use <code>basename()</code> instead of writing your own function</h1>\n\n<p>Again, since you are already writing Linux-specific code, consider using <a href=\"http://man7.org/linux/man-pages/man3/basename.3.html\" rel=\"noreferrer\"><code>basename()</code></a> directly.</p>\n\n<h1>Make the path to the executable explicit</h1>\n\n<p>It's very weird to see code that gets the first executable in a directory. There is no guarantee in which order directories are traversed. So if there is more than one, it is not deterministic what your task runner is going to do. Why not pass the full filename to the executable to the worker?</p>\n\n<h1>Confusing use of brackets in <code>usage()</code></h1>\n\n<p>In <code>usage()</code>, I see the following:</p>\n\n<pre><code>fprintf(stderr, \"retask [flags]\\n\");\nfprintf(stderr, \" -c &lt;directory&gt; [default=.] use specified directory as work dir\\n\");\nfprintf(stderr, \" -r &lt;seconds&gt; [default=%li] interval for requeue\\n\", DEFAULT_REQUEUE_INTERVAL);\n</code></pre>\n\n<p>In the first line, brackets are used to indicate optional arguments. That's indeed the standard way to represent those. But subsequent lines, you also write brackets around the default value. This is a bit confusing. I recommend you rewrite it to:</p>\n\n<pre><code>fprintf(stderr, \" -c &lt;directory&gt; Use specified directory as work dir. Default: %s\\n\", DEFAULT_LOCATION);\nfprintf(stderr, \" -r &lt;seconds&gt; Interval for requeue. Default: %i\\n\", DEFAULT_REQUEUE_INTERVAL);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T11:49:19.733", "Id": "465250", "Score": "0", "body": "Thanks, but according to https://lwn.net/Articles/360509/ `posix_spawn` is not a good option" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T16:54:50.723", "Id": "465301", "Score": "1", "body": "@AlexBar, In review the link provided, I don't see any indictment of `posix_spawn`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T10:06:59.997", "Id": "237283", "ParentId": "237275", "Score": "13" } }, { "body": "<p>You should consider to check the return value of malloc, on main.c you have</p>\n\n<pre><code>char *process_name = (char *) malloc(name_len + 1 + sizeof(REQUEUE_PROCESS));\nmemcpy(process_name, worker-&gt;name, name_len);\n</code></pre>\n\n<p>Consider that malloc could fail and you will have a problem.</p>\n\n<pre><code>char *process_name = (char *) malloc(name_len + 1 + sizeof(REQUEUE_PROCESS));\nif (process_name != NULL) {\n memcpy(process_name, worker-&gt;name, name_len);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T11:39:49.720", "Id": "465358", "Score": "0", "body": "On Linux `malloc()` is [quite unlikely](https://news.ycombinator.com/item?id=7541650) to return `NULL`, so you should consider if the effort of trying to deal with `malloc()` failure is worth spending." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T08:32:27.843", "Id": "465523", "Score": "0", "body": "That's a misconception based on common desktop configurations (with unlimited `ulimit -v`). It's certainly not true for all processes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T10:30:30.687", "Id": "237284", "ParentId": "237275", "Score": "3" } }, { "body": "<p>I only want to add some nitpicks, but otherwise a really clean code base!</p>\n\n<h1>Don't create types with<code>_t</code> suffix</h1>\n\n<p>These types are reserved by POSIX and C is currently even moving to claiming some of these, too.</p>\n\n<h1>Use function prototypes</h1>\n\n<p>Currently you don't use function prototypes for functions with no arguments, eg.</p>\n\n<pre><code>void f();\n</code></pre>\n\n<p>This declaration defines the existence of a function returning void but \"doesn't specify* whether it takes any arguments. To provide the necessary parameters (ie. that it does take no arguments), use:</p>\n\n<pre><code>void f(void);\n</code></pre>\n\n<p>This will allow the compiler to error-check for mismatching definitions/declarations.</p>\n\n<h1>Error handling: Print path</h1>\n\n<p>While it's a common pattern to eg. do</p>\n\n<pre><code>if (err = foo(), err == -1) {\n perror(\"progname: foo\");\n}\n// Prints\n// progname: foo: Some error message.\n</code></pre>\n\n<p>It's sensible to use a different pattern for functions like open:</p>\n\n<pre><code>if (fd = open(\"bla.txt\", mode), fd == -1) {\n perror(\"progname: bla.txt\");\n}\n// Prints eg.\n// progname: bla.txt: File not found\n</code></pre>\n\n<p>You chose a kinda in-between approach, describing the specific file with \"worker dir\" or something similar, however this makes it hard to understand errors, eg. when the path to worker dir is ill-formed for some reason. I'd print that rather significant information for debugging as part of the message. The message about \"worker dir creation failed\" is more of a user-centered message. I'd split those (developer-centric, end-user-centric) to have this:</p>\n\n<pre><code>fprintf(stderr, \"retask: %s: %s\\n\n \"Worker for creation failed\\n\", path, strerror(errno));\n</code></pre>\n\n<h1>Declare variables when used</h1>\n\n<p>Since C99 you can declare variables later, when needed. This gives you far more possibilities for using <code>const</code> and often makes it easier to read as you don't need to \"remember\" what the variable was meant to say.</p>\n\n<h1>Vertical space</h1>\n\n<p>I'd use some empty lines to structure more, like paragraphs when writing prose. It makes it easier on the eyes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T11:08:49.320", "Id": "237318", "ParentId": "237275", "Score": "7" } } ]
{ "AcceptedAnswerId": "237281", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T07:07:56.953", "Id": "237275", "Score": "13", "Tags": [ "c", "linux", "posix" ], "Title": "Light task-processing systems with zero dependency for Linux systems" }
237275
<p>Edit</p> <ul> <li>If there is a better way to ask this question to avoid negative votes, please let me know.</li> <li>I have looked into <a href="https://codereview.stackexchange.com/help/how-to-ask">https://codereview.stackexchange.com/help/how-to-ask</a></li> </ul> <p>How would I implement a class dedicated to returning html strings for a list of products/cart items?</p> <ul> <li>Written as part of an interview assignment.</li> <li>Simply this is a shopping website with some items a user may add or remove from their shopping cart.</li> <li>This function is responsible for returning the html to display for the list of cart items.</li> <li>Currently there is no dedicated class for returning html strings.</li> <li>I feel I would be moving most of this code into another class, defeating the point.</li> </ul> <p>Code: </p> <pre><code>function listItems() { $formatter = new Formatter(); $html = ""; $id = 0; foreach ($_SESSION["Cart"] as $item) { if ($item["quantity"] &gt; 0) { $html = $html . '&lt;pre&gt; &lt;div class="name"&gt;'.$this&gt;getName($item) .'&lt;/div&gt;&lt;div class="price"&gt;Price: $' . $formatter-&gt;formatPrice($item) . '&lt;/div&gt; &lt;div class="quantity"&gt;Quantity: ' . $item["quantity"] . '&lt;/div&gt; &lt;div class="total"&gt;Total: $' . $this-&gt;getTotal($item) . '&lt;/div&gt; &lt;form class="removeForm" method="POST"&gt; &lt;input class="removeInput" type="hidden" name="removeId" value=' . $id . ' /&gt; &lt;input class="removeInput" type="submit" name="removeButton" value="Remove from Cart" /&gt; &lt;/form&gt; &lt;/pre&gt;'; } $id++; } $html = $html . '&lt;pre&gt; &lt;div class="overallTotal"&gt;Overall Total: $' . $this-&gt;getOverallTotal() . '&lt;/div&gt; &lt;/pre&gt;'; return $html; } </code></pre> <p>Formatter class method returns a number with 2 decimal point format.</p> <p>Full Repository here if you want more to critique: </p> <ul> <li><a href="https://github.com/NathanielPather/Basic-Shopping-Cart/blob/Post-Code-Review/ShoppingCart.php" rel="nofollow noreferrer">https://github.com/NathanielPather/Basic-Shopping-Cart/blob/Post-Code-Review/ShoppingCart.php</a></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:02:03.407", "Id": "465226", "Score": "1", "body": "The down-vote may be triggered by introducing the code `How would I implement`, making it look [*not implemented yet*](https://codereview.stackexchange.com/help/on-topic) - down-voters, please comment! OTOH, the post does *not* show the implementation of such a class: if you got one, include it. (If not, I think the question off-topic.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:07:32.600", "Id": "465229", "Score": "0", "body": "I didn't mention anything about html output earlier and was looking for general advice to improve this function. So to specify I added a desire to have an output class.\n\nI don't really know what I want other than to \"be better\" which is too general. I only picked this function because I thought it could be improved, but I don't have an argument as to why I think that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:12:51.070", "Id": "465231", "Score": "1", "body": "`I [presented] this function because I thought it could be improved, but I don't have an argument as to why I think that` one of the \"use cases\" for CodeReview@SE. Just stay [on topic](https://codereview.stackexchange.com/help/on-topic) and [don't ask in a way to avoid](https://codereview.stackexchange.com/help/dont-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:26:27.873", "Id": "465235", "Score": "0", "body": "Sorry, I don't understand `one of the \"use cases\" for CodeReview@SE`. Are you saying your quote of me doesn't follow the use case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:37:46.933", "Id": "465238", "Score": "0", "body": "(I left out *I think that to be*. But: you *urgently* need to remove parts about code not yet written. This question may be *closed* - ***not*** meaning *go away*, but *this should not be answered unless improved*.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T09:38:34.600", "Id": "465239", "Score": "0", "body": "(Out for ~8 hours - sorry, sort of.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T10:43:12.070", "Id": "465242", "Score": "0", "body": "You should include all the code from the github link directly into you question. I have posted a review of all the code. When you include all the code, you will get my upvote as well. :)" } ]
[ { "body": "<p>You might want to decompose it into smaller pieces that will be easier to follow and eventually modify.</p>\n\n<p>You could also learn a bit about dependency injection. Creating new instances all around anytime you need them is not very good.</p>\n\n<p>Here is a very simple rewrite of your code and a lot of pieces are missing but I hope it gives some general guideline.</p>\n\n<p>It uses PHP 7.4 features, if you can't use those, of course ignore all the typehints, etc..</p>\n\n<p>Also it might make sense to depend on interfaces instead of classes directly, but didn't want to go this far as I think it could be too much for you at one go.</p>\n\n<hr>\n\n<p>Dont be shy to define structures.</p>\n\n<pre><code>class Product\n{\n public int $id;\n public string $name;\n public float $price;\n\n public function __construct(int $id, string $name, float $price)\n {\n $this-&gt;id = $id;\n $this-&gt;name = $name;\n $this-&gt;price = $price;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Create product repository</p>\n\n<pre><code>class ProductsRepository\n{\n /**\n * @param array&lt;int&gt; $ids\n * @return array&lt;int, Product&gt;\n */ \n function getProducts(array $ids): array\n {\n // get it from somewhere\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Structure for item in cart holds a bit more.</p>\n\n<pre><code>class CartItem\n{\n public int $productId;\n public string $name;\n public float $unitPrice;\n public int $quantity;\n public function __construct(int $productId, string $name, float $unitPrice, int $quantity = 1)\n {\n $this-&gt;productId = $productId;\n $this-&gt;name = $name;\n $this-&gt;unitPrice = $unitPrice;\n $this-&gt;quantity = $quantity;\n }\n public function getTotalPrice(): float\n {\n return $this-&gt;unitPrice * $this-&gt;quantity;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Cart holds many items, allows to iterate them, and add them and it knows the product repository to allow it doing so.</p>\n\n<pre><code>class Cart\n{\n private ProductsRepository $products;\n /** @var array&lt;CartItem&gt; */\n private array $items;\n public function __construct(ProductsRepository $products, array $items = [])\n {\n $this-&gt;products = $products;\n $this-&gt;items = $items;\n }\n public function getItems(): array\n {\n return $this-&gt;items;\n }\n\n public function getTotalPrice(): int\n {\n // count it here, or have it in property and make sure it is updated while adding items.\n }\n\n public function add(int $productId, int $quantity = 1)\n {\n if (isset($this-&gt;items[$productId])) {\n // already in cart =&gt; increase quatity\n } else {\n $product = $this-&gt;products-&gt;getProduct($productId);\n //handle product not exists, not on stock, etc.\n $this-&gt;items[$productId] = new CartItem($product-&gt;id, $product-&gt;name, $product-&gt;price, $quantity);\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>We will store cart in session, this will take care of it.</p>\n\n<pre><code>class CartSessionStorage\n{\n // we need it for the Cart instances\n // and maybe we wont store product names in session but load them from products repo?\n private ProductsRepository $products;\n\n public function loadCart(): Cart\n {\n // load from session\n }\n public function saveCart(Cart $cart): void\n {\n // save to session\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Renderer knows the html structure and some localization/formatting rules.</p>\n\n<pre><code>class CartRenderer\n{\n private Formatter $formatter;\n public function __construct(Formatter $formatter)\n {\n $this-&gt;formatter = $formatter;\n }\n public function renderCart(Cart $cart): string\n {\n $html = '';\n // your rendering here;\n foreach ($cart-&gt;getItems() as $item) {\n //you can use heredoc, but add some html escaping, nor heredoc nor your code handle it\n $html .= \n &lt;&lt;&lt;HTML\n &lt;div&gt;write html here&lt;div&gt;and dont mind if u use &lt;span&gt;{$item-&gt;getTotalPrice()}&lt;/span&gt;\n HTML;\n }\n return $html;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Put it all together.</p>\n\n<pre><code>$products = new ProductsRepository();\n$storage = new SessionCartStorage(products);\n$formatter = new Formatter();\n$renderer = new CartRenderer($formatter);\n</code></pre>\n\n<hr>\n\n<p>And there you go.</p>\n\n<pre><code>$cart = $storage-&gt;loadCart();\n\n// form submission?\n$cart-&gt;add($productId, $quantity);\n$storage-&gt;saveCart($cart);\n\n// render it\necho $renderer-&gt;renderCart($cart);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T13:28:53.217", "Id": "466437", "Score": "0", "body": "Thank you for the in-depth code review.\n\nI found the dependency injection design pattern the most interest and useful point. I've read up on it and think I understand the gist of it.\n\nThis really helped a lot, and I will definitely be referring to this review for a while." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T10:31:43.720", "Id": "237285", "ParentId": "237276", "Score": "1" } } ]
{ "AcceptedAnswerId": "237285", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T07:20:55.217", "Id": "237276", "Score": "1", "Tags": [ "php" ], "Title": "PHP Shopping Website with Cart - Returning a HTML String" }
237276
<p>I got this problem on a HackerRank challenge and this was the best I could come up with. It's basically just using DFS to find connected components (in this case, friend circles). I was having a tough time figuring out how to track unvisited nodes. Please let me know how I can improve this code. It appears to work, but the test cases given were quite simple.</p> <p><strong>Problem:</strong></p> <p>There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature, i.e., if A is friend of B and B is friend of C, then A is also friend of C. A friend circle is a group of students who are directly or indirectly friends.</p> <p>You have to complete a function <code>int friendCircles(char[][] friends)</code> which returns the number of friend circles in the class. Its argument, friends, is a <code>NxN</code> matrix which consists of characters "Y" or "N". If <code>friends[i][j] == "Y"</code> then i-th and j-th students are friends with each other, otherwise not. You have to return the total number of friend circles in the class.</p> <pre><code>Sample Input 0: 4 YYNN YYYN NYYN NNNY Sample Output 0: 2 Explanation 0: There are two pairs of friends [0, 1] and [1, 2]. So [0, 2] is also a pair of friends by transitivity. So first friend circle contains (0, 1, 2) and second friend circle contains only student 3 Sample Input 1: 5 YNNNN NYNNN NNYNN NNNYN NNNNY Sample output 1: 5 </code></pre> <p>Constraints (sorry, couldn't get formatting down so I had to put the constraints down here):</p> <ul> <li>1 &lt;= N &lt;= 300.</li> <li>Each element of matrix friends will be "Y" or "N".</li> <li>Number of rows and columns will be equal in friends.</li> <li>friends[i][j] = "Y", where 0 &lt;= i &lt; N.</li> <li>friends[i][j] = friends[j][i], where 0 &lt;= i &lt; j &lt; N.</li> </ul> <p><strong>Solution:</strong></p> <pre><code>import java.util.ArrayDeque; import java.util.Deque; import java.util.HashSet; import java.util.Set; public class Solution { public static int friendsCircle(char[][] friends) { // The only alternative I could think of, instead of // tracking unvisited nodes, was to put visited nodes // in a set and then do setOfAllNodes.removeAll(visited) // to see which nodes are still unvisited Set&lt;Integer&gt; unvisited = new HashSet&lt;&gt;(); boolean[] visited = new boolean[friends.length]; Deque&lt;Integer&gt; stack = new ArrayDeque&lt;&gt;(); int connectedComponents = 0; for (int i = 0; i &lt; friends.length; i++) { unvisited.add(i); } // dfs on friends matrix while (!unvisited.isEmpty()) { stack.push(unvisited.iterator().next()); connectedComponents++; while (!stack.isEmpty()) { int currVertex = stack.pop(); if (visited[currVertex] == false) { visited[currVertex] = true; unvisited.remove(currVertex); for (int i = 0; i &lt; friends[currVertex].length; i++) { if (friends[currVertex][i] == 'Y' &amp;&amp; visited[i] == false) { stack.push(i); } } } } } return connectedComponents; } public static void main(String[] args) { char[][] friends = { {'Y','Y','N','N'}, {'Y','Y','Y','N'}, {'N','Y','Y','N'}, {'N','N','N','Y'} }; System.out.println(friendsCircle(friends)); } } </code></pre>
[]
[ { "body": "<p>Welcome to Code Review. Your code is good and easy to read, you can iterate over only half of the matrix (in my case the elements of the matrix a[i,j] with i &lt; j) because from the test matrices always results a[i, j] = a[j, i] so friendship in symmetric .\nI'm using a <code>TreeMap&lt;Integer, Set&lt;Integer&gt;&gt;</code> to store initial situation to guarantee natural order of the keys so it will always the lower index the index where friends will be added : everybody is friend of himself (reflexive property) so map[i]={ i }.</p>\n\n<pre><code>int n = friends.length;\nMap&lt;Integer, Set&lt;Integer&gt;&gt; map = new TreeMap&lt;&gt;();\nfor (int i = 0; i &lt; n; ++i) {\n Set&lt;Integer&gt; set = new TreeSet&lt;&gt;();\n set.add(i);\n map.put(i, set);\n}\n</code></pre>\n\n<p>Now I check all elements a[i, j] with i &lt; j and see if i appears as key in the map: if yes I add j to map[j], otherwise it means that i appears in another set and I will add j to this set. At the end in any case I will remove the key j:</p>\n\n<pre><code>for (int i = 0; i &lt; n; ++i) {\n for (int j = 0; j &lt; n; ++j) {\n if (i &lt; j &amp;&amp; friends[i][j] == 'Y') {\n if (map.containsKey(i)) {\n map.get(i).add(j); \n } else {\n for (Integer key : map.keySet()) {\n Set&lt;Integer&gt; set = map.get(key);\n if (set.contains(i)) {\n set.add(j);\n }\n }\n }\n map.remove(j);\n }\n }\n}\n</code></pre>\n\n<p>The number of circles will coincide with the number of keys present in the map at the end:</p>\n\n<pre><code>public static int CountFriendsCircles(char[][] friends) {\n int n = friends.length;\n Map&lt;Integer, Set&lt;Integer&gt;&gt; map = new TreeMap&lt;&gt;();\n for (int i = 0; i &lt; n; ++i) {\n Set&lt;Integer&gt; set = new TreeSet&lt;&gt;();\n set.add(i);\n map.put(i, set);\n }\n\n for (int i = 0; i &lt; n; ++i) {\n for (int j = 0; j &lt; n; ++j) {\n if (i &lt; j &amp;&amp; friends[i][j] == 'Y') {\n if (map.containsKey(i)) {\n map.get(i).add(j); \n } else {\n for (Integer key : map.keySet()) {\n Set&lt;Integer&gt; set = map.get(key);\n if (set.contains(i)) {\n set.add(j);\n }\n }\n }\n map.remove(j);\n }\n }\n }\n\n return map.size();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:24:02.553", "Id": "237297", "ParentId": "237278", "Score": "4" } }, { "body": "<p>I have suggestions for you.</p>\n\n<ol>\n<li><p>The <code>unvisited</code> should be renamed <code>unvisitedIndexes</code> in my opinion.</p></li>\n<li><p>I suggest that you create a method to build the <code>unvisited</code> set to separate the logic from the main method.</p></li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static int friendsCircle(char[][] friends) {\n Set&lt;Integer&gt; unvisited = buildUnvisitedSet(friends);\n}\n\nprivate static Set&lt;Integer&gt; buildUnvisitedSet(char[][] friends) {\n Set&lt;Integer&gt; unvisited = new HashSet&lt;&gt;();\n for (int i = 0; i &lt; friends.length; i++) {\n unvisited.add(i);\n }\n return unvisited;\n}\n</code></pre>\n\n<ol start=\"3\">\n<li><p>Instead of using <code>visited[currVertex] == false</code> and <code>visited[i] == false</code>, you can use <code>!visited[currVertex]</code> and <code>!visited[i]</code>.</p></li>\n<li><p>You can make a method to check if the current node is visited or not, instead of handling the array each time.</p></li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static int friendsCircle(char[][] friends) {\n //[...]\n if (isNotVisited(visited, currVertex)) {\n //[...]\n }\n //[...]\n}\n\npublic static boolean isNotVisited(boolean[] visited, int index) {\n return !visited[index];\n}\n</code></pre>\n\n<ol start=\"5\">\n<li>I suggest that you extract the logic that finds the friend position in a method, this will make the code shorter and easier to read.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static int friendsCircle(char[][] friends) {\n //[...]\n int friendPosition = findFriendPosition(friends, visited, currVertex);\n if (friendPosition != -1) {\n stack.push(friendPosition);\n }\n //[...]\n}\n\nprivate static int findFriendPosition(char[][] friends, boolean[] visited, int currVertex) {\n for (int i = 0; i &lt; friends[currVertex].length; i++) {\n if (friends[currVertex][i] == 'Y' &amp;&amp; isNotVisited(visited, i)) {\n return i;\n }\n }\n return -1;\n}\n</code></pre>\n\n<h2>Refoctored code</h2>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n char[][] friends = {\n {'Y', 'Y', 'N', 'N'},\n {'Y', 'Y', 'Y', 'N'},\n {'N', 'Y', 'Y', 'N'},\n {'N', 'N', 'N', 'Y'}\n };\n System.out.println(friendsCircle(friends));\n}\n\npublic static int friendsCircle(char[][] friends) {\n\n boolean[] visited = new boolean[friends.length];\n Set&lt;Integer&gt; unvisitedIndexes = buildUnvisitedSet(friends);\n\n Deque&lt;Integer&gt; stack = new ArrayDeque&lt;&gt;();\n int connectedComponents = 0;\n\n // dfs on friends matrix\n while (!unvisitedIndexes.isEmpty()) {\n stack.push(unvisitedIndexes.iterator().next());\n connectedComponents++;\n\n while (!stack.isEmpty()) {\n int currVertex = stack.pop();\n\n if (isNotVisited(visited, currVertex)) {\n visited[currVertex] = true;\n unvisitedIndexes.remove(currVertex);\n\n int friendPosition = findFriendPosition(friends, visited, currVertex);\n if (friendPosition != -1) {\n stack.push(friendPosition);\n }\n }\n }\n }\n\n return connectedComponents;\n}\n\nprivate static int findFriendPosition(char[][] friends, boolean[] visited, int currVertex) {\n for (int i = 0; i &lt; friends[currVertex].length; i++) {\n if (friends[currVertex][i] == 'Y' &amp;&amp; isNotVisited(visited, i)) {\n return i;\n }\n }\n return -1;\n}\n\npublic static boolean isNotVisited(boolean[] visited, int index) {\n return !visited[index];\n}\n\nprivate static Set&lt;Integer&gt; buildUnvisitedSet(char[][] friends) {\n // The only alternative I could think of, instead of\n // tracking unvisited nodes, was to put visited nodes\n // in a set and then do setOfAllNodes.removeAll(visited)\n // to see which nodes are still unvisited\n Set&lt;Integer&gt; unvisited = new HashSet&lt;&gt;();\n for (int i = 0; i &lt; friends.length; i++) {\n unvisited.add(i);\n }\n return unvisited;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:25:12.873", "Id": "237298", "ParentId": "237278", "Score": "1" } } ]
{ "AcceptedAnswerId": "237297", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T08:00:40.410", "Id": "237278", "Score": "5", "Tags": [ "java", "programming-challenge", "graph" ], "Title": "HackerRank: Friend Circles (DFS in Java)" }
237278
<p>Here I have a class where I'm checking if <code>model_id</code> exists in the table <code>models_web_tbl</code>.</p> <p>Everything works like a charm but I just want to know if I'm on the right path.</p> <pre><code>class test extends dbh{ public function modelExist($model_id) { $sql = "SELECT * FROM models_web_tbl WHERE model_id = ?"; $stmt = $this-&gt;connect()-&gt;prepare($sql); $stmt-&gt;execute([$model_id]); $match = $stmt-&gt;fetch(PDO::FETCH_OBJ); if ($match &gt; 0){ echo "found"; }else { $model_web_twitter = "twitter"; $sql = "INSERT INTO models_web_tbl (model_web_twitter, model_id) VALUES (?, ?)"; $stmt = $this-&gt;connect()-&gt;prepare($sql); $stmt-&gt;execute([$model_web_twitter, $model_id]); } } } $model_id = 66; $exist = new test (); $exist = $exist-&gt;modelExist($model_id); </code></pre>
[]
[ { "body": "<p>Function <code>modelExist</code> should check if model exists and return boolean. Your function does something completely different. It only needs that check for its job.</p>\n\n<pre><code>public function modelExists(int $modelId): bool;\n</code></pre>\n\n<p>To check existence of a row, you don't need all its columns. Select just <code>1</code> (literally) and check if you have received a row from the query or not.</p>\n\n<pre><code>SELECT 1 FROM models_web_tbl WHERE model_id = ?\n</code></pre>\n\n<p>Create another function for the insert</p>\n\n<pre><code>public function insertModel(int $modelId, string $modelWeb): void\n</code></pre>\n\n<p>Maybe you wanted to combine it into another function.</p>\n\n<pre><code>public function tryInsert(int $modelId, string $modelWeb): bool\n{\n if ($this-&gt;modelExists($modelId)) {\n return false;\n }\n $this-&gt;insert($modelId, $modelWeb);\n return true;\n}\n</code></pre>\n\n<p>Don't connect to database again for every query</p>\n\n<pre><code>class test\n{\n private PDO $connection;\n function __construct(PDO $connection) {\n $this-&gt;connection = $connection;\n }\n function modelExists(int $modelId): bool\n {\n // ...\n $this-&gt;connection-&gt;prepare($sql);\n // ...\n }\n\n function insert(int $modelId, $modelWeb): void\n { \n // ...\n $this-&gt;connection-&gt;prepare($sql);\n // ...\n }\n}\n</code></pre>\n\n<pre><code>$connection = connect();\n$test = new test($connection);\n // I don't know why it was important to assign 'twitter' to a variable first :)\nif (!$test-&gt;tryInsert($model_id, 'twitter')) {\n // echo definitely dont belong into exists-check function\n echo \"found\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T11:14:45.167", "Id": "465244", "Score": "0", "body": "Is there a criterion to choose between `SELECT 1` or `SELECT COUNT(*)` for the query? (Obviously makes no difference if `model_id` is a key, but we can't know that here)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T11:27:42.257", "Id": "465247", "Score": "0", "body": "@TobySpeight well if model_id is unique then you at least save the dummy aggregation (it really is not needed so why adding, its like adding extra noops for no reason), but the difference will be miniscule. So it is just a convention or preference I guess. However if it was not unique, it would even make sense to add `LIMIT 1` and definitely avoid `COUNT`, unless you really need to know the exact count. But in this case only \"none vs. any\" is requested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T12:24:36.443", "Id": "465251", "Score": "0", "body": "Thanks; I see that `LIMIT 1` is a better choice for ensuring we're not sent a huge result." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T11:04:54.257", "Id": "237288", "ParentId": "237286", "Score": "2" } }, { "body": "<p>The code you posted doesn't seem to be doing what it says. From the way it is called and from the method's name one could tell it is intended to check if the id exists or not. But it doesn't return any answer to this question. instead it inserts some info into a database, which is extremely confusing.</p>\n\n<p>Also this code does some strange things like echoing the word \"found\" or overwriting the $exist variable with null value. </p>\n\n<p>Therefore, the first and foremost thing you need to do is to make this code <em>consistent</em>. After that it will be possible to review it. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T13:12:34.437", "Id": "237293", "ParentId": "237286", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T10:35:23.463", "Id": "237286", "Score": "0", "Tags": [ "php", "database" ], "Title": "Check if ID exist or not" }
237286
<p>I am currently working on writing a library for use with LIFX light bulbs over their UDP API. I have written the code for creating the packet headers, but I'm unsure whether it is the most idiomatic approach, as I am new to Clojure. Please tell me what you think about the following code.</p> <pre><code>(ns lifx-lib.packet.header (:require [clj-struct.core :as struct])) (def protocol-num 1024) (def header-size 36) (defn- frame-header [size tagged source] (struct/pack "&lt;2HI" size (bit-or protocol-num 0x1000 (if tagged 0x3000 0x0000)) source)) (defn- address-header [address resp ack sequence] (struct/pack "&lt;2Q" address (bit-or (if resp (bit-shift-left 1 48) 0) (if ack (bit-shift-left 1 49) 0) (bit-shift-left sequence 56)))) (defn- protocol-header [type] (struct/pack "&lt;Q2H" 0 type 0)) (defn create-header [params] (let [ size (:size params 0) tagged (:tagged params true) source (:source params 0) address (:address params 0) resp (:resp params false) ack (:ack params false) type (:type params 0) sequence (:sequence params 0)] (into [] (concat (frame-header size tagged source) (address-header address resp ack sequence) (protocol-header type))))) </code></pre>
[]
[ { "body": "<p>Looks pretty good to me. There are a few shortcuts you could add if you don't mind using the Tupelo Clojure library. One of them is <a href=\"https://cljdoc.org/d/tupelo/tupelo/0.9.190/api/tupelo.core#vals-%3Emap\" rel=\"nofollow noreferrer\">vals->map</a>\nand <a href=\"https://cljdoc.org/d/tupelo/tupelo/0.9.190/api/tupelo.core#with-map-vals\" rel=\"nofollow noreferrer\">with-map-vals</a>. </p>\n\n<p>Called with a list of symbols like <code>(vals-&gt;map a b c)</code> returns a map like <code>{:a a :b b :c c}</code>:</p>\n\n<pre><code>(let [a 1\n b 2\n c 3]\n (vals-&gt;map a b c)) ;=&gt; {:a 1 :b 2 :c 3} }\n</code></pre>\n\n<p>Given a map like <code>{:a 1 :b 2 :c 3}</code> (such as generated by <code>(vals-&gt;map a b c)</code>), performs safe let destructuring using <code>grab</code> like:</p>\n\n<pre><code> (let [some-map {:a 1 :b 2 :c 3} } ]\n (with-map-vals some-map [a b c]\n (+ a b c))) ;=&gt; 6\n</code></pre>\n\n<p><code>with-map-vals</code> is safe for typos since <code>grab</code> will throw if the requested key is not present. See vals->map for simple creation of labeled data maps.</p>\n\n<p>For default values, I think the simplest way is like this:</p>\n\n<pre><code> (let [defaults {:a 1 :dir :up :name \"joe\"}\n v1 {:a 2}\n v2 {:a 9 :dir :left :name \"sally\"}]\n (spyx (into defaults v1))\n (spyx (glue defaults v2))\n</code></pre>\n\n<p>There is also the pure clojure way:</p>\n\n<pre><code>; Pure clojure way\n(let [{:keys [a dir name ] } v1]\n (spyx :pure-1 (vals-&gt;map a dir name)) )\n\n; can't use `defaults` here, need map with keyword =&gt; symbol\n(let [{:keys [a dir name] :or {a 1 dir :up name \"joe\"}} v1] \n (spyx :pure-2 (vals-&gt;map a dir name)))\n\n(let [{:keys [a dir name ] :or {a 1 dir :up name \"joe\"}} v2] \n (spyx :pure-1 (vals-&gt;map a dir name)) )\n</code></pre>\n\n<p>See also <a href=\"https://clojure.org/guides/destructuring\" rel=\"nofollow noreferrer\">Clojure Destructuring</a>.</p>\n\n<hr>\n\n<p>Lastly, instead of <code>concat</code> I like to use <a href=\"https://github.com/cloojure/tupelo#gluing-together-like-collections\" rel=\"nofollow noreferrer\">glue</a>.</p>\n\n<pre><code>; Glue together like collections:\n(is (= (glue [ 1 2] '(3 4) [ 5 6] ) [ 1 2 3 4 5 6 ] )) ; all sequential (vectors &amp; lists)\n(is (= (glue {:a 1} {:b 2} {:c 3} ) {:a 1 :c 3 :b 2} )) ; all maps\n(is (= (glue #{1 2} #{3 4} #{6 5} ) #{ 1 2 6 5 3 4 } )) ; all sets\n(is (= (glue \"I\" \" like \" \\a \" nap!\" ) \"I like a nap!\" )) ; all text (strings &amp; chars)\n\n; If you want to convert to a sorted set or map, just put an empty one first:\n(is (= (glue (sorted-map) {:a 1} {:b 2} {:c 3}) {:a 1 :b 2 :c 3} ))\n(is (= (glue (sorted-set) #{1 2} #{3 4} #{6 5}) #{ 1 2 3 4 5 6 } ))\n</code></pre>\n\n<hr>\n\n<p>Lastly, I wouldn't bother with <code>defn-</code> It just makes testing harder and provides little value. If you have non-public functions that you don't want in the documentation (via the <code>lein-codox</code> plugin), you can add metadata to the function like:</p>\n\n<pre><code>(defn ^:no-doc my-helper-fn\n ...)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T15:17:19.027", "Id": "237300", "ParentId": "237289", "Score": "2" } } ]
{ "AcceptedAnswerId": "237300", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T12:26:08.330", "Id": "237289", "Score": "3", "Tags": [ "clojure" ], "Title": "Constructing a packet header" }
237289
<p>I'm looking to find what security flaws this code might have. I believe it's immune to time attacks, passwords are stored encrypted, and I'm using sessions to store local data. </p> <p>Let's assume the following:</p> <ul> <li>All traffic is over SSL</li> <li>Users have to re-authenticate after 30 minutes of inactivity</li> </ul> <p>Login page:</p> <pre><code>{% block body %} &lt;p&gt;CMS index&lt;/p&gt; &lt;form id="login" action="/login" method="post"&gt; &lt;input type="text" name="username" placeholder="Username"&gt; &lt;input type="password" name="password" placeholder="Password"&gt; &lt;input type="submit" class="success button" value="Submit"&gt; &lt;/form&gt; &lt;form id="createUser" action="/createUser" method="post"&gt; &lt;input type="text" name="username" placeholder="Username"&gt; &lt;input type="password" name="password" placeholder="Password"&gt; &lt;input type="password" name="vPass" placeholder="Verify Password"&gt; &lt;input type="submit" class="success button" value="Submit"&gt; &lt;/form&gt; {% endblock %} </code></pre> <p>Flask app:</p> <pre><code>@app.route('/cms/') def cmsHome(): return render_template('cmsIndex.html') @app.route('/login', methods = ['POST', 'GET']) def cmsLogin(): result = request.form user = User() sessionId = user.loginUser(result['username'], result['password']) if sessionId != False: session['id'] = sessionId return redirect(url_for('cmsEvents')) else: return redirect(url_for('cmsHome')) @app.route('/createUser/', methods = ['POST', 'GET']) def createUser(): result = request.form user = User() check = user.createUser(result['username'], result['password'], result['vPass']) if check == True: flash('Account created') elif check == False: flash("Your username/password is too short (3/8) or passwords don't match") return redirect(url_for('cmsHome')) @app.route('/cmsevents/') @app.route('/cmsevents/&lt;page&gt;') def cmsEvents(page = 1): return "Made it" </code></pre> <p>Class:</p> <pre><code>import time, json, requests, pymysql, string, random from passlib.hash import bcrypt class User: def __init__(self): pass def createUser(self, username, password, vPass): dbm = Database() if len(username) &lt; 3: return False if len(password) &lt; 8: return False if password != vPass: return False password = bcrypt.hash(password) with dbm.con: dbm.cur.execute("INSERT INTO admin.users (username, password) VALUES (%s, %s)", (username, password)) return True def loginUser(self, username, password): dbm = Database() with dbm.con: dbm.cur.execute("SELECT id FROM admin.users WHERE username = %s", (username, )) if dbm.cur.rowcount == 1: dbm.cur.execute("SELECT password FROM admin.users WHERE username = %s", (username, )) fetch = dbm.cur.fetchone() check = bcrypt.verify(password, fetch[0]) if check == True: sessionId = bcrypt.hash(username + ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(40))) dbm.cur.execute("UPDATE admin.users SET session = %s WHERE username = %s", (sessionId, username)) return sessionId else: return False else: return False def verifyUser(self, sessionId): dbm = Database() with dbm.con: dbm.cur.execute("SELECT id FROM admin.users WHERE session = %s", (sessionId, )) if dbm.cur.rowcount == 1: return True else: return False </code></pre> <p>I realize this code could use some touching up (properly redirect when there's no session, manage users by id instead of username, etc), but I want to know about any security issues before continuing.</p> <p>I know about Flask-Login, please don't recommend it. I'm doing this by hand for the learning experience.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T13:47:11.487", "Id": "237294", "Score": "4", "Tags": [ "python", "python-3.x", "flask" ], "Title": "Potential Security Threats With Custom Login" }
237294
<p>Consider a struct with a name two Int values :</p> <pre><code>struct StructWithNameAndTwoInts { let name: String let from: Int let to: Int } </code></pre> <p>Now I want to compare two structs based on the values of <code>from</code> and <code>to</code>. There are three possibilities:</p> <blockquote> <p>Not equal: <code>from</code> and <code>to</code> from both structs are different.</p> <p>Half equal: Both <code>from</code>s are equal, but both <code>to</code>s are not.</p> <p>Equal: Both <code>from</code>s are equal and both <code>to</code>s are equal.</p> </blockquote> <p>I also need to take into consideration the from and to could be swapped, so I cannot just use <code>A == B</code>. I came up with the following:</p> <p>The three results could be in an enum:</p> <pre><code>enum CompareResult { case equal case halfEqual case notEqual } </code></pre> <p>Then I could write a function for <code>StructWithTwoInts</code> to do the comparison:</p> <pre><code>func compareWith(_ other: StructWithTwoInts) -&gt; CompareResult { if (self.from == other.from &amp;&amp; self.to == other.to) || (self.from == other.to &amp;&amp; self.to == other.from) { return .equal } else if (self.from == other.from &amp;&amp; self.to != other.to) || (self.from == other.to &amp;&amp; self.to != other.from) { return .halfEqual } else if (self.from != other.from &amp;&amp; self.to != other.to) || (self.from != other.to &amp;&amp; self.to != other.from) { return .notEqual } } </code></pre> <p>And finally:</p> <pre><code>let A = StructWithNameAndTwoInts(name: "Foo", from: 5, to: 28) let B = StructWithNameAndTwoInts(name: "Bar", from: 5, to: 22) let C = StructWithNameAndTwoInts(name: "Baz", from: 2, to: 22) let D = StructWithNameAndTwoInts(name: "Drop", from: 28, to: 5) let result1 = A.compareWith(B) // .halfEqual let result2 = A.compareWith(C) // .notEqual let result3 = A.compareWith(D) // .equal </code></pre> <p>This worked, but feels like a kludge. Is there anyway to write this differently?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:21:01.470", "Id": "465270", "Score": "0", "body": "Hold up why would the to and from be different but still be equal? That defies the statement in your post itself/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:21:55.027", "Id": "465271", "Score": "0", "body": "Also, please provide full context - did we even need to know this name property exists? If you mention it, you should include it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:22:11.153", "Id": "465272", "Score": "0", "body": "So if A = (3, 24) and B = (24, 3) they should be equal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:23:14.747", "Id": "465273", "Score": "0", "body": "I left the name out because I am not comparing the names in this particular case, only the from and to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:23:24.507", "Id": "465274", "Score": "0", "body": "But they aren't! If two things are moving towards each other, that does not put them at the same position. And if you are not including the name or other properties, don't tell us that they exist." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:24:13.890", "Id": "465276", "Score": "0", "body": "That would indeed be the case if they were coordinates, but they are not in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:27:24.643", "Id": "465278", "Score": "0", "body": "Your structure has poor naming. Is it really just a MyStruct? Or is there a name that would be helpful?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:28:53.007", "Id": "465279", "Score": "0", "body": "The name of the struct is completely irrelevant. Could you please focus your comments on the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:31:07.127", "Id": "465280", "Score": "0", "body": "My review on your question is of the only actual code you have here, and that is in the first block. My primary complaint is that there are poor naming conventions, you are telling us that there is additional info that is irrelevant, and if it truly is, we don't need to know it exists. So either put it in the code or do not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:33:10.793", "Id": "465281", "Score": "0", "body": "Fine, I will update the question so you can focus on the review of the three lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:36:23.587", "Id": "465282", "Score": "1", "body": "_**My primary complaint is that there are poor naming conventions**_: Calling it a \"StructWithTwoInts\" is no more useful than calling it \"MyStruct\". Still just as useless, and no more meaningful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:39:11.737", "Id": "465283", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/104463/discussion-between-freezephoenix-and-koen)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T22:07:19.277", "Id": "465325", "Score": "1", "body": "The close reason is misleading - I put the final close vote in because the code submitted for review cannot possibly compile, which makes it non-working code by definition. Feel free to address the review points from [the answer below](https://codereview.stackexchange.com/a/237310/23788) and then post the updated code as a new, well-formed question with actual working code. See [how to post a follow-up question?](https://codereview.meta.stackexchange.com/q/1065/23788) on meta for all the details." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T03:10:32.217", "Id": "465343", "Score": "0", "body": "Fair enough about closing the question. Just for the record, I edited the question after the (in my opinion) irrelevant comments about lack of context and misleading struct naming. The edited code was entered in the browser without testing in Xcode. The answer below has a lot of useful suggestions so I will leave it here." } ]
[ { "body": "<p>A couple of issues:</p>\n\n<ol>\n<li><p>Your <code>compareWith(_:)</code> will not compile, as you have a path of execution where you are not returning any value. </p></li>\n<li><p>We’ve also moved away from method names with the trailing preposition, and might name it <code>compare(with:)</code> instead. Or because you're not considering the name associated with these pairs of numbers, I might call it <code>compareValues(with:)</code> to make it unambiguous that we’re ignoring the name associated with this pair, and only comparing their respective values.</p></li>\n<li><p>I might suggest giving this structure a more meaningful name. In the absence of more information, I'll just call it a <code>NamedPair</code>.</p>\n\n<pre><code>struct NamedPair {\n let name: String\n let from: Int\n let to: Int\n}\n</code></pre>\n\n<p>That having been said, I'd probably rename <code>from</code> and <code>to</code> as well because that suggests some directionality which may or may not be valid. (I also wouldn't generally use a preposition, alone, for a property name, probably leaning towards <code>fromValue</code> and <code>toValue</code> at the very least.) But as you haven't shared the functional intent for this structure, I've left those property names alone.</p></li>\n<li><p>I might be inclined to use tuples for the equality state and separate out the “reversed” scenario into its own test, to make the intent absolutely explicit and clear.</p>\n\n<p>I also think you're missing the “half equal” scenario where <code>self.to == other.from</code>.</p>\n\n<p>Anyway, pulling that together, perhaps something:</p>\n\n<pre><code>extension NamedPair {\n enum CompareResult {\n case equal\n case halfEqual\n case notEqual\n }\n\n func compareValues(with other: NamedPair) -&gt; CompareResult {\n if (from, to) == (other.from, other.to) {\n return .equal\n } else if (from, to) == (other.to, other.from) {\n return .equal\n } else if from == other.from || from == other.to || to == other.to || to == other.from {\n return .halfEqual\n } else {\n return .notEqual\n }\n }\n}\n</code></pre></li>\n<li><p>While I've called this <code>NamedPair</code>, it strikes me that this might be, more generally, a <code>NamedSet</code>, where you might just want to know whether the sets match, intersect, or are disjoint:</p>\n\n<pre><code>struct NamedSet {\n let name: String\n let set: Set&lt;Int&gt;\n}\n\nextension NamedSet {\n enum CompareResult {\n case equal\n case intersect\n case disjoint\n }\n\n func compareValues(with other: NamedSet) -&gt; CompareResult {\n if set == other.set {\n return .equal \n } else if set.isDisjoint(with: other.set) {\n return .disjoint\n } else {\n return .intersect\n }\n }\n}\n</code></pre>\n\n<p>Not only does this handle the generalized scenario, but it offloads the equality and intersection logic to the existing <code>Set</code> type.</p></li>\n<li><p>For what it’s worth, these are both seem like good candidates to be generics:</p>\n\n<pre><code>struct NamedPair&lt;T: Comparable&gt; {\n let name: String\n let from: T\n let to: T\n}\n\nextension NamedPair {\n enum CompareResult {\n case equal\n case halfEqual\n case notEqual\n }\n\n func compareValues(with other: NamedPair) -&gt; CompareResult {\n if (from, to) == (other.from, other.to) {\n return .equal\n } else if (from, to) == (other.to, other.from) {\n return .equal\n } else if from == other.from || from == other.to || to == other.to || to == other.from {\n return .halfEqual\n } else {\n return .notEqual\n }\n }\n}\n</code></pre>\n\n<p>And</p>\n\n<pre><code>struct NamedSet&lt;T: Hashable&gt; {\n let name: String\n let set: Set&lt;T&gt;\n}\n\nextension NamedSet {\n enum CompareResult {\n case equal\n case intersect\n case disjoint\n }\n\n func compareValues(with other: NamedSet) -&gt; CompareResult {\n if set == other.set {\n return .equal \n } else if set.isDisjoint(with: other.set) {\n return .disjoint\n } else {\n return .intersect\n }\n }\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T03:04:53.203", "Id": "465342", "Score": "1", "body": "Ah, using a Set makes a lot of sense. I'll go over all your comments this weekend." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T21:59:08.743", "Id": "237310", "ParentId": "237295", "Score": "4" } } ]
{ "AcceptedAnswerId": "237310", "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T14:06:20.320", "Id": "237295", "Score": "-2", "Tags": [ "swift" ], "Title": "Comparing two structs in Swift" }
237295
<p>In the start of one of my methods I have a section of code that needs to get three sub-lists of grouped dictionaries from a list of grouped dictionaries. This is a big list and I'm optimizing it a little by only looking at a smaller sub-list generated from a communal attribute.</p> <p>Is there a faster a way to generate these three lists. </p> <p>Code </p> <pre><code> private List&lt;List&lt;CellData&gt;&gt; FormatOfficeData(List&lt;Dictionary&lt;References.ColHeaders, CellData&gt;&gt; dataOffice) { List&lt;Dictionary&lt;References.ColHeaders, CellData&gt;&gt; dataDownTown = new List&lt;Dictionary&lt;References.ColHeaders, CellData&gt;&gt;(); List&lt;Dictionary&lt;References.ColHeaders, CellData&gt;&gt; dataSuburban = new List&lt;Dictionary&lt;References.ColHeaders, CellData&gt;&gt;(); List&lt;Dictionary&lt;References.ColHeaders, CellData&gt;&gt; dataTotal = new List&lt;Dictionary&lt;References.ColHeaders, CellData&gt;&gt;(); dataOffice = dataOffice.Where(x =&gt; x[References.ColHeaders.AssetClass].val == "All Classes" &amp;&amp; ( x[References.ColHeaders.Submarket].val == "Downtown" || x[References.ColHeaders.Submarket].val == "Suburban" || x[References.ColHeaders.Submarket].val == "Total")).ToList(); dataDownTown = dataOffice.Where(x =&gt; x[References.ColHeaders.Submarket].val == "Downtown").ToList(); dataSuburban = dataOffice.Where(x =&gt; x[References.ColHeaders.Submarket].val == "Suburban").ToList(); dataTotal = dataOffice.Where(x =&gt; x[References.ColHeaders.Submarket].val == "Total").ToList(); ... Code continues </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T20:13:16.860", "Id": "465318", "Score": "0", "body": "you should provide a working code. non-working codes will be ignored." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T20:33:46.020", "Id": "465319", "Score": "0", "body": "The code does work. I can just simply return null and the everything works. Or do you mean I should post all code that implement this function? I can recreate dummy data and pass it in if need be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T20:37:31.503", "Id": "465320", "Score": "0", "body": "yes, minimal code is required and sample data is appreciated as well as an example of how the data needs to be organized." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T20:47:48.347", "Id": "465321", "Score": "2", "body": "@Mandelbrotter you should post the full code (the method code) plus any implemented functions, classes, interfaces ..etc. that are used in the code. providing this is required." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T15:26:05.290", "Id": "237301", "Score": "1", "Tags": [ "c#", "performance" ], "Title": "What would be a more optimal way of filtering a list into sub-lists" }
237301
<p>Since I'm new at this site I will try to start with something very simple.</p> <p>I'm making an "Automatic insert" in a Excel Spreadsheet and my code is working correctly, but I'm not so sure about my way of coding. Does the code follow good VBA programming practices?</p> <p>Here is my code:</p> <pre><code>Option Explicit Sub inserisciAutomatico() Application.ScreenUpdating = False Application.EnableEvents = False Dim KitNr As String Dim KitNrAppoggio As String Dim kitNrSecondoAppoggio As String Dim provaFormula As Range Dim primoValore As String Dim numeroID As String Dim descrizione As String Dim gruppo As String Dim concatena As String Dim disegno As String Dim treD As String Dim distinta As String Dim immagine As String Dim formulaCopy As String Dim cell As Range Dim risultato As Range Dim risultatoAppoggio As Range Dim valore As String Dim appoggio As String Dim provissima As Integer valore = Worksheets("CODICI").ComboBox1.Value appoggio = "fine" Set cell = Worksheets("CODICI").Range("D4:D250").Find(valore) 'Debug.Print cell.Address Set risultato = Worksheets("CODICI").Range("D4:D250").Find(appoggio, LookIn:=xlValues, After:=cell) Set risultatoAppoggio = Worksheets("CODICI").Range("D4:D250").Find(Worksheets("CODICI").ComboBox1.Value, LookIn:=xlValues) 'Debug.Print risultato.Address 'Debug.Print risultatoAppoggio.Address 'kitNr = risultato.Offset(0, -2) kitNrSecondoAppoggio = risultatoAppoggio.Offset(-1, -3) Set provaFormula = Worksheets("CODICI").Range("Z1") provaFormula.FormulaArray = "=MAX(IF(LEFT(B7:B250,1)=""" &amp; kitNrSecondoAppoggio &amp; """, B7:B250))" KitNr = Worksheets("CODICI").Range("Z1").Value Debug.Print provaFormula.FormulaArray KitNrAppoggio = KitNr + 1 'Application.WorksheetFunction.Max (Range("a:a")) Range(risultato.Address).EntireRow.Insert primoValore = risultato.Offset(-1, -3).Address numeroID = risultato.Offset(-1, -2).Address descrizione = risultato.Offset(-1, 0).Address gruppo = risultato.Offset(-1, 1).Address concatena = risultato.Offset(-1, 2).Address disegno = risultato.Offset(-1, 3).Address treD = risultato.Offset(-1, 4).Address distinta = risultato.Offset(-1, 5).Address immagine = risultato.Offset(-1, 6).Address formulaCopy = risultato.Offset(-2, 2).Address Range(primoValore).Value = "T0" Range(numeroID).Value = KitNrAppoggio Range(numeroID).Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous 'Range(numeroID).Borders(xlEdgeBottom).Weight = xlHairline Range(numeroID).Font.Bold = False Range(numeroID).Font.Name = "Calibri" Range(numeroID).Font.Size = 10 Range(descrizione).Font.Bold = False Range(descrizione).Font.Name = "Calibri" Range(descrizione).Font.Size = 10 Range(descrizione).Value = Worksheets("CODICI").TextBox1.Value Range(descrizione).Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous 'Range(descrizione).Borders(xlEdgeBottom).Weight = xlHairline Range(gruppo).NumberFormat = "@" Range(gruppo).Value = Worksheets("CODICI").ComboBox2.Value Range(formulaCopy).Select Selection.Copy Range(concatena).PasteSpecial xlPasteFormulas 'Range(concatena).Value = "T0" + KitNrAppoggio + Worksheets("CODICI").ComboBox2.Value Range(disegno).Value = ".dwg" Range(treD).Value = ".asm" Range(distinta).Value = ".xls" Range(immagine).Value = ".jpg" </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T16:16:48.147", "Id": "465296", "Score": "4", "body": "Since you _are_ new to the site, you would be well served to read through the [help] to find out how to ask a good question here. The TL;DR: `<title>` should succinctly state what the code does. `<body>` should tell us about _what_ the code does (any _why_ you've made any unusual choices, if you have). It should also include a _completely functional_ routine (or more than one as necessary). Including what you're looking for in a review (as you've done) is also helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T16:22:18.207", "Id": "465297", "Score": "0", "body": "@FreeMan thank you for answering. So basically I should comment every line of my code and write what it actually do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T16:54:48.050", "Id": "465300", "Score": "5", "body": "No, you should just use the space above an below were you put the code to explain what it does. Also you should make sure that you only post code that works to this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T17:09:51.370", "Id": "465302", "Score": "2", "body": "@ChangeWorld Downvotes are always an indicator you should go (back) to the [help] and check all aspects that make up a _good question_ and you're not failing to be eventually being _off-topic_ at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T17:19:23.117", "Id": "465303", "Score": "0", "body": "Also note that @FreeMan's post isn't considered an _answer_, but a comment, how you should improve your question. Please do so, and explain more detail above your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T17:41:53.390", "Id": "465306", "Score": "4", "body": "@ChangeWorld Please follow K00lman's instructions. It seems I wasn't quite clear enough. You've got to give us something to work with in order to write a review for you. Otherwise, we're left guessing and we could guess wrong. Since a good review can take hours for someone to write up, it's considerate of the asker to give as much info as possible so as to not waste the reviewers time doing the wrong thing." } ]
[ { "body": "<p>The comments I have fall into three categories that relate to general programming practices that would be applicable to any language, not just VBA. </p>\n\n<ol>\n<li>Raw Strings</li>\n<li>Don't Repeat Yourself (DRY) </li>\n<li>Single Responsibility Principle (SRP) </li>\n</ol>\n\n<p><strong>Raw Strings:</strong>\nThere are a lot of raw strings (examples: \"CODICI\", \"Z12\", \"fine\") in the code. I'm guessing that the ease of Copy-Paste made it simple to paste <code>Worksheet(\"CODICI\")</code> in the 10 places where a reference to sheet \"CODICI\" is needed. However, should you ever change the name of this sheet someday (and chances are excellent that you will want to), by then there will be at least 10 places to <em>get wrong</em> - and the compiler/interpreter will not help you find them. By adding a module level variable for the worksheet and assigning it once, you avoid this maintenance issue and reduce the volume of text in your subroutine. There is a performance improvement here as well, but it will not be noticeable - performance is not the motivation for the change. Raw strings like \"CODICI\" are generally to be avoided within your code for the above reasons. Strings that never change for you subroutine are excellent candidates to be declared as module level constants. And, when you want to change the name of the worksheet \"CODICI\", you only need to change your code in a single place (easy to get right!).</p>\n\n<p><strong>DRY:</strong>\nDRY is important from both readability and maintenance of your code. Eliminating repeated blocks of code by writing small, focused, methods to eliminate the repeated code is the typical example of DRY. However, repeatedly writing raw strings or copy-pasting multiple line expressions falls under this principle as well. </p>\n\n<p><strong>SRP:</strong>\nA simple search will provide you a better definition of SRP better than I can/will provide here. As the name implies, SRP encourages that each subroutine, function you write (in VBA or anything else) only does one thing. A good criteria for SRP is this: a subroutine (or function) has a single responsibility if it has only one reason to change. Your code has as single subroutine. Consequently, it contains many reasons to change because it does <em>everything</em>. Some of the reasons to change have been mentioned above within the DRY section. Full disclosure: I regularly fail to achieve SRP my own code, but it is certainly a good principle to aspire to.</p>\n\n<p><code>Sub inserisciAutomatico()</code> is the macro entry point for the code - I would suggest that it's responsibility is to declare constants, initialize the necessary module level variables and call a sequence of operations to accomplish the task. The rewrite provided below does not accomplish this goal completely, but hopefully does so to a degree that is useful as an example.</p>\n\n<p>By consolidating these tasks/responsibilities to smaller, single responsibility methods - you will make your code far easier to understand and maintain. As you have already done, declaring <code>Option Explicit</code> at the top of your module is a good practice. It forces the explicit declaration of all variables used. A good indicator that <code>Sub inserisciAutomatico()</code> is doing 'too much' is the long list of variables it has declared. Creating smaller focused subroutines and functions to accomplish the macro's goal will make many of these disappear. </p>\n\n<p>The rewrite below removes many of raw strings by declaring them as constants. It also reduces the number of local variable declarations needed by calling subroutines focused on the tasks associated with the original variable. It also moves the remaining local variable declarations closer to their usage (generally a good practice). I'll apologize in advance for my lack of any skills in Italian. Some of the subroutines are named a bit strangely. The names were chosen to identify the principle that motivated their creation.</p>\n\n<pre><code>Option Explicit\n\nPrivate Const TheMainWorksheetName As String = \"CODICI\"\nPrivate Const DefaultFont As String = \"Calibri\"\nPrivate Const DefaultFontSize As Long = 10\nPrivate Const Appoggio As String = \"fine\"\nPrivate Const ProvaFormulaRange As String = \"B7:B250\"\nPrivate Const ValoreRange As String = \"D4:D250\"\nPrivate Const DWG As String = \".dwg\"\nPrivate Const ASM As String = \".asm\"\nPrivate Const XLS As String = \".xls\"\nPrivate Const JPG As String = \".jpg\"\nPrivate Const ProvaFormulasAddress As String = \"Z1\"\nPrivate Const PrimoValoreT0 = \"T0\"\n\n'DRY - use a variable (needs a better name) to avoid \n'repeating the expression 'Worksheets(\"CODICI\")'\nPrivate theMainWorksheet As Worksheet\n\nSub inserisciAutomatico()\n\n Application.ScreenUpdating = False\n Application.EnableEvents = False\n\n Set theMainWorksheet = Worksheets(TheMainWorksheetName)\n\n Dim risultati As Range\n Set risultati = theMainWorksheet.Range(ValoreRange)\n\n 'Dim valore As String\n 'ComboBox1 needs a meaningful name to indicate what \n 'value it is providing - for this example, it has been named 'valoreComboBox'\n 'valore = theMainWorksheet .ComboBox1.value\n\n 'Renaming ComboBox1 eliminates variable 'valore' and there is no longer \n 'any uncertainty what is provided by the control\n Dim cell As Range\n Set cell = risultati.Find(theMainWorksheet .valoreComboBox.value)\n\n Dim risultato As Range\n Set risultato = risultati.Find(Appoggio, LookIn:=xlValues, After:=cell)\n\n Dim risultatoAppoggio As Range\n Set risultatoAppoggio = risultati.Find(theMainWorksheet .valoreComboBox.value, LookIn:=xlValues)\n\n Dim kitNrSecondoAppoggio As String\n kitNrSecondoAppoggio = risultatoAppoggio.Offset(-1, -3)\n\n Dim provaFormula As Range\n Set provaFormula = theMainWorksheet.Range(ProvaFormulasAddress)\n provaFormula.FormulaArray = \"=MAX(IF(LEFT(\" &amp; ProvaFormulaRange &amp; \",1)=\"\"\" &amp; kitNrSecondoAppoggio &amp; \"\"\", \" &amp; ProvaFormulaRange &amp; \"))\"\n\n Range(risultato.Address).EntireRow.Insert\n\n\n SRP_SetupPrimoValore risultato.Offset(-1, -3).Address, PrimoValoreT0\n\n 'KitNR was originally declared as a String, so the original KitNr + 1 operation below acted like integer addition\n 'because VBA implicitly converts KitNr to a number. Declare KitNr as an actual number type and eliminate any confusion\n Dim KitNr As Long\n KitNr = CLng(theMainWorksheet.Range(ProvaFormulasAddress).value)\n 'The subrouting wants a string...so explicitly provide it...again to eliminate any confusion\n SRP_SetupNumeroID risultato.Offset(-1, -2).Address, CStr(KitNr + 1)\n\n 'TextBox1 needs a meaningful name to indicate what it is providing\n SRP_SetupDescrizione risultato.Offset(-1, 0).Address, wksht.TextBox1.value\n\n 'ComboBox2 needs a meaningful name to indicate what it is providing\n SRP_SetupGruppo risultato.Offset(-1, 1).Address, wksht.ComboBox2.value\n\n SRP_SetupTheFormula risultato.Offset(-1, 2).Address, risultato.Offset(-2, 2).Address\n\n Range(risultato.Offset(-1, 3).Address).value = DWG\n Range(risultato.Offset(-1, 4).Address).value = ASM\n Range(risultato.Offset(-1, 5).Address).value = XLS\n Range(risultato.Offset(-1, 6).Address).value = JPG\n\nEnd Sub\n\nPrivate Sub SRP_SetupPrimoValore(ByVal addr As String, ByVal value As String)\n Range(addr).value = value\nEnd Sub\n\nPrivate Sub SRP_SetupNumeroID(ByVal addr As String, ByVal kitNrAppoggio As String)\n Range(addr).value = kitNrAppoggio\n DRY_AvoidRepeatingTheFormattingOfNumeroIDAndDescrizione Range(addr)\nEnd Sub\n\nPrivate Sub SRP_SetupDescrizione(ByVal addr As String, ByVal value As String)\n Range(addr).value = value\n DRY_AvoidRepeatingTheFormattingOfNumeroIDAndDescrizione Range(addr)\nEnd Sub\n\nPrivate Sub SRP_SetupGruppo(ByVal addr As String, ByVal comboBox2Value As String)\n Range(addr).value = comboBox2Value\n Range(addr).NumberFormat = \"@\"\nEnd Sub\n\nPrivate Sub SRP_SetupTheFormula(ByVal addr As String, ByVal formulaAddress As String)\n Range(formulaAddress).Select\n Selection.Copy\n Range(addr).PasteSpecial xlPasteFormulas\nEnd Sub\n\nPrivate Sub DRY_AvoidRepeatingTheFormattingOfNumeroIDAndDescrizione(ByRef theCell As Range)\n theCell.Font.Bold = False\n theCell.Font.Name = DefaultFont\n theCell.Font.Size = DefaultFontSize\n theCell.Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous\nEnd Sub\n</code></pre>\n\n<p>The 'raw' numbers within the <code>Offset(...)</code> statements are still a maintence issue waiting to happen. I would consider creating a small ClassModule or UserDefinedType (UDT) to host the rowOffset and columnOffset values. After creating the Class or UDT, create module level variables with names for each Offset pair to identify what the offsets mean (for example, \"risultatoToNumerIDOffset\"). The result is that <code>risultato.Offset(-1, -2)</code> becomes something like <code>risultato.Offset(risultatoToNumerIDOffset.Columns, risultatoToNumerIDOffset.Rows)</code> and the offset values are no longer spread throughout the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T08:49:25.310", "Id": "465684", "Score": "0", "body": "Hello, really sorry for the long response but I just came back to work... I can say that you made a very good answer with all the details possible, and the interesting thing were the little private sub routines, that everyone do a single thing. Really good coding. I like it very much. Hope to learn a lot from it. Besides, I started with a simple code like this one. Now from what you said to me I will try to apply it on the rest of my code! If you prefer I'm going to make another question, when I'm ready so you gonna see the final result :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T06:00:53.500", "Id": "237417", "ParentId": "237302", "Score": "3" } } ]
{ "AcceptedAnswerId": "237417", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T16:08:12.033", "Id": "237302", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "VBA Automatic insert in a Excel Spreadsheet" }
237302
<p>Please review for performance. and also naming convention</p> <p><a href="https://leetcode.com/problems/binary-tree-level-order-traversal/" rel="nofollow noreferrer">https://leetcode.com/problems/binary-tree-level-order-traversal/</a></p> <blockquote> <p>Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).</p> <p>For example:</p> <pre><code>Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] </code></pre> </blockquote> <pre><code>using System.Collections.Generic; using System.Linq; using GraphsQuestions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TreeQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/binary-tree-level-order-traversal/ /// &lt;/summary&gt; [TestClass] public class BinaryTreeLevelOrderTraversalTest { // 3 // / \ // 9 20 // / \ // 15 7 [TestMethod] public void TreeTest() { TreeNode root = new TreeNode(3); root.left = new TreeNode(9); root.right = new TreeNode(20); root.left.left = new TreeNode(15); root.left.right = new TreeNode(7); IList&lt;IList&lt;int&gt;&gt; res = BinaryTreeLevelOrderTraversalClass.LevelOrder(root); CollectionAssert.AreEqual(res[0].ToList(), new List&lt;int&gt;{3}); CollectionAssert.AreEqual(res[1].ToList(), new List&lt;int&gt;{9,20}); CollectionAssert.AreEqual(res[2].ToList(), new List&lt;int&gt;{15,7}); } [TestMethod] public void OneNodeTreeTest() { TreeNode root = new TreeNode(3); IList&lt;IList&lt;int&gt;&gt; res = BinaryTreeLevelOrderTraversalClass.LevelOrder(root); CollectionAssert.AreEqual(res[0].ToList(), new List&lt;int&gt; { 3 }); } } public class BinaryTreeLevelOrderTraversalClass { public static IList&lt;IList&lt;int&gt;&gt; LevelOrder(TreeNode root) { List&lt;IList&lt;int&gt;&gt; res = new List&lt;IList&lt;int&gt;&gt;(); if (root == null) { return res; } Queue&lt;TreeNode&gt; Q = new Queue&lt;TreeNode&gt;(); Q.Enqueue(root); int counter = 0; // which level while (Q.Count &gt; 0) { int children = Q.Count; res.Add(new List&lt;int&gt;()); for (int i = 0; i &lt; children; i++) { var temp = Q.Dequeue(); res[counter].Add(temp.val); if (temp.left != null) { Q.Enqueue(temp.left); } if (temp.right != null) { Q.Enqueue(temp.right); } } counter++; } return res; } } } </code></pre>
[]
[ { "body": "<h3>Avoid unnecessary variables</h3>\n\n<p>The <code>counter</code> variable is unnecessary.\nFor each level, you need just a <code>List&lt;int&gt; level</code>,\nadd the elements of the level to this list,\nand then add this list to <code>res</code>.</p>\n\n<p>By eliminating this variable, you also eliminate any concerns about the correctness of <code>res[counter].Add(temp.val);</code>.\nWith the code changed to <code>level.Add(temp.val)</code>,\nthe mental burden is reduced.</p>\n\n<h3>Use more descriptive names</h3>\n\n<ul>\n<li><code>res</code> could be <code>levels</code></li>\n<li><code>temp</code> could be <code>node</code></li>\n<li><code>LevelOrder</code> could be <code>GetLevels</code></li>\n<li><code>BinaryTreeLevelOrderTraversalClass</code> would be better without <code>Class</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T20:00:50.380", "Id": "237338", "ParentId": "237312", "Score": "1" } } ]
{ "AcceptedAnswerId": "237338", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-14T22:55:05.830", "Id": "237312", "Score": "3", "Tags": [ "c#", "programming-challenge" ], "Title": "LeetCode: Binary Tree Level Order Traversal C#" }
237312
<p><strong>Motivation</strong></p> <p>I want to run some compute heavy tasks on a separate process, so that they don't hog the GIL and I can make effective use of a multi-core machine. </p> <p>Where those tasks are pure functions, I'd just use the provided <code>multiprocessing.Pool</code>. That, however, doesn't work as well for tasks that hold state. I'll assume an example of a process that's doing on-the-fly encryption of data and pumping it to a file. I'd like the keys, the block chaining parameters, and the open file handle (which can't be pickled and passed between processes) to reside as internal state of some <code>EncryptedWriter</code> object. I'd like to be able to use the public interface of that object completley transparently. But I'd like that object to reside on the external process. </p> <hr> <p><strong>Overview</strong></p> <p>To that end, this code creates a decorator <code>@process_wrap_object</code> which wraps a class. The new class will spawn an external process to instantiate an object of the wrapped class. The external process then calls methods on it in the required order, and passes back associated return values. The coordinating object that lives on the original process is responsible for forwarding these functions.</p> <p>The function <code>process_wrap_object</code> is the decorator itself, which takes a class and returns a class. </p> <p>The function <code>_process_wrap_event_loop</code> is the one which the worker process runs, which is tightly coupled to the <code>process_wrap_object</code>.</p> <p>Finally the function <code>_process_disconnection_detector</code> just checks whether the <code>process_wrap_object</code> coordinating object has been destroyed, whether by normal garbage collection or because the main process crashed. In either case, it should signal the worker process to close down cleanly.</p> <hr> <p><strong>Caveats</strong></p> <p>Please note that method calls are blocking, as normal method calls are. This means that on its own, this wrapper will not speed anything up: it just gets the work done elsewhere with more overhead. However, it cooperates effectively with the main process being divvied up with lighter intra-process threading.</p> <hr> <p><strong>Code</strong></p> <pre><code>import inspect from functools import partial from multiprocessing import Process, Queue, Pipe from threading import Thread CLOSE_CODE = "_close" def _process_disconnection_detector(pipe, instruction_queue): """Watcher thread function that triggers the process to close if its partner dies""" try: pipe.recv() except EOFError: instruction_queue.put((CLOSE_CODE, (), {})) def _process_wrap_event_loop(new_cls, instruction_queue, output_queue, pipe, *args, **kwargs): cls = new_cls.__wrapped__ obj = cls(*args, **kwargs) routines = inspect.getmembers(obj, inspect.isroutine) # Inform the partner class what instructions are valid output_queue.put([r[0] for r in routines if not r[0].startswith("_")]) # and record them for the event loop routine_lookup = dict(routines) disconnect_monitor = Thread(target=_process_disconnection_detector, args=(pipe, instruction_queue)) disconnect_monitor.start() while True: instruction, inst_args, inst_kwargs = instruction_queue.get() if instruction == CLOSE_CODE: break inst_op = routine_lookup[instruction] res = inst_op(*inst_args, **inst_kwargs) output_queue.put(res) disconnect_monitor.join() def process_wrap_object(cls): """ Class decorator which exposes the same public method interface as the original class, but the object itself resides and runs on a separate process. """ class NewCls: def __init__(self, *args, **kwargs): self._instruction_queue = Queue() # Queue format is ({method_name}, {args}, {kwargs}) self._output_queue = Queue() # Totally generic queue, will carry the return type of the method self._pipe1, pipe2 = Pipe() # Just a connection to indicate to the worker process when it can close self._process = Process( target=_process_wrap_event_loop, args=([NewCls, self._instruction_queue, self._output_queue, pipe2] + list(args)), kwargs=kwargs ) self._process.start() routine_names = self._output_queue.get() assert CLOSE_CODE not in routine_names, "Cannot wrap class with reserved method name." for r in routine_names: self.__setattr__( r, partial(self.trigger_routine, routine_name=r) ) def trigger_routine(self, *trigger_args, routine_name, **trigger_kwargs): self._instruction_queue.put((routine_name, trigger_args, trigger_kwargs)) return self._output_queue.get() def __del__(self): # When the holding object gets destroyed, # tell the process to shut down. self._pipe1.close() self._process.join() for wa in ('__module__', '__name__', '__qualname__', '__doc__'): setattr(NewCls, wa, getattr(cls, wa)) setattr(NewCls, "__wrapped__", cls) return NewCls </code></pre> <p>Sample usage:</p> <pre><code>@process_wrap_object class Example: """Sample class for demoing stuff""" def __init__(self, a, b): self._a = a self._b = b def inc_a(self): self._a += 1 def inc_b(self, increment=1): self._b += increment def id(self): return f"{self._a} - {self._b} = {self._a - self._b}" proc_obj = Example(8, 6) print(proc_obj.id()) proc_obj.inc_a() proc_obj.inc_a() print(proc_obj.id()) proc_obj.inc_b() print(proc_obj.id()) proc_obj.inc_b(3) print(proc_obj.id()) </code></pre> <hr> <p>I'm after a general review of both high level approach and particular implementation, with particular interest in any subtleties around multiprocessing or correctly wrapping decorators for classes. </p> <p>Any suggestions about additional functionality that would make this decorator markedly more useful are also welcome. One feature I'm considering, but have not yet implemented, is explicit support for <code>__enter__</code> and <code>__exit__</code> to work with <code>with</code> blocks. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T00:47:19.127", "Id": "465337", "Score": "0", "body": "Interesting question, could you fill out the \"sample usage\" so it's like a convoluted \"hello world\" using your class and passing between the threads? It seems like you started to, but `EncryptedWriter` doesn't seem to contain the mutating or printing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T08:24:46.853", "Id": "465354", "Score": "0", "body": "I've changed the example to be runnable (and a bit more hello world like). \n\nThere shouldn't be anything more to do than run it as is: the decorator takes care of working on another process, and using the new object uses the same interface as the old one." } ]
[ { "body": "<p>There are a couple of issues with destructors, firstly is the issue with closing pipes on Linux/Unix <a href=\"https://stackoverflow.com/questions/6564395/why-doesnt-pipe-close-cause-eoferror-during-pipe-recv-in-python-multiproces\">as discussed here</a> (though the pipe is actually no longer necessary once we fix the second issue). Secondly the <code>functools.partial</code> method appears to capture a reference to self which causes the wrapper object to not be destructed when expected, I have fixed this using <code>__getattr__</code> however this has the drawback of allowing the class to respond to any method, perhaps a check in that function that the routine_name is valid would be wise, alternatively if this solution is acceptable the inspect code could all be removed simply calling <code>getattr</code> in <code>_process_wrap_event_loop</code>.</p>\n\n<p>This means we can remove the pipe</p>\n\n<pre><code>import inspect\nfrom multiprocessing import Process, Queue, Pipe\nfrom threading import Thread\n\nCLOSE_CODE = \"_close\"\n\ndef _process_wrap_event_loop(new_cls, instruction_queue, output_queue, *args, **kwargs):\n cls = new_cls.__wrapped__\n obj = cls(*args, **kwargs)\n\n routines = inspect.getmembers(obj, inspect.isroutine)\n # Inform the partner class what instructions are valid\n output_queue.put([r[0] for r in routines if not r[0].startswith(\"_\")])\n # and record them for the event loop\n routine_lookup = dict(routines)\n\n while True:\n instruction, inst_args, inst_kwargs = instruction_queue.get()\n if instruction == CLOSE_CODE:\n break\n inst_op = routine_lookup[instruction]\n res = inst_op(*inst_args, **inst_kwargs)\n output_queue.put(res)\n\ndef process_wrap_object(cls):\n \"\"\"\n Class decorator which exposes the same public method interface as the original class,\n but the object itself resides and runs on a separate process.\n \"\"\"\n class NewCls:\n def __init__(self, *args, **kwargs):\n self._instruction_queue = Queue() # Queue format is ({method_name}, {args}, {kwargs})\n self._output_queue = Queue() # Totally generic queue, will carry the return type of the method\n self._process = Process(\n target=_process_wrap_event_loop,\n args=([NewCls, self._instruction_queue, self._output_queue] + list(args)),\n kwargs=kwargs\n )\n self._process.start()\n\n routine_names = self._output_queue.get()\n\n assert CLOSE_CODE not in routine_names, \"Cannot wrap class with reserved method name.\"\n\n def __getattr__(self, routine_name):\n def f(*trigger_args, **trigger_kwargs):\n self._instruction_queue.put((routine_name, trigger_args, trigger_kwargs))\n return self._output_queue.get()\n return f\n\n def __del__(self):\n # When the holding object gets destroyed,\n # tell the process to shut down.\n self._instruction_queue.put((CLOSE_CODE, (), {}))\n self._process.join()\n\n for wa in ('__module__', '__name__', '__qualname__', '__doc__'):\n setattr(NewCls, wa, getattr(cls, wa))\n setattr(NewCls, \"__wrapped__\", cls)\n\n return NewCls\n</code></pre>\n\n<p>This can be demonstrated with the following example</p>\n\n<pre><code>@process_wrap_object\nclass Example:\n \"\"\"Sample class for demoing stuff\"\"\"\n def __init__(self, a, b):\n self._a = a\n self._b = b\n\n def inc_a(self):\n self._a += 1\n\n def inc_b(self, increment=1):\n self._b += increment\n\n def id(self):\n return f\"{self._a} - {self._b} = {self._a - self._b}\"\n\n def __del__(self):\n print(\"Deleting example\")\n\nproc_obj = Example(8, 6)\nprint(proc_obj.id())\nproc_obj.inc_a()\nproc_obj.inc_a()\nprint(proc_obj.id())\nproc_obj.inc_b()\nprint(proc_obj.id())\nproc_obj.inc_b(3)\nprint(proc_obj.id())\n\ndel proc_obj\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T23:45:19.107", "Id": "465412", "Score": "0", "body": "Thank you. I'll spin up a Linux VM for further work, since I've hitherto been testing exclusively on Windows. \n\nThe problem with `partial` capturing `self` is also a very good spot. I've been looking at using `partialmethod` and have most of a solution. I just want to nail down some of the details around metadata, and in particular making sure that `help` is as helpful as it can be." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T12:56:09.390", "Id": "237324", "ParentId": "237314", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T00:21:32.640", "Id": "237314", "Score": "5", "Tags": [ "python", "python-3.x", "multithreading" ], "Title": "Decorator to instantiate class on another process" }
237314
<p>I am a novice of Python and I am trying to understand how to use OOP paradigm to improve my scripts. My scripts usually read some data from a formatted csv file and perform some numerical analysis. Here is a short example:</p> <pre><code>SIMPLY SUPPORTED BEAM NNODES &lt;NNnodes&gt;&lt;Node,X,Y&gt; 2 1,0,0 2,1,0 </code></pre> <p>This input is for a script for solving a structural analysis problem. Generally one may want to extend the functionalities of the script adding new features, for instance adding elements, materials, section properties and so on.</p> <p>My idea is to set up the code in such way one can include those functionalities in the easiest possible way. </p> <p>My solution is to create a class, and then extend it using inheritance. Here what I wrote so far:</p> <ul> <li>A class for the properties of the problem, named <code>Mesh</code></li> <li>Two initial instance variables storing the name of the input file and the title (first row of the csv file)</li> <li>A method for reading information from the file, named <code>read_input</code></li> </ul> <pre><code>class Mesh() : 'class defining the property of the problem' def __init__(self) : self.name = None self.title = None def read_input(self, input_name) : self.name = input_name with open(self.name) as file : self.title = file.readline() </code></pre> <p>Let's say that one may want to improve the script including the number of nodes (NNODES in the csv file). First I create a class for node, storing ID and coordinates:</p> <pre><code>class Node() : 'class for defining a node' def __init__(self, input1 , input2 , input3) : self.ID = int(input1) self.x = float(input2) self.y = float(input3) </code></pre> <p>Then I add "functionalities" to the class defining a new child class (with the same name of the parent class, because I don't actually need a new child class, just a redefinition of the initial <code>Mesh</code> class ). The new class reads:</p> <ul> <li>New constructor, using super() to include the parent class constructor and new instance variables.</li> <li>Redefinition of the <code>read_input</code> method to include the new lines of the csv file.</li> </ul> <pre><code>class Mesh(Mesh) : 'Mesh that includes nodal loads' def __init__ (self) : super().__init__() self.Nnodes = None self.nodes = list() def read_input(self, input_name) : super().read_input(input_name) with open(self.name) as file : while not file.readline().startswith('NNODES') : continue self.Nnodes = int( file.readline() ) for node in range(0,self.Nnodes) : ID , x, y = file.readline().split(',') self.nodes.append( Node( ID , x, y ) ) </code></pre> <p>Finally, the initialization of the class and the use of the method to read the file:</p> <pre><code>input = Mesh() input.read_input('input_short.txt') </code></pre> <p>Here my doubts: </p> <ul> <li>Is it a good application of the OOP paradigm or I have totally misunderstood the concept?</li> <li>Does it have any sense to call the child class with the same name of the parent class? (I did not find any examples in previous questions)</li> <li>Is it a good way to structure the code? Maybe other people than me will modify the code in future, and I would like to simplifies this procedure as much as possible.</li> </ul> <p>I have always used procedural languages, such as C and FORTRAN, and I don't have any experience in OOP paradigm. </p> <p><strong>EDIT</strong> I modified the code with suggestions from StackOverflow</p> <ol> <li>Modification of the class <code>Mesh</code>, in this way it should be self-contained.</li> <li>Child class name different from the parent one.</li> <li>Use of dataclass for defining the <code>Node</code> class.</li> </ol> <p>Code:</p> <pre><code>from dataclasses import dataclass class Mesh() : 'class defining the property of the problem' def __init__(self , input1) : self.title = input1 name = 'input_short.txt''' with open(name) as file : mesh1 = Mesh( file.readline() ) #let's add a new functionality @dataclass class Node: 'class for defining a node' ID: int x: float y: float class Mesh_nodes(Mesh) : 'Extend Mesh class to account for nodes' def __init__(self , input1, input2, input3) : super().__init__(input1) self.Nnodes = input2 self.nodes = input3 name = 'input_short.txt''' with open(name) as file : while not file.readline().startswith('NNODES') : continue Nnodes = int( file.readline() ) nodes = list() for node in range(0,Nnodes) : ID , x, y = file.readline().split(',') nodes.append( Node( int(ID) , float(x), float(y) ) ) mesh1 = Mesh_nodes(name,Nnodes,nodes) </code></pre> <p>Anyway, my original questions are still valid:</p> <ul> <li><p>Is it a good application of the OOP paradigm or I have totally misunderstood the concept?</p></li> <li><p>Is it a good way to structure the code? Maybe other people than me will modify the code in future, and I would like to simplifies this procedure as much as possible.</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T15:09:17.053", "Id": "465367", "Score": "3", "body": "The edit makes it apparent that the code doesn't work as intended. `SECTIONS` is not handled by the provided code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T15:56:05.210", "Id": "465379", "Score": "1", "body": "\"I am just wondering if this is possible or not.\" Yes, it's possible. The answer isn't `super()`. Get the code working with \"Edit 2\" and then add another object and get it working with that. Once you have it working with 3 objects move them around and see how you can get it to work - you'll notice the `while` ignore loop is a problem." } ]
[ { "body": "<p>Your code can probably utilize OOP.\nHowever, the way you're currently using objects is not what I'd call good.</p>\n\n<p>But before we start adding in complicated objects, it looks like we can do everything you want with a couple of functions:</p>\n\n<ol>\n<li><p>Read the title of the document:</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>self.title = file.readline()\n</code></pre>\n</blockquote></li>\n<li><p>You read until you get to <code>NNODES</code>:</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>while not file.readline().startswith('NNODES') : continue\n</code></pre>\n</blockquote></li>\n<li><p>You read the amount of lines to read:</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>self.Nnodes = int( file.readline() )\n</code></pre>\n</blockquote></li>\n<li><p>You read the CSV:</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>for node in range(0,self.Nnodes) :\n ID , x, y = file.readline().split(',')\n self.nodes.append( Node( ID , x, y ) )\n</code></pre>\n</blockquote></li>\n</ol>\n\n<p>All of 2-4 seems to be related to how you read NNODES objects, so we can just call them in the same function.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def load(file):\n return {\n 'title': file.read_line(),\n 'nnodes': _load_nnode(file),\n }\n\n\n_NNODE_KEYS = ['ID', 'x', 'y']\n\n\ndef _load_nnode(file):\n while not file.readline().startswith('NNODES'):\n continue\n amount = int(file.readline())\n values = []\n for node in range(amount):\n values.append(dict(zip(\n _NNODE_KEYS,\n file.readline().split(',')\n )))\n return values\n\n\nwith open('input_short.txt') as f:\n data = load(f)\n import pprint\n pprint.pprint(data)\n</code></pre>\n\n<pre><code>{\n 'title': 'SIMPLY SUPPORTED BEAM',\n 'nnodes': [\n {'ID': '1', 'x': '0', 'y': '0'},\n {'ID': '2', 'x': '1', 'y': '0'},\n ]\n}\n</code></pre>\n\n<hr>\n\n<p>I can understand how OOP would help here, but your current method isn't great.</p>\n\n<p>Inheritance isn't really going to help here. All you need to do is make your objects have a load method like the above. This load method should be a <code>staticmethod</code> so that it's in charge of instantiating the objects.\nIt seriously just needs to be that simple.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Mesh:\n title: str\n nnode: NNode\n\n @classmethod\n def load(cls, file):\n return cls(\n file.readline(),\n NNode.load(file),\n )\n\n\n@dataclass\nclass NNode:\n nodes: List[dict]\n\n @classmethod\n def load(cls, file):\n while not file.readline().startswith('NNODES'):\n continue\n amount = int(file.readline())\n values = []\n for node in range(amount):\n values.append(dict(zip(\n _NNODE_KEYS,\n file.readline().split(',')\n )))\n return cls(values)\n</code></pre>\n\n<hr>\n\n<p>Now this could be a cool little file reader project you have. But the thing is, that you've not really implemented much.</p>\n\n<ol>\n<li>You ignore vital data with a <code>while</code> ignore loop.</li>\n<li>You ignore what the data should look like, you don't parse <code>NNODES &lt;NNnodes&gt;&lt;Node,X,Y&gt;</code>.</li>\n<li>You assume everything is the exact same format, you haven't implemented a way to allow different classes.</li>\n</ol>\n\n<p>Overall I'm not going to write these things for you. I suggest you try your arm at them with the above code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T15:06:49.267", "Id": "465365", "Score": "0", "body": "Your code for sure is better than mine, but that's not exactly what i'm looking for. I made a small edit to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T15:08:22.913", "Id": "465366", "Score": "0", "body": "@Stefano As addressed at the bottom of my answer, you have not written that and so I'm not going to create something you can't be arsed to implement yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T15:20:43.817", "Id": "465368", "Score": "0", "body": "Of course you are right, but I don't want you to write the code for me. Probably my edit 2 is bad written" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T15:28:24.873", "Id": "465372", "Score": "0", "body": "@Stefano \"but I don't know how to start to find a solution.\" shows the code not working as you intend, and all you're asking is \"give me a solution to my problem\". That is off-topic here, as your code should be working the way you intend it to; it's clear it's not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T15:49:26.833", "Id": "465377", "Score": "0", "body": "The problem is that I don't really know where to find something. I looked at previous questions, I looked in the manuals, I looked at some guides on internet. I'll try to make a code that does not work as I would like" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T13:46:49.210", "Id": "237325", "ParentId": "237322", "Score": "4" } } ]
{ "AcceptedAnswerId": "237325", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T11:47:41.250", "Id": "237322", "Score": "1", "Tags": [ "python", "object-oriented", "inheritance" ], "Title": "OOP paradigm in python - Extend class functionalities" }
237322
<p>Here is my very first code which fetch data and add it to MySql. Please review my code and let me know if I'm on the right path. Is there anything I can improve? </p> <p>postsData class = fetch and add data blog posts</p> <p>categoriesData class = fetch and add data for categories of my blog. Ex: bmw, nissan, opel, ford, etc</p> <p>connect.php</p> <pre><code>class dbh{ private $host = "localhost"; private $user = "root"; private $pwd = ""; private $dbname = "test_blog"; public $conn; public function __construct() { $this-&gt;conn = $this-&gt;connect(); } private function connect() { $dsn = 'mysql:host=' . $this-&gt;host . ';dbname=' . $this-&gt;dbname; $pdo = new PDO ($dsn, $this-&gt;user, $this-&gt;pwd); $pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo-&gt;setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $pdo-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); return $pdo; } } </code></pre> <p>func.class.php</p> <pre><code> class postsData extends dbh{ public function getPosts() { $sql = "SELECT * FROM posts_tbl"; $stmt = $this-&gt;conn-&gt;prepare($sql); $stmt-&gt;execute(); $result = $stmt-&gt;fetchAll((PDO::FETCH_OBJ)); return $result; } public function addPost($filter_author, $filter_title, $filter_txt) { $sql = "INSERT INTO posts_tbl (post_author, post_title, post_txt) VALUES (?, ?, ?)"; $stmt = $this-&gt;conn-&gt;prepare($sql); $stmt-&gt;execute([$filter_author, $filter_title, $filter_txt]); } } class categoriesData extends dbh{ public function getCategories () { $sql = "SELECT * FROM categories_tbl"; $stmt = $this-&gt;conn-&gt;prepare($sql); $stmt-&gt;execute(); $result = $stmt-&gt;fetchAll((PDO::FETCH_OBJ)); return $result; } public function adCategory ($filter_name, $filter_slug) { $sql = "INSERT INTO categories_tbl (category_name, category_slug) VALUES (?, ?)"; $stmt = $this-&gt;conn-&gt;prepare($sql); $stmt-&gt;execute([$filter_name, $filter_slug]); } } //test $post = new PostsData(); $posts = $post-&gt;getPosts(); foreach ($posts as $post) { echo $post-&gt;post_title . '&lt;br&gt;'; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T15:22:08.250", "Id": "465369", "Score": "3", "body": "Could you please explain a little more about what the code does? What kind of categories is it posting to the database?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T15:27:28.707", "Id": "465371", "Score": "0", "body": "Blog categories - category 1 : bmw, category 2: nissan etc" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T15:29:14.210", "Id": "465373", "Score": "0", "body": "Please add the category explanation to the question. Right now there are 2 votes to close your question due to lack of details." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T09:00:23.543", "Id": "465527", "Score": "0", "body": "I have recently posted a review on a very similar question. It could be of help to you as well. https://codereview.stackexchange.com/a/237237/212100 And actually this one too https://codereview.stackexchange.com/a/237288/212100 It's incredible how you both even extend a `dbh` class. Where are you getting this idea? Does it come from some tutorial?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T09:31:13.600", "Id": "465533", "Score": "2", "body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T13:20:50.710", "Id": "465561", "Score": "0", "body": "One suggestion I'll make is if you think you might need to call the same statement multiple times in the same page/script(particularly your addPost and addCategory methods) it's worth keeping your statements around as properties on the class so you can use them again later rather than always doing a round trip to the DB to prepare the statement for each post/category you add.\n`$this->addPostStatement = $this->addPostStatement ?? $this->conn->prepare($sql);` for example." } ]
[ { "body": "<p>Your code is mostly all right, especially given it's your first code attempt. </p>\n\n<p>I would say there is only on critical flaw. A post or a category is not a <em>database connection</em>. Hence it should be never extended from it. It would be like if you extend a <em>human</em> from a <em>car</em> simply because a human is going to ride a car. A car is a service used by a human, that needs to be injected into a human object. </p>\n\n<p>Besides, the way your code is written, it will create a new connection to the database in the every class instance. Which will result in the \"Too many connections\" error. </p>\n\n<p>To sum it up: </p>\n\n<ul>\n<li>a database connection has to be made only <strong>once</strong>. and then passed as a parameter to all your classes that need it. </li>\n<li>your dbh class is rather useless. it does't add anything to original PDO. so you can get rid of it and simply create a plain PHP file with connection code and include it in your scripts</li>\n<li>then you have to rewrite your data classes adding a constructor, providing either vanilla PDO or your own database connection class' instance as a parameter</li>\n</ul>\n\n<p>something like this</p>\n\n<pre><code>class categoriesData {\n protected $conn;\n public function __construct($conn) {\n $this-&gt;conn = $conn;\n }\n ...\n</code></pre>\n\n<p>and then use it like this</p>\n\n<pre><code>require_once 'pdo.php';\n$post = new PostsData($pdo);\n$posts = $post-&gt;getPosts();\n\nforeach ($posts as $post) { \n echo $post-&gt;post_title . '&lt;br&gt;';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T11:38:30.607", "Id": "237433", "ParentId": "237327", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T14:38:17.577", "Id": "237327", "Score": "0", "Tags": [ "php", "mysql" ], "Title": "Fetch and add data to MySql" }
237327
<p>I have 2 maps. First map consists of order in which a specific set of services is executed. Second map contains execution time each service took. I need to display this information. Following is my piece of code. How can this be improved by performance and syntax?</p> <pre><code>public static String getAllExecTimes(MasterVO masterVO, boolean displayAll) { StringBuilder builder = new StringBuilder(); Map&lt;Integer, DurationVo&gt; durationMap = null; Map&lt;Integer, Integer&gt; orderMap = null; List&lt;Integer&gt; keys = null; if (displayAll) { builder.append("\nSection A\n"); durationMap = masterVO.getMapA(); orderMap = masterVO.getOrderMap(); keys = new ArrayList&lt;&gt;(orderMap.keySet()); keys.sort(new CustomComparator()); for (Integer execOrder : keys) { Integer target = orderMap.get(execOrder); if (null != target) { builder.append(durationMap.get(target)); } } if (null != masterVO.getMapB()) { builder.append("\nSection B\n"); durationMap = masterVO.getMapB(); keys = new ArrayList&lt;&gt;(durationMap.keySet()); for (Integer target : keys) { builder.append(durationMap.get(target)); } } } durationMap = masterVO.getMapC(); keys = new ArrayList&lt;&gt;(durationMap.keySet()); keys.sort(new CustomComparator()); builder.append("\nFinal Section\n"); for (Integer target : keys) { builder.append(durationMap.get(target)); } return builder.toString(); } private static final class CustomComparator implements Comparator&lt;Integer&gt; { public int compare(Integer first, Integer second) { return first.compareTo(second); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T20:59:08.713", "Id": "465393", "Score": "1", "body": "To prevent downvotes in the future, you should present code that is complete and compilable. Yours is missing the `MasterVO` and `DurationVo` classes. It is also missing some test code that demonstrates how `getAllExecTimes` is used. It is also missing some example data to show what exactly you expect from the code." } ]
[ { "body": "<p>Code review in order of appearance:</p>\n\n<pre><code>public static String getAllExecTimes(MasterVO masterVO, boolean displayAll) {\n</code></pre>\n\n<p>Static methods should be avoided if you may expect them to contain state, such as hints on how to format the class. Why not create an object that performs the formatting?</p>\n\n<p>Boolean parameters are not a good idea. They are pretty unreadable. But in this case it is worse, as the <code>displayAll</code> doesn't give any hint to a user what actually <strong>is</strong> displayed. What about an enum, e.g. <code>enum Display {DISPLAY_MAP_C_ONLY, DISPLAY_MAPS_A_B_C;}</code>? </p>\n\n<pre><code>Map&lt;Integer, DurationVo&gt; durationMap = null;\nMap&lt;Integer, Integer&gt; orderMap = null;\nList&lt;Integer&gt; keys = null;\n</code></pre>\n\n<p>Never ever instantiate variables before they are needed in Java, and don't use the same variable reference for two different maps (A and C). This makes for very error prone code, especially if you are starting to assign <code>null</code> to the variables, which should almost <strong>never</strong> be necessary. <strong>Create separate methods</strong> when code is very similar or when variable names are starting to clash.</p>\n\n<p>Why is there a <code>MasterVO</code> and a <code>DurationVo</code>? It's fine to choose all uppercase or camelcase, but please do so <strong>consistently</strong>.</p>\n\n<pre><code>durationMap = masterVO.getMapA();\norderMap = masterVO.getOrderMap();\n</code></pre>\n\n<p>You know, a map is a mapping from a set of keys to values. However, you only have duration and order, and it isn't even clear which one is key and what is the value.</p>\n\n<pre><code>keys = new ArrayList&lt;&gt;(orderMap.keySet());\nkeys.sort(new CustomComparator());\n</code></pre>\n\n<p>Now this is just not right. If you put the keys into a <code>TreeSet</code> instead then they will be ordered during insertion. Even better, why not use a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html\" rel=\"nofollow noreferrer\"><code>TreeMap</code></a> and sort then when you setup the <code>Map</code>?</p>\n\n<pre><code>if (null != target) {\n</code></pre>\n\n<p>First of all, you should just write this as <code>if (target != null) {</code>; this is a well known anti-pattern for Java, it's just not needed and it hurts readability. It is item #1: \"Yoda Conditions\" for the \"new jargon\" article <a href=\"https://blog.codinghorror.com/new-programming-jargon/\" rel=\"nofollow noreferrer\">at coding horror</a>.</p>\n\n<p>The bigger question is why you would allow <code>null</code> values in such a map in the first place. Even without knowing the design, I have the feeling that <code>null</code> values should be avoidable in this case, especially since keys without values are simply skipped in the resulting string.</p>\n\n<pre><code>if (null != masterVO.getMapB()) {\n</code></pre>\n\n<p>Now whole maps seem to be missing in action. Use <code>Optional&lt;...Map&gt;</code> instead.</p>\n\n<pre><code>private static final class CustomComparator implements Comparator&lt;Integer&gt; {\n\n public int compare(Integer first, Integer second) {\n return first.compareTo(second);\n }\n}\n</code></pre>\n\n<p>Seriously, how does this custom comparator differ from normal integer ordering? Do you <em>need</em> to specify a specific comparator in that case? And why is it called <code>CustomComperator</code>? That name doesn't explain <strong>how</strong> it is custom.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T20:56:26.203", "Id": "465391", "Score": "0", "body": "I disagree that all static methods are bad. They are quite useful in many cases. — Regarding the `CustomComparator`: maybe Tishy Tash just didn't know that `Comparator.naturalOrdering()` exists." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T20:58:12.430", "Id": "465392", "Score": "0", "body": "I've not said that all static methods are bad, but I'll explain it better. It will already use that ordering if you don't specify a specific comparator - included that in the explanation too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T16:59:55.680", "Id": "237333", "ParentId": "237332", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T16:15:20.243", "Id": "237332", "Score": "0", "Tags": [ "java", "stream" ], "Title": "Compare two map objects and show relative information Java 8" }
237332
<p>In Java, I use a <a href="https://github.com/ben-manes/caffeine/wiki/Population#loading" rel="nofollow noreferrer"><code>LoadingCache</code></a> which offers <a href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/2.2.0/com/github/benmanes/caffeine/cache/Caffeine.html#weakKeys--" rel="nofollow noreferrer">weakKeys</a> and I need something similar in Typescript, so I wrote the following:</p> <pre><code>function loadingWeakCache&lt;K extends object, V&gt;(loader: (k: K) =&gt; V) : ((k: K) =&gt; V) { const cache = new WeakMap&lt;K, V&gt;(); return function(k: K) : V { let v = cache.get(k); if (v !== undefined) return v; v = loader(k); cache.set(k, v); return v; }; } </code></pre> <p>It seems to work and I'd like it to be reviewed<sup>*</sup></p> <p>Unfortunately, I need to cache a two-argument function. My first attempt was </p> <pre><code>function pairLoadingWeakCache&lt;K1 extends object, K2 extends object, V&gt;(loader: (k1: K1, k2: K2) =&gt; V) : (k1: K1, k2: K2) =&gt; V { const cache = new WeakMap&lt;K1, (k2: K2) =&gt; V&gt;(); return function(k1: K1, k2: K2) : V { let second = cache.get(k1); if (second !== undefined) return second(k2); const v = loader(k1, k2); second = loadingWeakCache(k =&gt; loader(k1, k)); cache.set(k1, second); return second(k2); }; } </code></pre> <p>which was wrong as it prevented collecting the second key because of it being referenced from the closure. I'm only presenting it here as it's a smart but broken idea someone could propose. I rewrote it as</p> <pre><code>function pairLoadingWeakCache&lt;K1 extends object, K2 extends object, V&gt;(loader: (k1: K1, k2: K2) =&gt; V) : (k1: K1, k2: K2) =&gt; V { const cache = new WeakMap&lt;K1, WeakMap&lt;K2, V&gt;&gt;(); return function(k1: K1, k2: K2) : V { let second = cache.get(k1); if (second === undefined) { second = new WeakMap(); cache.set(k1, second); } else { const v = second.get(k2); if (v !== undefined) return v; } const v = loader(k1, k2); second.set(k2, v); return v; }; } </code></pre> <p>and I'd like it to be reviewed<sup>*</sup> as well.</p> <hr> <p><sup>*</sup> <sub>Just please ignore my single-line conditionals as it's my strongly preferred way.</sub></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T17:38:57.397", "Id": "237334", "Score": "2", "Tags": [ "typescript", "cache", "weak-references" ], "Title": "Loading weak cache in typescript" }
237334
<p>My goal is to get a list of related <strong>statementIds</strong> in order of most repeated.</p> <p>In my database I have stems(Words):</p> <pre><code>+---------+-----------------+ | Stem | StatementId | +---------+-----------------+ | Hello | [2,46,62] | | Good | [1,123,45] | | Morning | [23,2436,12312] | +---------+-----------------+ </code></pre> <p>My steps:</p> <ol> <li>Get all <strong>statementIds</strong> <code> [6, 86],[6],[4],[3, 86],[...]</code> </li> <li><p>Create an empty object, and everytime i see a number,increase its value (or set to 1 if it hasen't been seen before) <code>  {2: 1, 3: 4, 4: 1, 6: 11, 85: 1, 86: 5, 87: 1, 89: 1} </code></p></li> <li><p>Sort the object by the attribute and put it in an array of relevancy. <code>  ["6", "86", "3", "89", "87", "85", "4", "2"] </code></p></li> </ol> <p>Full code:</p> <pre class="lang-js prettyprint-override"><code>getAllStatementIdFromStem = async (stems: string[]) =&gt; { const ids: { [key: number]: number } = {}; await this.getBulkStem(stems).toArray((stems: Stem[]) =&gt; stems.map(({ statements }) =&gt; statements.forEach((statementId: number) =&gt; { typeof ids[statementId] === "undefined" ? (ids[statementId] = 1) : ids[statementId]++; }) ) ); return Object.entries(ids) .sort((a, b) =&gt; a[1] - b[1]) .reverse() .map(x =&gt; x[0]); }; </code></pre> <p>Could I be doing something more effectively? I feel like I am doing way too many extra steps.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T00:25:49.683", "Id": "465807", "Score": "0", "body": "Couple of questions: are statement IDs and sentence IDs the same? Can you provide an end to end example, e.g. for X input you should get Y output. Means that I can step through the code on my end, using your input, and see if any steps can be optimised." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T12:38:48.817", "Id": "466028", "Score": "0", "body": "Updated the names.\ninput = [ [1], [65, 85, 86, 87, 88, 89], [2], [1, 2]]\noutput = [1, 2, 89, 88, 87, 86, 85, 65]" } ]
[ { "body": "<p>Overall looks good. I think following improvements can be suggested.</p>\n\n<p>1.Instead of this</p>\n\n<pre><code>typeof ids[statementId] === \"undefined\"\n ? (ids[statementId] = 1)\n : ids[statementId]++;\n</code></pre>\n\n<p>How about this for more readability</p>\n\n<pre><code>ids[statementId] = (ids[statementId] || 0) + 1;\n</code></pre>\n\n<p>2.Instead of doing <code>sort</code> and immediately <code>reverse</code>. You can change sort function (with descending order) so that you can avoid <code>reverse</code> call.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T04:54:50.640", "Id": "237602", "ParentId": "237337", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T19:01:58.170", "Id": "237337", "Score": "3", "Tags": [ "javascript", "performance", "complexity", "typescript" ], "Title": "Finding Common Items in arrays" }
237337
<p>How would you in a pythonic manner write a function that returns the common substring found at the beginning of a set of strings? This is my ugly attempt:</p> <pre><code>def common_start(s): l = len(s) if l == 0: return None elif l == 1: return next(iter(s)) else: i = iter(s) start = next(i) while start != "": if all(ii.startswith(start) for ii in i): return start else: i = iter(s) start = start[:-1] next(i) # were comparing againt the first item, so we don't need it else: return "" s = set(("abc1","abcd","abc","abc abc")) common_start(s) # "abc" s = set(("ab","abcd","abc","abc abc")) common_start(s) # "ab" s = set(("ab",)) common_start(s) # "ab" s = set(("","abcd","abc","abc abc")) common_start(s) # "" s = set() common_start(s) # None </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T07:56:04.047", "Id": "465843", "Score": "0", "body": "Is there a reason why you want `common_start({}) == None` instead of `\"\"`?" } ]
[ { "body": "<p>You should read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> and get a linter; <a href=\"https://pypi.org/project/pycodestyle/\" rel=\"nofollow noreferrer\">pycodestyle</a>, <a href=\"https://pypi.org/project/pylint/\" rel=\"nofollow noreferrer\">pylint</a>, <a href=\"https://pypi.org/project/flake8/\" rel=\"nofollow noreferrer\">flake8</a>, <a href=\"https://pypi.org/project/prospector/\" rel=\"nofollow noreferrer\">prospector</a>, <a href=\"https://pypi.org/project/coala/\" rel=\"nofollow noreferrer\">coala</a>. It doesn't matter which one, just get one and use it.</p>\n\n<ul>\n<li>Indenting with 3 spaces is awful, no-one can easily interact with your code.<br>\nI've never in my life seen 3 spaces for indentation, it makes me think your post is a joke.</li>\n<li>Variables like <code>s</code>, <code>l</code> and <code>ii</code> are useless.</li>\n<li><p>It's really bad to put statements on the same line as other statements.</p>\n\n<blockquote>\n <pre class=\"lang-py prettyprint-override\"><code>if l == 0: return None\n</code></pre>\n</blockquote>\n\n<p>The amount of times I've just not seen the <code>return None</code> with lines like this isn't funny. It's nearly 100%.</p></li>\n</ul>\n\n<hr>\n\n<ul>\n<li>Change your <code>if</code>, <code>elif</code>, <code>else</code> to guard statements and you can dedent your code.</li>\n<li>There's no need for <code>while</code> <code>else</code>, you've not broken from the loop.</li>\n<li>Returning <code>None</code> is just odd at best, change it to an empty string.</li>\n<li>Taking a set as input is really strange, it causes you to have to do <code>next(iter(s))</code>. And you're not even exploiting the benefits of it.</li>\n<li><p>Using iterators is clever, but not smart. You can just make a new list to contain all but the first value.</p>\n\n<p>Additionally it doesn't really matter if you check against the first value because it's always going to be a subset of itself. Just seems like adding complexity for the sake of complexity.</p></li>\n<li><p>You can remove the <code>if l == 1</code> check.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def common_start(values):\n if len(values) != 0:\n start = values[0]\n while start:\n if all(value.startswith(start) for value in values):\n return start\n start = start[:-1]\n return \"\"\n</code></pre>\n\n<hr>\n\n<p>However this isn't the best. If there are <span class=\"math-container\">\\$s\\$</span> values, and each have a length <span class=\"math-container\">\\$l\\$</span> then your code runs in <span class=\"math-container\">\\$O(sl^2)\\$</span> time.</p>\n\n<p>Instead I'd suggest checking the first value against everything once - running in <span class=\"math-container\">\\$s\\$</span> time. Since you do this <span class=\"math-container\">\\$l\\$</span> times it runs in <span class=\"math-container\">\\$O(sl)\\$</span> time.</p>\n\n<p>To do so you can use <code>zip</code> to iterate through all the first characters, then second characters at the same time. From this you can check if they are the same and append them to a temporary list. Finally you return the contents of the list converted to one single string. In the end you would end up with something like <a href=\"https://codereview.stackexchange.com/users/43117/salparadise\">salparadise</a> <a href=\"https://codereview.stackexchange.com/a/237341\">created</a>.</p>\n\n<p>Again I would still make an empty list or set as input return an empty string.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def common(values):\n start = []\n for characters in zip(*values):\n if len(set(characters)) != 1:\n break\n start.append(characters[0])\n return ''.join(start)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T21:32:25.103", "Id": "465399", "Score": "0", "body": "good stuff. +1, I think you raise the bar on how to craft an answer. I will keep mine deleted :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T21:34:52.557", "Id": "465400", "Score": "0", "body": "@salparadise Oh no, I feel like a bully!!! ‎" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T21:52:27.640", "Id": "465403", "Score": "0", "body": "@AJNeufeld FWIW [bar](https://dictionary.cambridge.org/dictionary/english/bar) was not a typo, I was using it's preposition meaning. I'll leave it so it's easier to understand tho :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T21:56:01.967", "Id": "465404", "Score": "0", "body": "@Peilonrayz My bad. I read it and found it jarring -- figured it was a typo, but I can see how it actually makes sense with \"bar\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T19:23:53.967", "Id": "465929", "Score": "0", "body": "Peilonrayz Can you please give an example of a guard statement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T21:06:57.990", "Id": "465950", "Score": "1", "body": "@Baz the quoted `if` would be a guard statement if the `elif` after it were an `if` and the `else` didn't exist. In short if you return in the body of an if just don't use else or elif." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T21:22:52.660", "Id": "237342", "ParentId": "237340", "Score": "10" } }, { "body": "<p>Your usage of <code>iter()</code> and <code>next()</code> is unnecessarily confusing. This comes from the requirement of using a <code>set</code> as an input, where sets are not indexable.</p>\n\n<p>If you passed in a list, then instead of this:</p>\n\n<pre><code> elif l == 1: return next(iter(s))\n</code></pre>\n\n<p>you could write:</p>\n\n<pre><code> elif l == 1: return s[0]\n</code></pre>\n\n<p>which is much clearer. It gets even clearer when you remove the iterator from the <code>all( ... for ii in i)</code>, which necessitates using <code>i = iter(s); next(i)</code> to reset the iterator. Here is the updated code:</p>\n\n<pre><code>def common_start(*s):\n l = len(s)\n if l == 0:\n return None\n elif l == 1:\n return s[0]\n\n start = s[0]\n while start != \"\" and not all(ii.startswith(start) for ii in s[1:]):\n start = start[:-1]\n\n return start\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>&gt;&gt;&gt; s = { \"abc1\", \"abcd\", \"abc\", \"abc abc\" }\n&gt;&gt;&gt; common_start(*s)\n'abc'\n</code></pre>\n\n<p>The <code>*s</code> explodes the set into a list of arguments.</p>\n\n<hr>\n\n<h1>Reduce</h1>\n\n<p>What is the common prefix among N strings? It would be the same as taking the common prefix of the first two strings, and using that compute the common prefix with the third string, and so on, until you reach the last string.</p>\n\n<pre><code>common_start({a, b, c, d}) == common_prefix(common_prefix(common_prefix(a, b), c), d)\n</code></pre>\n\n<p>Which leads us to <a href=\"https://docs.python.org/3/library/functools.html?highlight=reduce#functools.reduce\" rel=\"noreferrer\"><code>functools.reduce()</code></a>.</p>\n\n<pre><code>from functools import reduce\n\ndef common_start(s):\n if s:\n return reduce(common_prefix, s)\n\n return None\n</code></pre>\n\n<p>Now, we just need a function to return the common prefix of two strings.</p>\n\n<p>As an example, this works, although is a bit cryptic. You might be able to come up with a simpler, possibly faster method:</p>\n\n<pre><code>from itertools import takewhile\n\ndef common_prefix(a, b):\n return a[:len(list(takewhile((lambda z: z[0] == z[1]), zip(a, b))))]\n</code></pre>\n\n<hr>\n\n<h1>os.path</h1>\n\n<p>Surprisingly, Python comes with <a href=\"https://docs.python.org/3/library/os.path.html#os.path.commonprefix\" rel=\"noreferrer\">the required function built-in to the <code>os.path</code> module</a>. Just need to convert the <code>set</code> to a <code>list</code>, and handle the empty set to <code>None</code> special case:</p>\n\n<pre><code>import os\n\ndef common_start(s):\n if s:\n return os.path.commonprefix(list(s))\n\n return None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T22:00:46.740", "Id": "465405", "Score": "0", "body": "Nice answer. Smart use of `reduce`. But I'd personally not pass `common_prefix` as a PR." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T22:11:04.697", "Id": "465406", "Score": "0", "body": "@Peilonrayz PR?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T22:12:18.020", "Id": "465408", "Score": "0", "body": "Pull request :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T22:13:56.233", "Id": "465409", "Score": "0", "body": "Also that `os.path` solution is amazing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T22:18:03.823", "Id": "465410", "Score": "0", "body": "@Peilonrayz Ah yes. It was one part showing off with a one-line solution, and one part ensuring it didn't get used as someone's homework solution. I haven't done any performance testing on it; it may be fast, it may be slow. It would require a hell of a justification for me to accept it as a PR too. ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T11:45:09.863", "Id": "465438", "Score": "0", "body": "Congrats on the gold Python tag" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T15:22:00.293", "Id": "465449", "Score": "0", "body": "@Peilonrayz Thanks!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T21:41:50.490", "Id": "237344", "ParentId": "237340", "Score": "9" } }, { "body": "<p>I would personally prefer that (1) you <em>yield</em> elements one by one, and (2) that you use the built-in functions as much as possible. Python comes with the <a href=\"https://docs.python.org/3.3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip</code></a> function that allows you to iterate over elements with the same index. That is, <code>zip(* ['ab', 'xyz'])</code> will yield <code>('a', 'x')</code> and then <code>('b', 'y')</code>. Notice that it only yields elements up to the shortest string has been exhausted, hence the bounds are dealt with automatically. Notice also that since <code>zip(* ['ab', 'abc', 'abx'])</code> yields <code>('a', 'a', 'a')</code> and <code>('b', 'b', 'b')</code>, you can use <code>len(set(elt)) == 1</code> to verify that the characters are all the same.</p>\n\n<p>Depending on how you want to use the function, I would perhaps <em>yield</em> elements, and perhaps make a <em>wrapper function</em> to turn the result into a string.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def _common_prefix(seq):\n \"\"\"A generator that yields common elements of a sequence of sequences.\"\"\"\n for e in zip(*seq):\n if len(set(e)) != 1:\n break\n yield e[0]\n\n\ndef common_prefix(seq):\n \"\"\"Compute the common prefix of a sequence of sequence\"\"\"\n return \"\".join(_common_prefix(seq))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T12:28:48.923", "Id": "237372", "ParentId": "237340", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T20:27:39.227", "Id": "237340", "Score": "9", "Tags": [ "python" ], "Title": "Find common substring that starts a set of strings" }
237340
<p>I was working to upgrade some code to C# 8.0 and came across an interesting pattern with default parameters and non-nullable reference types. I'm working if it's clear enough to the caller.</p> <p>Given this pre C# 8.0 code,</p> <pre><code>Task FooAsync( Bar bar = null, CancellationToken ct = default) { bar = bar ?? new Bar(); // some sensible default } </code></pre> <p>the <code>bar</code> parameter is flagged as one to potentially make nullable (<code>Bar? bar = null</code>). This would indicate to the caller that they can pass <code>null</code>.</p> <p>However, if I want to encourage the caller not to pass <code>null</code> for the parameter, I could do something like this in C# 8.0:</p> <pre><code>Task FooAsync( Bar bar = null!, CancellationToken ct = default) { bar ?? = new Bar(); // some sensible default } </code></pre> <p>Is this a sensible approach to avoid passing <code>null</code> into the parameter? I know the caller can still do: <code>FooAsync(bar: null!)</code> but that obviously sticks out.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T21:25:03.540", "Id": "465397", "Score": "0", "body": "could someone with high enough rep please create [c#-8.x] and [nullable-reference-types]?" } ]
[ { "body": "<p>My take on this is that the function signature should not lie.\nSo if it can handle a null passed in, as it can, it should use </p>\n\n<pre><code>Bar? bar = null\n</code></pre>\n\n<p>Another approach could be to overload the function with another which only takes a single parameter. Something like ...</p>\n\n<pre><code>Task FooAsync(\n Bar bar,\n CancellationToken ct = default)\n{\n ...\n}\n\nTask FooAsync(\n CancellationToken ct = default)\n{\n return FooAsync(new Bar(), ct);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T22:01:00.690", "Id": "237345", "ParentId": "237343", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T21:24:34.543", "Id": "237343", "Score": "3", "Tags": [ "c#", "null" ], "Title": "Non-nullable reference type default parameters in C# 8" }
237343
<p>Here is a custom <code>Random&lt;T&gt;</code> class which could be used as:</p> <pre><code>Random&lt;int&gt; random = Random&lt;int&gt;(10); int zeroToTen = random.Next(); </code></pre> <p>I also made it seedable through the ambient context, so the following is observed allowing to potentially have <code>Seed</code> anywhere above in the call stack to simplify unit testing:</p> <pre><code>Random&lt;int&gt; Numbers { get; } = new Random&lt;int&gt;(10); [TestMethod] public void Seed_With_Seed_Value() { int[] a, b; using (new Seed("Numbers", 33)) a = new[] { Numbers.Next(), Numbers.Next(), Numbers.Next(), Numbers.Next() }; using (new Seed("Numbers", 33)) b = new[] { Numbers.Next(), Numbers.Next(), Numbers.Next(), Numbers.Next() }; CollectionAssert.AreEqual( a, b); } [TestMethod] public void Seed_With_Sequence() { using (new Seed("Numbers") { 1, 2, 3 }) { Assert.AreEqual(1, Numbers.Next()); Assert.AreEqual(2, Numbers.Next()); Assert.AreEqual(3, Numbers.Next()); } } </code></pre> <p>where library code is:</p> <pre><code>public class Random&lt;T&gt; { public Random(T max, [CallerMemberName] string name = null) { Max = max; Name = name; } T Max { get; } string Name { get; } public T Next() =&gt; (T)Convert.ChangeType( Seed.Of(Name).Next(Convert.ToDouble(Max)), typeof(T)); } </code></pre> <p>and:</p> <pre><code>public class Seed : IEnumerable, IDisposable { static AsyncLocal&lt;Seed&gt; Context { get; } = new AsyncLocal&lt;Seed&gt;(); static Seed Default { get; } = new Seed(); public static Seed Of(string name) { for (var c = Context.Value; c != null; c = c.Parent) if (c.Name == name) return c; return Default; } Seed() { Value = null; Sequence = new ConcurrentQueue&lt;double&gt;(); Random = new Random(); } public Seed(string name, int? value = null) { Name = name; Value = value; Parent = Context.Value; Context.Value = this; Sequence = new ConcurrentQueue&lt;double&gt;(); Random = value == null ? new Random() : new Random(value.Value); } public void Dispose() =&gt; Context.Value = Parent; Seed Parent { get; } string Name { get; } int? Value { get; } ConcurrentQueue&lt;double&gt; Sequence { get; } Random Random { get; } public void Add(double next) =&gt; Sequence.Enqueue(next); public double Next(double max) =&gt; Sequence.TryDequeue(out var value) ? value : Random.NextDouble() * max; public IEnumerator GetEnumerator() =&gt; Sequence.GetEnumerator(); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T22:33:48.700", "Id": "237347", "Score": "2", "Tags": [ "c#" ], "Title": "Testable random number generator" }
237347
<p>Here is my solution to <a href="https://www.hackerrank.com/challenges/grading/problem" rel="nofollow noreferrer">Grading Students</a> courtesy of HackerRank. My code passes all tests in the testing suite but I feel like there could be a better implementation of it. But nonetheless, what are some pros/cons of my current implementation? Thank you for answering. </p> <pre class="lang-py prettyprint-override"><code>def gradingStudents(grades): rounded_grades = [] for grade in grades: if grade &lt; 38: rounded_grades.append(grade) else: if grade % 5 == 0: rounded_grades.append(grade) else: difference = 0 new_grade = grade while grade % 5 != 0: difference += 1 new_grade += 1 if new_grade % 5 == 0: break if difference &lt; 3: rounded_grades.append(new_grade) else: rounded_grades.append(grade) return rounded_grades </code></pre>
[]
[ { "body": "<ul>\n<li>Your code is pretty good. Nice job.</li>\n<li>I'd personally change the first <code>else</code> to an <code>elif</code> so you don't have as much indentation.</li>\n<li><p>Rather than using that while loop you can just use one <code>%</code> per number.</p>\n\n<p>For each number if you get the modulo then you can find out how much to add. 7 % 5 is 2. Where 5 - 2 is not less than 3.</p>\n\n<p>And so you can easily change the while to just <code>difference = 5 - grade % 5</code></p></li>\n<li>You can merge <code>grade % 5 == 0</code> into the else.</li>\n<li>You can change the order and content of the ifs. This is as we don't need to call <code>list.append</code> three times, just mutate <code>grade</code>.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def gradingStudents(grades):\n rounded_grades = []\n for grade in grades:\n if grade &gt;= 38:\n difference = 5 - grade % 5\n if difference &lt; 3:\n grade += difference\n rounded_grades.append(grade)\n return rounded_grades\n</code></pre>\n\n<p>Since we know the range that anything modulo 5 is 0-4, we can just make a small lists that holds how much to round.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>ADDITIONS = [0, 0, 0, 2, 1]\n\n\ndef gradingStudents(grades):\n rounded_grades = []\n for grade in grades:\n if grade &gt;= 38:\n grade += ADDITIONS[grade % 5]\n rounded_grades.append(grade)\n return rounded_grades\n</code></pre>\n\n<p>You can also change the code to a list comprehension if you're that way inclined.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>ADDITIONS = [0, 0, 0, 2, 1]\n\n\ndef gradingStudents(grades):\n return [\n grade if grade &lt; 38 else grade + ADDITIONS[grade % 5]\n for grade in grades\n ]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T00:23:04.343", "Id": "465413", "Score": "0", "body": "Thank you for your commentary. I very much prefer the first version that you wrote. List comprehensions are great and all but just seeing the first version is good enough for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T00:27:38.697", "Id": "465414", "Score": "1", "body": "No problem, happy I could help :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T00:16:28.650", "Id": "237350", "ParentId": "237349", "Score": "3" } } ]
{ "AcceptedAnswerId": "237350", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-15T23:41:16.470", "Id": "237349", "Score": "3", "Tags": [ "python", "algorithm", "programming-challenge" ], "Title": "Grading Students - Hackerrank" }
237349
<p>I have devised a novel sorting algorithm, named Oracle Sort, which I believe is far superior to all currently known sorting algorithms (under certain assumptions). It utilizes an oracle to achieve a constant time complexity with regard to both the length of the input sequence and the number of distinct elements in the input sequence.</p> <p>However, it seems that current computing is not yet ready for such an advanced algorithm, and therefore certain compromises had to be made and the algorithm had to be altered. As a result of these alterations, the performance of the provided algorithm has been much degraded. Therefore, I ask for any advice regarding the improvement of the time complexity of the algorithm as it stands.</p> <p>Given below is an example implementation of the algorithm in Python 3.</p> <pre class="lang-py prettyprint-override"><code>from itertools import count, product def oraclesort(input_seq): """ Find a sequence (via enumeration), with is equal the sorted input sequence. Under ideal circumstances the enumeration would be done in parallel for all sequences of length up to at least the length of the input, and enumerating each of these sequences would take constant time. However, currently we are not able to achieve such results, so we have to resort to a less efficient sequential enumeration. The equality of enumerated candidate sequence and the sorted input sequence is determined by an oracle (the oracle_equals_sorted() function), which can tell in (assumed) constant time, whether the given candidate is equal to the sorted input. This, combined with the constant time needed to generate the candidates, gives us a total time complexity of O(1); the best known time complexity of an arbitrary-input sorting algorithm. """ for i in count(): for candidate_seq in product(input_seq, repeat=i): if oracle_equals_sorted(candidate_seq, input_seq): return candidate_seq def oracle_equals_sorted(candidate_seq, input_seq): """ Oracle which checks whether candidate_seq equals the sorted input_seq. The oracle should work in constant time (or ideally, in no-time), but we are limited to deterministic Turing Machines, and therefore, we are limited to certain implementations of the oracle, and these implementations happen to have non-optimal (eg. nonzero) time complexity. Despite being suboptimal, this implementation of the oracle is very elegant in that it internally uses the oracle sort to determine whether the given candidate sequence is equal to the sorted input sequence, hence completing a beautiful cycle of mutual recursion. """ candidate_lst = list(candidate_seq) input_lst = list(input_seq) if not candidate_lst and not input_lst: return True if not candidate_lst or not input_lst: return False _, min_idx = min((val, idx) for idx, val in enumerate(input_lst)) input_lst_without_min = input_lst[:min_idx] + input_lst[min_idx+1:] return candidate_lst[0] == input_lst[min_idx] and \ candidate_lst[1:] == list(oraclesort(input_lst_without_min)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T01:02:28.173", "Id": "465417", "Score": "1", "body": "I'm going to tag this as `python`, please include either `python-2.x` or `python-3.x` to reflect what version you used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T05:16:17.680", "Id": "465423", "Score": "0", "body": "You might get better benchmark results if you measure the time complexity using a four-cornered day." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T23:51:50.450", "Id": "465485", "Score": "1", "body": "@S.S.Anne This is definitely not \\$O(n^2)\\$. According to my (possibly imprecise) calculations, this has [hyperfactorial](https://en.wikipedia.org/wiki/Factorial#Hyperfactorial) time complexity in the worst case. I didn't try to figure out the exact space complexity, but it's probably going to be \\$O(n^2)\\$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T23:53:20.637", "Id": "465486", "Score": "0", "body": "@kyrill Ah, so it's worse than O(n^2). I wonder where the OP got the O(1) from, then..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T23:54:47.950", "Id": "465487", "Score": "0", "body": "Well apparently the O(1) complexity is under some pretty unrealistic assumptions, such as being able to consume arbitrary-length input in constant time (which is trivially impossible)." } ]
[ { "body": "<ul>\n<li>well done providing doc strings</li>\n<li>sticking to the <a href=\"https://www.python.org/dev/peps/pep-0008/#a-foolish-consistency-is-the-hobgoblin-of-little-minds\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> makes Python code easier to grasp, especially for someone who didn't write it</li>\n<li>to make the naming more convincing, you should factor out <code>sequential_deterministic_stand_in_for_seeing_the_required_result()</code> and <code>sequential_deterministic_stand_in_for_checking_the_result()</code><br>\nAs a bonus, this removed implementation detail from the docstrings of \"the oracle functions\".</li>\n<li>the nested loops in <code>oraclesort()</code> seem to iterate <em>all</em> permutations of elements from <code>input_seq</code> - as indicated in the docstring.<br>\nUsing <a href=\"https://docs.python.org/3/library/itertools.html#itertools.permutations\" rel=\"nofollow noreferrer\">itertools.permutations()</a> is easier to read and should test sequences of like length, only.<br>\n(Strictly faster than the related bogobogosort for not repeatedly checking the same sequence.)</li>\n<li>instead of determining the index of the minimum value and using slices to construct <code>input_lst_without_min</code>, you could use just determine the minimum value, compare it to the start of the candidate sequence and remove it from the sequence to sort recursively:<br>\n<code>input_lst_without_min = input_seq[:]</code><br>\n<code>input_lst_without_min.remove(min(input_seq))</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T07:03:13.607", "Id": "465426", "Score": "0", "body": "While your algorithm may be original, I doubt it's novelty - I'm pretty sure I've seen it before, if not remembering implementations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T13:01:45.930", "Id": "465443", "Score": "2", "body": "Recommended literature: https://en.wikipedia.org/wiki/Poe%27s_law" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T13:23:15.693", "Id": "465446", "Score": "0", "body": "@kyrill There are useful mindsets, procedures and habits doing code reviews just as in other parts of (software) development. Look at the code in the question with an eye on the coding, or reject the code because the implementation, as prominently stated in the question, (inevitably, for the time being) misses the main design goal - whatever you choose, make good use of your (and your readers') time." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T06:50:52.787", "Id": "237359", "ParentId": "237351", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T00:53:09.163", "Id": "237351", "Score": "1", "Tags": [ "python", "performance", "algorithm", "python-3.x", "sorting" ], "Title": "Novel sorting algorithm" }
237351
<p><strong>check_prime.cpp</strong></p> <p><strong>Description</strong>: Accepts user input to check if the user entered a prime number.</p> <p><strong>Notes</strong>: If any text inputted after an integer will be ignored. </p> <p><strong>For example</strong>: 1234.5678 and 98abc will be interpreted as 1234 and 98, respectively.</p> <p>Please provide any feedback (positive or negative). </p> <pre><code>// check_prime.cpp // Author: Chris Heath // Date: 12/9/2018 // Description: Accepts user input to check if the user entered a prime number. // Notes: If any text inputted after an integer will be ignored. // For example: 1234.5678 and 98abc will be interpreted as 1234 and 98, respectively. #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;limits&gt; using namespace std; int is_prime (unsigned long int num) { unsigned long int n; // avoid loop; 0 or 1 are never prime if (num == 0 || num == 1) return 0; // loop through numbers 0..(n/2)+1, trying to // divide one into the other with no remainder. for (n=2; n &lt; (num/2)+1; n++) { // if we had no remainder during a revision, // input number has a divisor... NOT PRIME! if ((num % n) == 0) return 0; } // made it through gauntlet...prime! return 1; } int main() { unsigned long int i; cout&lt;&lt;"Enter an integer to check if it is a prime: "; cin&gt;&gt;i; while(1) { if(cin.fail()) { cin.clear(); cin.ignore(numeric_limits&lt;streamsize&gt;::max(),'\n'); cout&lt;&lt;"You have entered wrong input.\nPlease try again: "; cin&gt;&gt;i; } if(!cin.fail()) break; } if ( is_prime(i) ) cout&lt;&lt;"\n"&lt;&lt;i&lt;&lt;" IS PRIME!"&lt;&lt;endl; else cout&lt;&lt;"\n"&lt;&lt;i&lt;&lt;" is NOT prime."&lt;&lt;endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T01:22:51.963", "Id": "465418", "Score": "1", "body": "You only need to check up to `floor(sqrt(n))`. No matter how long your sqrt operation takes, it will eventually be faster to sqrt than to check all the extra numbers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T03:44:23.833", "Id": "465419", "Score": "0", "body": "can you rephrase (or expand) that comment so it more clearly (or explicitly) relates to my code? thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T03:52:58.197", "Id": "465421", "Score": "1", "body": "in the for loop in is_prime, you set the upper bound to. `n < (num/2) + 1`. You're checking too many numbers. instead, you want to only set the conditon to `n < floor(sqrt(x))`" } ]
[ { "body": "<p>Don't use <a href=\"https://stackoverflow.com/q/1452721/5231607\"><code>using namespace std;</code></a>.</p>\n\n<p>Since <code>is_prime</code> only has two possible return values, and given its name implies a binary result, it should return a <code>bool</code>, not an <code>int</code>. Then replace the return statements with the proper bool values.</p>\n\n<p>When checking for primes, you only need to go up to the square root of the number to check. This value can be computed once then used in the loop condition, or you can check for <code>i * i &lt;= num</code>, although this has the potential to overflow with sufficiently large <code>num</code>.</p>\n\n<p>The check for 0 or 1 can be simplified to <code>if (num &lt; 2)</code>.</p>\n\n<p>Before the loop, you can check <code>num</code> to see if it is divisible by 2 and return an appropriate value. Then you loop can start at 3 and increment by 2 (so you only need to check the odd numbers).</p>\n\n<p>You should declare your variables as close to the place you first use them as possible, so your loop could be</p>\n\n<pre><code>for (unsigned long n = 3; ...\n</code></pre>\n\n<p>(or <code>for (auto n = 3UL;</code>).</p>\n\n<p>When getting input, rather than <code>while (1)</code> with repeated conditions in the loop, you can say <code>while (!cin.fail())</code> and not check for that within the loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T03:49:09.367", "Id": "465420", "Score": "0", "body": "thank you very much for your feedback... all great points that i will incorporate asap" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T13:00:07.210", "Id": "465442", "Score": "0", "body": "The last of your comments seems wrong. The loop is not to get multiple values but to retry when reading the (single) value failed. I made the same mistake on first read and to be honest, I blame that to some part on the indentation depth of a single space and the inconsistent use of indentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T18:24:13.787", "Id": "465457", "Score": "0", "body": "@uli If the original input succeeds, the first condition within the loop will be false, the second true, and the loop will be skipped. If the original input fails, the first condition will be true, the input will be retried, and the loop stopped if the retried input succeeds. Another way to look at it is since the `while(1)` loop ends in a conditional break, it can be changed to a `do`/`while` loop, and since the remainder of the loop body is a conditional that matches the end condition you can make it a `while(!cin.fail())`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T20:55:53.077", "Id": "465470", "Score": "0", "body": "I'm still confused. In particular, I can't imagine repeating anything when the streamstate indicates success. Retry until failure doesn't make sense. We seem to agree on that the loop with redundant code can be improved though." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T02:29:00.883", "Id": "237354", "ParentId": "237352", "Score": "4" } }, { "body": "<ul>\n<li>Formatting: Indent your code consistently. This makes it easier to understand and spot errors. Also, it attracts people here to read it at all. Your's is not a mess, but inconsistent still.</li>\n<li>Another rather obvious error is not to return a boolean for a function that gives you a true/false result. This is implicit documentation. If you return an int, you need to say what it means and how to interpret it, which the user of a function has to read and understand. With a boolean, that meaning is clear and requires no additional documentation.</li>\n<li><code>using namespace std;</code> is okay-ish for an example like this. It's bad as regular habit and it's inacceptable when done in a header file. The problem this causes is the pollution of the global namespace. Replace this with single <code>using</code> statements, possibly restricted to a smaller scope like a class or function, or just prefix the <code>std::</code>.</li>\n<li>Your comment \"loop through numbers 0..(n/2)+1\" is misleading, your loop starts with value 2. Try to avoid repeating what the code does. Rather, use a comment (when necessary) to explain <em>why</em> you did something, in particular the <code>(n/2)+1</code> deserves some explanation.</li>\n<li>This leads to the point that the limit <code>(n/2)+1</code> is not optimal. Assuming there are two numbers <code>n</code> and <code>m</code> that divide a third value <code>k</code> that you're trying to find. If your approach is to try increasing values of <code>n</code>, then you can stop as soon as the resulting value of <code>k / n</code> is less than <code>n</code>. The reason is that <code>n</code> and <code>m</code> are interchangeable, so any possible result for <code>m</code> would have been tried as <code>n</code> already.</li>\n<li>The while loop could be structured differently, each operation is required only once, to remove redundancy. The first of these is <code>cin &gt;&gt; i</code>, the other is checking <code>cin.fail()</code>. Other than that the loop is fine and correct. As a strategy, think about how you would describe the steps to a human. Use this description as comments to form a template for your code. This then takes this form:</li>\n</ul>\n\n<pre><code>// output a prompt\ncout&lt;&lt;\"Enter an integer to check if it is a prime: \";\nwhile (true)\n{\n // try to read a single number\n cin &gt;&gt; i;\n // if reading succeeded, we're done\n if(!cin.fail())\n break;\n // skip remainder of the line of input\n cin.clear();\n cin.ignore(numeric_limits&lt;streamsize&gt;::max(),'\\n');\n // output a warning and try again\n cout&lt;&lt;\"You have entered wrong input.\\nPlease try again: \";\n}\n</code></pre>\n\n<ul>\n<li>A stream can be used in a boolean expression to find out whether something failed or not. The above could have been simplified to <code>if (cin &gt;&gt; i) break;</code>.</li>\n<li>Just to mention it, when input failed, it sometimes makes sense to check for EOF as well. If you were reading numbers in an endless loop, sending an EOF (Control-D or Control-Z, depending on the terminal) can be used to exit that loop. If I send EOF to your program, it endlessly rotates prompting for a new value.</li>\n<li>The final <code>return 0</code> in <code>main()</code> is not necessary. This is a specialty of the <code>main()</code> function though, it doesn't apply to other functions.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T12:57:49.787", "Id": "237373", "ParentId": "237352", "Score": "2" } }, { "body": "<p>Even on a machine with relatively fast division, this algorithm (trial division) may be slower than a suitable sieve. Even more so, once you improve the program to accept multiple inputs.</p>\n\n<hr>\n\n<p>I encourage you to accept arguments rather than prompting for input. That said, I still reviewed the input code in <code>main()</code>:</p>\n\n<p>There's currently a bug that the program loops indefinitely asking for input when <code>std::cin</code> is closed.</p>\n\n<p>The existing loop is structured poorly - instead of an infinite loop with a <code>break</code>, we should show the condition in the control part of the <code>while</code>:</p>\n\n<pre><code>std::cout&lt;&lt;\"Enter an integer to check if it is a prime: \";\nunsigned long int i;\nwhile (!(cin &gt;&gt; i)) {\n if (cin.eof()) {\n std::cerr &lt;&lt; \"Input read failure\\n\";\n return EXIT_FAILURE; // from &lt;cstdlib&gt;\n }\n\n cin.ignore(numeric_limits&lt;std::streamsize&gt;::max(),'\\n');\n cin.clear();\n std::cout &lt;&lt; \"You have entered wrong input.\\nPlease try again: \";\n}\n</code></pre>\n\n<p>Look, no <code>break</code> or <code>continue</code> - that makes the code easier to read and understand.</p>\n\n<hr>\n\n<p>There's an include that is unused, and can be safely removed:</p>\n\n<blockquote>\n<pre><code>#include &lt;string&gt;\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>This comment is ambiguous:</p>\n\n<blockquote>\n<pre><code>// Date: 12/9/2018\n</code></pre>\n</blockquote>\n\n<p>Avoid the abbreviated <code>d/m/y</code> form (because Americans swap the day and month around). Prefer forms with non-numeric month name, or use ISO-8601 format (<code>yyyy-mm-dd</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T10:55:50.900", "Id": "237429", "ParentId": "237352", "Score": "1" } }, { "body": "<ul>\n<li><p><code>int</code> is redundant in this variable declaration: <code>unsigned long int num</code>\nSee the properties table on this reference page: <a href=\"https://en.cppreference.com/w/cpp/language/types\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/language/types</a></p></li>\n<li><p>in this case, it is better to use <code>++n</code> rather than <code>n++</code> for better readability. <code>++n</code> precisely describes what this imperative procedure tries to do: increment the value of variable <code>n</code> by 1 and save the new value. The code is not relying on the extra step (make and return a copy of the original value) from post-increment operator to be functionally correct. Thus <code>n++</code> has a redundant step. </p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T18:50:38.420", "Id": "465613", "Score": "0", "body": "Could you explain why it is better to do these things?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T17:57:51.343", "Id": "237447", "ParentId": "237352", "Score": "2" } } ]
{ "AcceptedAnswerId": "237373", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T01:08:09.623", "Id": "237352", "Score": "4", "Tags": [ "c++", "performance" ], "Title": "check_prime.cpp (checks if input is a prime number)" }
237352
<p>This is a playable <a href="https://en.wikipedia.org/wiki/15_puzzle" rel="nofollow noreferrer">15 puzzle game</a> in Python and Curses. It consists of 2 files, a backend called <code>fifteen.py</code> and a frontend called <code>curses_frontend.py</code>. The idea is that different frontends could be built for different purposes.</p> <h1>fifteen.py:</h1> <pre class="lang-py prettyprint-override"><code>from enum import Enum from collections import namedtuple import random Coordinates = namedtuple(&quot;Coords&quot;,[&quot;x&quot;,&quot;y&quot;]) Direction = Enum(&quot;Direction&quot;,&quot;UP DOWN LEFT RIGHT&quot;) class FifteenPuzzle: initial_board = ((&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;), (&quot;5&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;), (&quot;9&quot;,&quot;A&quot;,&quot;B&quot;,&quot;C&quot;), (&quot;D&quot;,&quot;E&quot;,&quot;F&quot;,&quot; &quot;)) def __init__(self): self.board = [list(row) for row in self.initial_board] # tuple to list self.shuffle() def shuffle(self): for _ in range(100): self.move(random.choice(list(Direction))) def findzero(self): for y,row in enumerate(self.board): for x,v in enumerate(row): if v == &quot; &quot;: return Coordinates(x,y) def move(self,direction): p = self.findzero() if direction == Direction.UP: if p.y == 3: return False self.board[p.y][p.x] = self.board[p.y+1][p.x] self.board[p.y+1][p.x] = &quot; &quot; if direction == Direction.DOWN: if p.y == 0: return False self.board[p.y][p.x] = self.board[p.y-1][p.x] self.board[p.y-1][p.x] = &quot; &quot; if direction == Direction.LEFT: if p.x == 3: return False self.board[p.y][p.x] = self.board[p.y][p.x+1] self.board[p.y][p.x+1] = &quot; &quot; if direction == Direction.RIGHT: if p.x == 0: return False self.board[p.y][p.x] = self.board[p.y][p.x-1] self.board[p.y][p.x-1] = &quot; &quot; return True def is_win(self): return tuple(tuple(row) for row in self.board) == self.initial_board def __str__(self): ret = &quot;&quot; for row in self.board: for val in row: ret += val ret += &quot;\n&quot; return ret[:-1] # strip trailing newline </code></pre> <h1>curses_frontend.py</h1> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 from fifteen import FifteenPuzzle, Direction from pathlib import Path import time import os import curses DEFAULT_HIGHSCORE = 999 SAVE_LOCATION = Path.home()/&quot;.15scores&quot; class CursesApp(): KEYS_UP = [ord('w'),ord('W'),ord('j'),ord('J'),curses.KEY_UP] KEYS_DOWN = [ord('s'),ord('S'),ord('k'),ord('K'),curses.KEY_DOWN] KEYS_LEFT = [ord('a'),ord('A'),ord('h'),ord('H'),curses.KEY_LEFT] KEYS_RIGHT = [ord('d'),ord('D'),ord('l'),ord('L'),curses.KEY_RIGHT] def __init__(self): pass def __enter__(self): self.stdscr = curses.initscr() curses.noecho() curses.cbreak() self.stdscr.keypad(True) curses.curs_set(False) self.puzzle_win = curses.newwin(4,5,0,0) # extra space for newlines self.score_win = curses.newwin(1,curses.COLS - 1,4,0) self.message_win = curses.newwin(1,curses.COLS - 1,5,0) self.stdscr.refresh() self.score_win.addstr(0,0,&quot;Moves: &quot;) self.score_win.refresh() return self def __exit__(self,typ,val,tb): curses.nocbreak() self.stdscr.keypad(False) curses.curs_set(True) curses.echo() curses.endwin() def draw_puzzle(self,puzzle): self.puzzle_win.clear() self.puzzle_win.addstr(0,0,str(puzzle)) self.puzzle_win.refresh() def draw_message(self,s): self.message_win.clear() self.message_win.addstr(0,0,s) self.message_win.refresh() def draw_score(self,score): self.score_win.addstr(0,7,&quot; &quot;) # clear regular score self.score_win.addstr(0,7,str(score)) self.score_win.refresh() def draw_highscore(self,score): self.score_win.addstr(0,11,&quot;High Score: &quot;) self.score_win.addstr(0,23,str(score)) self.score_win.refresh() def gethighscore(): try: with open(SAVE_LOCATION, 'r') as f: return int(f.readline().rstrip()) except FileNotFoundError: return DEFAULT_HIGHSCORE except ValueError: os.remove(str(SAVE_LOCATION)) return DEFAULT_HIGHSCORE+1 def sethighscore(s): with open(SAVE_LOCATION, 'w') as f: f.write(str(s)) def main(app): puzzle = FifteenPuzzle() highscore = gethighscore() while True: puzzle.shuffle() score = 0 app.draw_score(0) if highscore &lt; DEFAULT_HIGHSCORE: app.draw_highscore(highscore) if highscore == DEFAULT_HIGHSCORE+1: app.draw_message(&quot;High score file corrupted. Erasing&quot;) time.sleep(1) while not puzzle.is_win(): app.draw_puzzle(puzzle) app.draw_message(&quot;arrows/hjkl/wasd:Move|q:quit&quot;) c = app.stdscr.getch() direction = None if c in app.KEYS_UP: direction = Direction.UP if c in app.KEYS_DOWN: direction = Direction.DOWN if c in app.KEYS_LEFT: direction = Direction.LEFT if c in app.KEYS_RIGHT: direction = Direction.RIGHT if direction: if puzzle.move(direction): score+=1 app.draw_score(score) else: app.draw_message(&quot;Invalid move&quot;) time.sleep(0.5) if c in (ord('q'),ord('Q')): app.draw_message(&quot;Press q again to quit&quot;) if app.stdscr.getch() in (ord('q'),ord('Q')): return app.draw_puzzle(puzzle) while True: if score &lt; highscore: highscore = score app.draw_highscore(score) app.draw_message(&quot;New high score!&quot;) sethighscore(score) time.sleep(0.5) app.draw_message(&quot;Play again? (y/n)&quot;) c = app.stdscr.getch() if c in (ord('y'),ord('Y')): break # from inner loop to return to outer loop if c in (ord('n'),ord('N')): return # from entire function if(__name__ == &quot;__main__&quot;): with CursesApp() as app: main(app) print(&quot;Thanks for playing!&quot;) </code></pre>
[]
[ { "body": "<h1>fifteen.py</h1>\n\n<h2><code>__init__</code></h2>\n\n<ul>\n<li>For easier testing, consider adding a way to initialize the board to a certain state. Something like this would be nice:\n\n<pre class=\"lang-python prettyprint-override\"><code>\"\"\"\n2 81\n73B6\nA4EC\n59DF\n\"\"\"\npuzzle = FifteenPuzzle(\"2 8173B6A4EC59DF\")\n</code></pre>\n\nYou would need to validate the input and transform it into a 4x4 grid (and of course omit the call to <code>shuffle()</code> for this flow) which is a bit of extra work, but it will prove very useful when writing unit tests.</li>\n<li>You should initialize an instance variable to track the coordinates of the blank space (more on this below).</li>\n</ul>\n\n<h2><code>shuffle</code></h2>\n\n<ul>\n<li>You're repeatedly calling <code>list(Direction)</code> within the loop when you could instead call it once outside the loop and bind it to a local variable. Also it doesn't need to be a list because we're not mutating it in any way, and <code>random.choice</code> accepts any sequence. So I would do <code>directions = tuple(Direction)</code> before the loop to get a sequence of all the directions.</li>\n<li>To avoid doing a bunch of repeated attribute lookups (e.g. <code>self.move</code>, <code>random.choice</code>) in a loop, we can instead do the lookups once and save the results in local variables for a speedup:\n\n<pre class=\"lang-python prettyprint-override\"><code>def shuffle(self) -&gt; None:\n directions = tuple(Direction)\n move = self.move\n random_choice = random.choice\n for _ in range(100):\n move(random_choice(directions))\n</code></pre>\n\nSource is <a href=\"https://wiki.python.org/moin/PythonSpeed#Take_advantage_of_interpreter_optimizations\" rel=\"nofollow noreferrer\">this page on Python speed</a>:\n\n<blockquote>\n <p>In functions, local variables are accessed more quickly than global variables, builtins, and attribute lookups. So, it is sometimes worth localizing variable access in inner-loops. For example, the code for <code>random.shuffle()</code> localizes access with the line, <code>random=self.random</code>. That saves the shuffling loop from having to repeatedly lookup <code>self.random</code>. Outside of loops, the gain is minimal and rarely worth it.</p>\n</blockquote></li>\n</ul>\n\n<h2><code>findzero</code></h2>\n\n<ul>\n<li>A more apt name for this is probably <code>find_blank</code> since we're actually finding the blank space (missing tile) in the puzzle.</li>\n</ul>\n\n<h2><code>move</code></h2>\n\n<ul>\n<li><code>findzero</code> is called every time <code>move</code> is called, which means we do a full scan of the board to find the blank space each time before stepping into the move logic. This is inefficient. Instead, track the coordinates of the blank space as an instance variable, e.g. <code>self.blank_space</code>. Then we only need to call <code>findzero</code> once, right after board initialization. After <code>self.blank_space</code> is initialized, on every move we can update <code>self.blank_space</code> accordingly.</li>\n<li>There is a lot of duplicated logic here that essentially swaps a designated adjacent tile with the current blank space based on the given direction. I would refactor some of this logic into a helper method that takes in the coordinates of the designated tile, and does the swapping and updating of the blank space position for you:\n\n<pre class=\"lang-python prettyprint-override\"><code>def move_tile_to_blank(self, t: Coordinates) -&gt; None:\n board = self.board\n b = self.blank_space\n board[b.y][b.x], board[t.y][t.x] = board[t.y][t.x], board[b.y][b.x]\n self.blank_space = t\n</code></pre></li>\n</ul>\n\n<h2><code>is_win</code></h2>\n\n<ul>\n<li>A better name for this method is probably <code>is_solved</code>.</li>\n<li>This is a prime candidate for the <code>@property</code> decorator so you can retrieve this status like you would an attribute:\n\n<pre class=\"lang-python prettyprint-override\"><code>&gt;&gt;&gt; puzzle = FifteenPuzzle(\"2 8173B6A4EC59DF\")\n&gt;&gt;&gt; puzzle.is_solved\nFalse\n&gt;&gt;&gt; puzzle = FifteenPuzzle(\"123456789ABCDEF \")\n&gt;&gt;&gt; puzzle.is_solved\nTrue\n</code></pre></li>\n<li>Instead of converting the whole board to a tuple of tuples and comparing it to <code>initial_board</code>, it's more time- and memory-efficient to compare the boards tile-by-tile with iterators:\n\n<pre class=\"lang-python prettyprint-override\"><code>@property\ndef is_solved(self) -&gt; bool:\n return all(\n tile == expected_tile\n for tile, expected_tile in zip(\n itertools.chain.from_iterable(self.board),\n itertools.chain.from_iterable(self.initial_board)\n )\n )\n</code></pre></li>\n</ul>\n\n<h2><code>__str__</code></h2>\n\n<ul>\n<li><p>Use <code>join()</code> to concatenate strings. From <a href=\"https://wiki.python.org/moin/PythonSpeed#Use_the_best_algorithms_and_fastest_tools\" rel=\"nofollow noreferrer\">the same page on Python speed</a>:</p>\n\n<blockquote>\n <p>String concatenation is best done with <code>''.join(seq)</code> which is an O(n) process. In contrast, using the '+' or '+=' operators can result in an O(n**2) process because new strings may be built for each intermediate step. The CPython 2.4 interpreter mitigates this issue somewhat; however, <code>''.join(seq)</code> remains the best practice.</p>\n</blockquote>\n\n<p>So this can actually be refactored to the following one-liner:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def __str__(self) -&gt; str:\n return \"\\n\".join(\"\".join(row) for row in self.board)\n</code></pre></li>\n</ul>\n\n<h2>Style</h2>\n\n<p>The following comments can be addressed by hand, or if you don't mind delegating that responsibility to a tool, you can use a code formatter like <a href=\"https://black.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\">Black</a> which will do it for you.</p>\n\n<ul>\n<li>Leave whitespace in between method declarations, it makes the code easier to read.</li>\n<li><p>Leave a space after commas, e.g.</p>\n\n<pre class=\"lang-python prettyprint-override\"><code># Yes:\n(\"1\", \"2\", \"3\", \"4\")\n\n# No:\n(\"1\",\"2\",\"3\",\"4\")\n\n# Yes:\ndef move(self, direction):\n\n# No:\ndef move(self,direction):\n</code></pre></li>\n</ul>\n\n<h1>curses_frontend.py</h1>\n\n<h2>Dependency injection</h2>\n\n<p>Your frontend logic exists in both the <code>CursesApp</code> class and the <code>main()</code> method, but I think it would be cleaner for all the logic to live in <code>CursesApp</code> instead. Dependencies such as <code>FifteenPuzzle</code> could then be initialized and injected into <code>CursesApp</code>. More on this below.</p>\n\n<h2>High score management</h2>\n\n<p>I would create a separate class dedicated to score management with the following responsibilities:</p>\n\n<ul>\n<li>loading the high score from a file</li>\n<li>tracking the current score and high score</li>\n<li>incrementing the current score</li>\n<li>resetting the current score</li>\n<li>saving the high score to a file</li>\n</ul>\n\n<p>Then this score tracker could be initialized and injected into <code>CursesApp</code> as a dependency, just like <code>FifteenPuzzle</code>.</p>\n\n<h2><code>curses.wrapper</code></h2>\n\n<p>Your <code>CursesApp</code> is a context manager that does proper setup/teardown of the curses application via methods like <code>curses.noecho()</code>, <code>curses.cbreak()</code>, etc. The <code>curses</code> module actually provides a nice convenience method <a href=\"https://docs.python.org/3/howto/curses.html#starting-and-ending-a-curses-application\" rel=\"nofollow noreferrer\"><code>curses.wrapper()</code></a> which does the same thing without all of that boilerplate code.</p>\n\n<h2><code>time.sleep</code></h2>\n\n<p>I would generally avoid using <code>time.sleep</code> here; it blocks the main thread, and combined with input buffering, if we make enough (let's say <code>k</code>) \"invalid moves\" in rapid succession, we end up with an unresponsive application for <code>k * SLEEP_TIME</code> seconds. This is not a great user experience.</p>\n\n<p>Instead, I would recommend giving the keyboard controls text its own line and moving the message window to its own line. Then you can use the pattern of displaying messages, blocking on any user input, and clearing the message once you've received that user input.</p>\n\n<h2><code>draw_score</code> and <code>draw_highscore</code></h2>\n\n<p>These should honestly be combined into one method, i.e. any time you print the current score, you should also print the high score as well. One advantage of doing things this way is we avoid brittle logic like</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>self.score_win.addstr(0,7,\" \") # clear regular score\nself.score_win.addstr(0,7,str(score))\n</code></pre>\n\n<p>where we are implicitly assuming the current score will never exceed four digits.</p>\n\n<h2>Mapping keyboard input to a <code>Direction</code></h2>\n\n<p>Use a map of ASCII values to <code>Direction</code>s instead of using four separate lists and <code>if</code> statements. So instead of this</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>direction = None\nif c in app.KEYS_UP:\n direction = Direction.UP\nif c in app.KEYS_DOWN:\n direction = Direction.DOWN\nif c in app.KEYS_LEFT:\n direction = Direction.LEFT\nif c in app.KEYS_RIGHT:\n direction = Direction.RIGHT\nif direction:\n # ...\n</code></pre>\n\n<p>you could have a map that starts out like this</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>KEY_TO_DIRECTION = {\n curses.KEY_UP: Direction.UP,\n curses.KEY_DOWN: Direction.DOWN,\n curses.KEY_LEFT: Direction.LEFT,\n curses.KEY_RIGHT: Direction.RIGHT,\n}\n</code></pre>\n\n<p>a separate map for custom key aliases for up/down/left/right</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>DIRECTION_TO_CUSTOM_KEYS = {\n Direction.UP: (\"w\", \"j\"),\n Direction.DOWN: (\"s\", \"k\"),\n Direction.LEFT: (\"a\", \"h\"),\n Direction.RIGHT: (\"d\", \"l\"),\n}\n</code></pre>\n\n<p>then you can populate <code>KEY_TO_DIRECTION</code> like so</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>for direction, keys in DIRECTION_TO_CUSTOM_KEYS.items():\n for key in keys:\n KEY_TO_DIRECTION[ord(key.lower())] = direction\n KEY_TO_DIRECTION[ord(key.upper())] = direction\n</code></pre>\n\n<p>and use it like so</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>if direction := KEY_TO_DIRECTION.get(c, None):\n # do something with `direction`\n</code></pre>\n\n<h2>Style</h2>\n\n<ul>\n<li><p><a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">PEP8</a> recommends the following order for imports, with a blank line between each group of imports:</p>\n\n<ol>\n<li>Standard library imports</li>\n<li>Related third party imports</li>\n<li>Local application/library specific imports</li>\n</ol></li>\n<li><p>Same issues here with lack of whitespace between methods and lack of whitespace after commas</p></li>\n<li>Drop unnecessary parentheses for the <code>__main__</code> guard, i.e. <code>if __name__ == \"__main__\":</code></li>\n</ul>\n\n<h2>Refactored version</h2>\n\n<p>Here's a refactored version (Python 3.8) of <code>curses_frontend.py</code> with the above suggestions incorporated:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>#!/usr/bin/env python3\n\nimport curses\nfrom pathlib import Path\nfrom typing import Tuple\n\nfrom fifteen import FifteenPuzzle, Direction\n\nDEFAULT_HIGHSCORE = 999\nSAVE_LOCATION = Path.home() / \".15scores\"\nDIRECTION_TO_CUSTOM_KEYS = {\n Direction.UP: (\"w\", \"j\"),\n Direction.DOWN: (\"s\", \"k\"),\n Direction.LEFT: (\"a\", \"h\"),\n Direction.RIGHT: (\"d\", \"l\"),\n}\n\n\nclass Scoreboard:\n score: int\n high_score: int\n save_file: Path\n\n def __init__(self, save_file: Path) -&gt; None:\n self.save_file = save_file\n self._load_high_score()\n self.score = 0\n\n def _load_high_score(self) -&gt; None:\n try:\n self.high_score = int(self.save_file.read_text().strip())\n except (FileNotFoundError, ValueError):\n self.high_score = DEFAULT_HIGHSCORE\n\n def increment(self, k: int = 1) -&gt; None:\n self.score += k\n\n def reset(self) -&gt; None:\n self.score = 0\n\n @property\n def current_and_high_score(self) -&gt; Tuple[int, int]:\n return (self.score, self.high_score)\n\n def publish(self) -&gt; bool:\n if self.score &lt; self.high_score:\n self.save_file.write_text(str(self.score))\n self.high_score = self.score\n return True\n return False\n\n\nclass CursesApp:\n QUIT_KEYS = (ord(\"q\"), ord(\"Q\"))\n YES_KEYS = (ord(\"y\"), ord(\"Y\"))\n NO_KEYS = (ord(\"n\"), ord(\"N\"))\n KEY_TO_DIRECTION = {\n curses.KEY_UP: Direction.UP,\n curses.KEY_DOWN: Direction.DOWN,\n curses.KEY_LEFT: Direction.LEFT,\n curses.KEY_RIGHT: Direction.RIGHT,\n }\n\n def __init__(self, stdscr, puzzle, scoreboard):\n self.stdscr = stdscr\n self.puzzle = puzzle\n self.scoreboard = scoreboard\n curses.curs_set(False)\n curses.use_default_colors()\n self.puzzle_win = curses.newwin(4, 5, 0, 0)\n self.score_win = curses.newwin(1, curses.COLS - 1, 4, 0)\n self.stdscr.addstr(5, 0, \"arrows/hjkl/wasd:move | q:quit\")\n self.message_win = curses.newwin(1, curses.COLS - 1, 6, 0)\n self.stdscr.refresh()\n\n _ord = ord\n key_map = self.KEY_TO_DIRECTION\n for direction, keys in DIRECTION_TO_CUSTOM_KEYS.items():\n for key in keys:\n key_map[_ord(key.lower())] = direction\n key_map[_ord(key.upper())] = direction\n\n def start(self):\n while self.play():\n self.scoreboard.reset()\n self.puzzle.shuffle()\n\n def play(self):\n while self.refresh() and not self.puzzle.is_solved:\n c = self.stdscr.getch()\n if c in self.QUIT_KEYS:\n self.draw_message(\"Press q again to quit\")\n if self.stdscr.getch() in self.QUIT_KEYS:\n return False\n self.clear_message()\n elif direction := self.KEY_TO_DIRECTION.get(c, None):\n if self.puzzle.move(direction):\n self.scoreboard.increment()\n\n if self.scoreboard.publish():\n self.draw_scores()\n self.draw_message(\"New high score!\")\n self.block_on_input()\n\n return self.wants_to_play_again()\n\n def wants_to_play_again(self):\n while True:\n self.draw_message(\"Play again? (y/n)\")\n c = self.stdscr.getch()\n if c in self.YES_KEYS:\n self.clear_message()\n return True\n elif c in self.NO_KEYS:\n self.clear_message()\n return False\n\n def draw_scores(self):\n current_score, high_score = self.scoreboard.current_and_high_score\n scores = f\"Moves: {current_score} | High Score: {high_score}\"\n self.score_win.clear()\n self.score_win.addstr(0, 0, scores)\n self.score_win.refresh()\n\n def refresh(self):\n self.puzzle_win.addstr(0, 0, str(self.puzzle))\n self.puzzle_win.refresh()\n self.draw_scores()\n return True\n\n def draw_message(self, s):\n self.message_win.clear()\n self.message_win.addstr(0, 0, s)\n self.message_win.refresh()\n\n def clear_message(self):\n self.message_win.clear()\n self.message_win.refresh()\n\n def block_on_input(self):\n return self.stdscr.getch()\n\n\ndef main(stdscr):\n puzzle = FifteenPuzzle()\n scoreboard = Scoreboard(SAVE_LOCATION)\n CursesApp(stdscr, puzzle, scoreboard).start()\n\n\nif __name__ == \"__main__\":\n curses.wrapper(main)\n print(\"Thanks for playing!\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T00:09:19.003", "Id": "237595", "ParentId": "237353", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T01:17:00.687", "Id": "237353", "Score": "5", "Tags": [ "python", "curses" ], "Title": "15 Puzzle in Python" }
237353
<p>So I based my "algorithm" on the poke method defined by Persi Diaconis. You start with the card at the bottom of a given deck and then poke the top card into a random position in the deck. At first the probability of this happening is 1/52 but once a card is below the bottom most card it increases to 2/52 since there is now two positions a card could go to move the bottom card up the deck.</p> <p>He claims it takes about 200 of these pokes to get the bottom card to the top. Then you poke the that bottom card which is now at the top somewhere random in the deck and he claims it is now completely randomized.</p> <p>My results have held true to that, I haven't calculated mean or standard deviation yet to check but just from initial runs it seems to hold true(he is a mathematician and I am a first year undergrad, of course its true).</p> <pre><code>public void shuffle() { SecureRandom rnd = new SecureRandom(); Card bottomCard = deck.get(deck.size() - 1); int i = 0; while(!deck.get(0).equals(bottomCard)) { Card poke = deck.get(0); deck.remove(0); deck.add(rnd.nextInt(52), poke); } deck.remove(bottomCard); deck.add(rnd.nextInt(52), bottomCard); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T02:52:03.387", "Id": "465826", "Score": "0", "body": "You're essentially shuffling an array, to which there is a well known good algorithm. Inventing a new one makes sense only if you have other requirements than \"producing a shuffled deck.\"" } ]
[ { "body": "<p>It's an interesting approach... Some cleanup to consider...</p>\n\n<pre><code>int i = 0;\n</code></pre>\n\n<p><code>i</code> is never used...</p>\n\n<pre><code>rnd.nextInt(52)\n</code></pre>\n\n<p>You might want to interrogate the size of <code>deck</code> at the start of the method, rather than using a fixed 'magic' number. That would mean that you'd be able to use the method to shuffle decks of multiple packs of cards for example...</p>\n\n<pre><code>deck.remove(bottomCard);\n</code></pre>\n\n<p>Although you're treating this as a unique case, it's still card 0, I'd consider defining a constant <code>FIRST_CARD_IN_DECK=0</code> to represent the card to remove.</p>\n\n<p>It's unclear where <code>deck</code> comes from should it be passed into the shuffle function?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T09:27:14.077", "Id": "465531", "Score": "0", "body": "Thank you for your response! So shuffle is a behavior in a `Deck` object that has the field deck which is non-static and private. LOL sorry i = 0 was left over from running some mean/standard deviation/chi-squared tests....... woops..... Maybe you can explain your logic for creating a constant, not that I think its unreasonable. I would argue that it just creates another Attribute that needs to be on the Stack at runtime, obviously in this case doesn't matter but in a bigger program would just mean more memory usage for a variable that doesn't need to be there." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T10:11:56.410", "Id": "237367", "ParentId": "237355", "Score": "2" } }, { "body": "<p>I assume that <code>shuffle</code> is inside a class that represents a <code>Deck</code>.</p>\n\n<hr>\n\n<p>52 is a <a href=\"https://refactoring.guru/replace-magic-number-with-symbolic-constant\" rel=\"nofollow noreferrer\">magic number</a>. We could simply replace it by a constant variable with the name <code>size</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>\npublic final int size = 52;\n\npublic void shuffle() {\n /* ... */\n while(/* ... */) {\n /* ... */ \n deck.add(rnd.nextInt(size), poke);\n }\n /* ... */\n deck.add(rnd.nextInt(size), poke);\n}\n</code></pre>\n\n<p>One important benefit is that we don't have to change <code>52</code> at multiple places if the size should change and typos can be avoided too.</p>\n\n<hr>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>Card poke = deck.get(0);\ndeck.remove(0);\n</code></pre>\n</blockquote>\n\n<p>This snipped can be simplified:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Card pole = deck.remove(0);\n</code></pre>\n\n<hr>\n\n<p>Extract <code>SecureRandom</code> to the class scope to only create an instance of it once instead for every <code>shuffle</code> invocation.</p>\n\n<p>If you are interested in testing we should try to make <code>shuffle</code> a <a href=\"https://en.wikipedia.org/wiki/Pure_function\" rel=\"nofollow noreferrer\">pure functions</a>, because they are easy to test. Since we depend on <code>SecureRandom</code> and randomness makes a method impure we need to override the method <code>nextInt</code> to return a constant value and <a href=\"https://stackoverflow.com/a/130862/8339141\">inject it as a dependency</a>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Test {\n class MockedRandom extends SecureRandom {\n\n int number;\n\n MockedRandom(int number) { this.number = number; }\n\n @Override\n public int nextInt(int bound) {\n return number;\n }\n\n }\n\n @Test\n void example() {\n Deck deck = new Deck(new MockedRandom(5));\n\n deck.shuffle();\n\n assertThat(...)\n }\n\n\n} \n</code></pre>\n\n<hr>\n\n<p>A <code>Deck</code> could contain besides <code>suffle</code> methods like <code>drawFromTop</code>, <code>last</code>, <code>remove</code> and <code>addRandomly</code> to make the algorithm more readable:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void shuffle() {\n while (first().equalsNot(last())) {\n addRandomly(drawFromTop());\n }\n\n addRandomly(drawFromBottom());\n}\n</code></pre>\n\n<hr>\n\n<p>I do not know which data structure you use for <code>deck</code> but if it is not an <code>LinkedList</code> you should think if the operation <code>deck.add(rnd.nextInt(52), poke);</code> <a href=\"https://www.quora.com/Why-does-ArrayList-take-more-time-to-insert-elements-in-the-beginning-than-LinkedList-in-Java?share=1\" rel=\"nofollow noreferrer\">could cause a performance issue</a> for you.</p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Deck {\n\n private final SecureRandom rnd = new SecureRandom();\n private final int size = 52;\n private LinkedList&lt;Card&gt; deck;\n\n public void shuffle() {\n while (first().equalsNot(last())) {\n addRandomly(drawFromTop());\n }\n\n addRandomly(drawFromBottom());\n }\n\n /**\n * Adds card at a random position\n *\n * @param card to add\n */\n private void addRandomly(Card card) {\n deck.add(rnd.nextInt(size), card);\n }\n\n /**\n * shows last card in the deck without to modify it\n */\n public Card last() {\n return deck.getFirst();\n }\n\n /**\n * shows first card in the deck without to modify it\n */\n public Card first() {\n return deck.getLast();\n }\n\n /**\n * removes first card from the deck and returns it\n */\n public Card drawFromTop() {\n return deck.removeFirst();\n }\n\n /**\n * removes last card from the deck and returns it\n */\n public Card drawFromBottom() {\n return deck.removeLast();\n } \n}\n</code></pre>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T00:50:35.060", "Id": "465645", "Score": "0", "body": "Thank you for this incredible response, it's going to take me a bit to get through it all, I will post updates and edits when I finish. I have a lot of school assignments right now and this is apart of a bigger program and now that I understand the purpose of pure functions and \"magic numbers\" replaced with constants I think I will write far more intuitive programs going forward :) Thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T04:05:21.323", "Id": "465651", "Score": "0", "body": "Hi, so I was hoping to port my card game application over to the web at some point which is when it seems like a DI pattern would make sense but for my current program I'm not sure it makes sense, maybe you could shed some light on this..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T10:46:40.783", "Id": "237428", "ParentId": "237355", "Score": "1" } } ]
{ "AcceptedAnswerId": "237428", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T02:40:31.047", "Id": "237355", "Score": "2", "Tags": [ "java", "algorithm", "shuffle" ], "Title": "Is this a reasonable algorithm for shuffling cards?" }
237355
<p>Just curious if someone could review my design, and implementation of the following requirements below. I am a mid level dev, and this is for a new job. I am looking for ways to improve, and your overall thoughts if you were the interviewer. </p> <p>Code Test Instructions:</p> <p>Write a simple application/service that accepts two inputs: chess piece (one of king, queen, rook or bishop) and a starting position using standard chess notation (a1, b2, c3, etc). The service provides all possible positions on a standard chess board that the chess piece can move to from that position.</p> <p>Assumptions: there are no other pieces on the board and there are no special considerations for a piece relative to another piece such as a king and rook moving together in a single turn under certain circumstances.</p> <p>Reviewer will be looking for correct functionality, use of design patterns, use of unit testing, use of object oriented programming, code re-use, etc. Each stage may be represented with a new project in the single solution.</p> <p>Stage 1:</p> <p>Create a C# 7 .net core class library project with model classes for the chess pieces and the algorithms for determining the possible moves.</p> <p>Create unit tests in a separate project with adequate coverage to test the algorithms</p> <p>Other stages are not listed because I am on stage 1.</p> <p>I did not use any design patterns because I thought it wasn't necessary, and would be overkill for this coding exercise. Should I add something like the strategy design pattern for the rules just for the sake of adding it? I thought I could explain that adding design patterns would add unnecessary complexity for these requirements.</p> <p>Code Below - Note: all other chess pieces are similar to the Queen class.</p> <pre><code>public class Board { private const int MAX_ROW_SIZE = 8; private const int MAX_COLUMN_SIZE = 8; public readonly Square[,] squares = new Square[MAX_ROW_SIZE,MAX_COLUMN_SIZE]; public Board() { for (int i = 0; i &lt; MAX_ROW_SIZE; i++) { for (int j = 0; j &lt; MAX_COLUMN_SIZE; j++) { squares[i,j] = new Square(i, j); } } } public List&lt;Square&gt; GetAvailableMoves(Square startingSquare) { if (startingSquare.piece == null) { throw new Exception("Square must have a chess piece on it to get the available moves."); } List&lt;Square&gt; validPieceMoves = new List&lt;Square&gt;(); for (int i = 0; i &lt; MAX_ROW_SIZE; i++) { for (int j = 0; j &lt; MAX_COLUMN_SIZE; j++) { int destColumn = j; int destRow = i; int sourceColumn = startingSquare.column; int sourceRow = startingSquare.row; bool isNewSquareValid = startingSquare.piece.IsValidMove(sourceColumn, sourceRow, destColumn, destRow); if (isNewSquareValid) { Square possibleSquare = new Square(destRow, destColumn); validPieceMoves.Add(possibleSquare); } } } return validPieceMoves; } } public abstract class PieceBase { public readonly PieceType pieceType; public PieceBase(PieceType pieceType) { this.pieceType = pieceType; } internal abstract bool IsValidMove(int sourceColumn, int sourceRow, int destColumn, int destRow); protected bool _IsDiagonalMove(int sourceColumn, int sourceRow, int destColumn, int destRow) { bool isDiagonalMove = Math.Abs(destColumn - sourceColumn) == Math.Abs(destRow - sourceRow); return isDiagonalMove; } protected bool _IsVerticalMove(int sourceColumn, int sourceRow, int destColumn, int destRow) { bool isVerticalMove = sourceColumn == destColumn &amp;&amp; sourceRow != destRow; return isVerticalMove; } protected bool _IsHorizontalMove(int sourceColumn, int sourceRow, int destColumn, int destRow) { bool isHorizontalMove = sourceRow == destRow &amp;&amp; sourceColumn != destColumn; return isHorizontalMove; } } public class Square { public readonly int row; public readonly int column; public PieceBase piece; public Square(int row, int column) { this.row = row; this.column = column; } public Square(int row, int column, PieceBase piece) { this.row = row; this.column = column; this.piece = piece; } public string GetDisplayCoordinates() { // 0 + 65 is the start of ascii uppercase characters // 65 + 32 is the start of ascii lowercase characters char rowCoordinate = Convert.ToChar(row + 65 + 32); return rowCoordinate + column.ToString(); } } public class Queen : PieceBase { public Queen() : base(PieceType.QUEEN) { } internal override bool IsValidMove(int sourceColumn, int sourceRow, int destColumn, int destRow) { bool isDiagonalMove = this._IsDiagonalMove(sourceColumn, sourceRow, destColumn, destRow); bool isVerticalMove = this._IsVerticalMove(sourceColumn, sourceRow, destColumn, destRow); bool isHorizontalMove = this._IsHorizontalMove(sourceColumn, sourceRow, destColumn, destRow); return isDiagonalMove || isVerticalMove || isHorizontalMove; } } </code></pre> <p>Below are the NUnit tests</p> <pre><code>[TestFixture] public class BoardTests { private Board chessBoard = new Board(); [Test] public void AllAvailableBishopMovesAreValid() { Square bishopStartSquare = new Square(4, 4, new Bishop()); List&lt;Square&gt; availableChessMoves = chessBoard.GetAvailableMoves(bishopStartSquare); foreach (Square availableMove in availableChessMoves) { bool isValidMove = this._IsDiagonalMove(bishopStartSquare, availableMove); Assert.IsTrue(isValidMove, "Move is not valid for Bishop from " + bishopStartSquare.GetDisplayCoordinates() + " to " + availableMove.GetDisplayCoordinates()); } } [Test] public void AllAvailableRookMovesAreValid() { Square rookStartSquare = new Square(4, 4, new Rook()); List&lt;Square&gt; availableChessMoves = chessBoard.GetAvailableMoves(rookStartSquare); foreach (Square availableMove in availableChessMoves) { bool isValidMove = this._IsVerticalMove(rookStartSquare, availableMove) || this._IsHorizontalMove(rookStartSquare, availableMove); Assert.IsTrue(isValidMove, "Move is not valid for Rook from " + rookStartSquare.GetDisplayCoordinates() + " to " + availableMove.GetDisplayCoordinates()); } } [Test] public void AllAvailableQueenMovesAreValid() { Square queenStartSquare = new Square(4, 4, new Queen()); List&lt;Square&gt; availableChessMoves = chessBoard.GetAvailableMoves(queenStartSquare); foreach (Square availableMove in availableChessMoves) { bool isValidMove = this._IsVerticalMove(queenStartSquare, availableMove) || this._IsHorizontalMove(queenStartSquare, availableMove) || this._IsDiagonalMove(queenStartSquare, availableMove); Assert.IsTrue(isValidMove, "Move is not valid for Queen from " + queenStartSquare.GetDisplayCoordinates() + " to " + availableMove.GetDisplayCoordinates()); } } [Test] public void AllAvailableKingMovesAreValid() { Square kingStartSquare = new Square(4, 4, new King()); List&lt;Square&gt; availableChessMoves = chessBoard.GetAvailableMoves(kingStartSquare); foreach (Square availableMove in availableChessMoves) { bool isValidMove = this._IsVerticalMove(kingStartSquare, availableMove) || this._IsHorizontalMove(kingStartSquare, availableMove) || this._IsDiagonalMove(kingStartSquare, availableMove); isValidMove = isValidMove &amp;&amp; this._HasMovedOnlyOneSquare(kingStartSquare, availableMove); Assert.IsTrue(isValidMove, "Move is not valid for King from " + kingStartSquare.GetDisplayCoordinates() + " to " + availableMove.GetDisplayCoordinates()); } } [Test] public void StartingSquareHasNoChessPiece() { Square startingSquare = new Square(1, 0); Exception ex = Assert.Throws&lt;Exception&gt;(() =&gt; chessBoard.GetAvailableMoves(startingSquare)); Assert.That(ex.Message == "Square must have a chess piece on it to get the available moves."); } #region utility methods private bool _IsDiagonalMove(Square sourceSquare, Square destSquare) { int destColumn = destSquare.column; int destRow = destSquare.row; int sourceColumn = sourceSquare.row; int sourceRow = sourceSquare.row; bool isDiagonalMove = Math.Abs(destColumn - sourceColumn) == Math.Abs(destRow - sourceRow); return isDiagonalMove; } private bool _IsVerticalMove(Square sourceSquare, Square destSquare) { int destColumn = destSquare.column; int destRow = destSquare.row; int sourceColumn = sourceSquare.row; int sourceRow = sourceSquare.row; bool isVerticalMove = sourceColumn == destColumn &amp;&amp; sourceRow != destRow; return isVerticalMove; } private bool _IsHorizontalMove(Square sourceSquare, Square destSquare) { int destColumn = destSquare.column; int destRow = destSquare.row; int sourceColumn = sourceSquare.row; int sourceRow = sourceSquare.row; bool isHorizontalMove = sourceRow == destRow &amp;&amp; sourceColumn != destColumn; return isHorizontalMove; } private bool _HasMovedOnlyOneSquare(Square sourceSquare, Square destSquare) { int destColumn = destSquare.column; int destRow = destSquare.row; int sourceColumn = sourceSquare.row; int sourceRow = sourceSquare.row; bool isRowMoveOne = sourceRow - destRow * 1 == 1; bool isColumnMoveOne = sourceColumn - destColumn * 1 == 1; return isRowMoveOne &amp;&amp; isColumnMoveOne; } #endregion } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T07:01:37.140", "Id": "466341", "Score": "0", "body": "Well I ended up getting the job :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T11:38:36.353", "Id": "466350", "Score": "0", "body": "Oh, yeah, interview for an actual job. Sorry, I wasn't trying to participate in that :) **Congratulations!** And yeah, I'm still implementing the chess game now and then, in between things. Castling and check validation are pretty tricky although it is now close to be done. Now for the computer chess player and the scoring system - I might not go that far." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T11:44:00.183", "Id": "466351", "Score": "0", "body": "`>B d7-d8 \n\nInvalid move because [a4] put the players king in check` :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T04:50:27.777", "Id": "466398", "Score": "0", "body": "Yeah I realized the day before the interview, should have done an edit of the post." } ]
[ { "body": "<p>Some quick remarks WRT style:</p>\n\n<ul>\n<li><p>Public properties should have at least a <code>{ get; }</code> (IMHO; I'm not a fan of <code>public readonly</code> and instead prefer <code>{ get; private set; }</code>) and should be PascalCase.</p></li>\n<li><p>Don't just throw any <code>Exception</code>, throw the correct one, e.g. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.argumentexception\" rel=\"nofollow noreferrer\"><code>ArgumentException</code></a>.</p></li>\n<li><p>Underscores should only be used to prefix class-wide private properties; certainly not methods.</p></li>\n<li><p>Do not assign a value only to return it on the next line. Combine those two lines into one.</p></li>\n<li><p>Do not pointlessly abbreviate: there's no need to use \"dest\" instead of \"destination\". It certainly doesn't make your code clearer.</p></li>\n<li><p>What is the point of allocating <code>destColumn</code>, <code>destRow</code>, <code>sourceColumn</code> and <code>sourceRow</code> in your \"utility\" methods? Why not simply use <code>destSquare.column</code> etc.?</p></li>\n<li><p>Use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\">string interpolation</a> instead of concatenation.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T14:12:56.173", "Id": "237440", "ParentId": "237356", "Score": "1" } }, { "body": "<p><strong>Design</strong><br/></p>\n\n<p>This is stage 1 of a project and there will be further stages with (presumably) new requirements coming in later stages.</p>\n\n<p>One of the things to think about when reviewing a design is how well it lends itself to extensions in the requirements.</p>\n\n<p>So let's think about some possible additional requirements for this project</p>\n\n<p>1) Add the knight and pawn pieces <br/>\n2) Allow for other pieces on the board (which will block moves)</p>\n\n<p>So how would we fit these requirements into the current design?</p>\n\n<p>Currently, ascertaining the valid moves is split between two classes</p>\n\n<ul>\n<li>The board, which asks the piece 'can you move here' for each location on the board.</li>\n<li>The piece, which reports whether or not it can move there.</li>\n</ul>\n\n<p>In the current implementation, the code for checking a particular kind of move (diagonal, horizontal, vertical) is in the base Piece class. </p>\n\n<p><strong>Add the Knight and Pawn</strong> <br/>\nWe add the two new sub classes. The pawn, especially, brings the current shape of checking each possible location and checking if it is valid into question. A pawn can move to one of three, maybe four places (one of two if we are ignoring other pieces). Checking every possible location to see if it is valid seems very wasteful. The knight has a relatively small number of possible valid moves and the check for these is unrelated to the existing diagonal, horizontal, vertical checks.</p>\n\n<p>We could just put the check in the Knight sub-class, say, <em>IsKnightMove()</em>. \nThis works but the irrelevant <em>IsDiagonalMove()</em>, <em>IsVerticalMove()</em>, <em>IsHorizontalMove()</em> routines in the base class sort of niggles. <br/></p>\n\n<p>As does the check every possible move to see if it is valid.</p>\n\n<p>Say we have an initial chess board set up and want to find the valid moves for each piece. Of the back-line pieces, only the knight can move, but we check every possible location for each piece and there is no way of pruning the checks because the possible moves are piece dependent.</p>\n\n<p>So how can we change the shape to fix some of the problems? <br/></p>\n\n<p>If we make each piece responsible for generating a list of places to which it can move (passing in the current board state - not used yet but we reckon, <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a> aside, that it is going to be needed) We can use our knowledge of how the pieces move to generate the possible moves and, if later needed, to adjust the checks based upon other pieces on the board. </p>\n\n<pre><code>public interface IChessPiece\n{\n BoardLocation CurrentLocation { get; set; }\n ChessPieceType Type { get; }\n IEnumerable&lt;Move&gt; GetValidMoves(ChessBoard board);\n}\n\npublic class BoardLocation\n{\n private const int BoardSize = 8;\n\n private static bool IsInRange(int pos)\n {\n return (pos &gt;= 1) &amp;&amp; (pos &lt;= BoardSize);\n }\n\n public BoardLocation(int row, int col)\n {\n if (!IsInRange(row))\n {\n throw new ArgumentOutOfRangeException(\"row\");\n }\n if (!IsInRange(col))\n {\n throw new ArgumentOutOfRangeException(\"col\");\n }\n Row = row;\n Column = col;\n }\n public int Row { get; }\n public int Column { get; }\n}\n\npublic class Move\n{\n public Move(IChessPiece piece, BoardLocation endingLocation)\n {\n Piece = piece ?? throw new ArgumentNullException(\"piece\");\n EndingLocation = endingLocation ?? throw new ArgumentNullException(\"endingLocation\");\n }\n public IChessPiece Piece { get; }\n public BoardLocation EndingLocation { get; }\n}\n</code></pre>\n\n<p><strong>NOTES:<br/></strong>\nWhen writing code we can hit problems with <em>how much is enough</em> (YAGNI exists for a reason). In the above, the board location is just a simple container for the row and column positions. It could also be responsible for formatting the position for display e.g. e4 or we could leave this up to an external formatter so that we could use the older notation (KP4). It could also be responsible for parsing an input string, or we could leave this to another class. The <em>Move</em> class could be omitted (just return a list of BoardLocations) but we may want to know the piece/move combinations.</p>\n\n<p>In a lot of cases it comes down to a Matter of Personal Preference (MoPP (tm)).</p>\n\n<p><strong>Finding valid moves</strong><br/>\nWith this shape we can use knowledge of how each piece moves to generate the possible moves (optionally using the board state). A pawn on d2 can now move to d3 or d4 (if nothing is in the way) or possibly take on c3 or e3 if there is something there or is taking <em>en passant</em></p>\n\n<p>A knight can generate the 2 to 6 possible moves it can make</p>\n\n<p>The King, Queen, Rook and Bishop can all generate their own possible moves in their respective classes.</p>\n\n<p>Shared functionality? The code for generating moves / checking if a move is valid can be shared but doesn't need to be in the base class, it could be in a shared utility class (again a MoPP, I don't like cluttering up a base class with code that is not used by all the sub classes).</p>\n\n<pre><code>public abstract class ChessPiece : IChessPiece\n{\n private BoardLocation _currentLocation;\n public BoardLocation CurrentLocation\n {\n get =&gt; _currentLocation;\n set =&gt; _currentLocation = value ?? throw new ArgumentNullException();\n }\n public abstract ChessPieceType Type { get; }\n public abstract IEnumerable&lt;Move&gt; GetValidMoves(ChessBoard board);\n}\n\npublic class King : ChessPiece\n{\n private readonly static int[][] MoveTemplates = new int[][]\n {\n new [] { 1, -1 },\n new [] { 1, 0 },\n new [] { 1, 1 },\n new [] { 0, -1 },\n new [] { 0, 1 },\n new [] { -1, -1 },\n new [] { -1, 0 },\n new [] { -1, 1 },\n\n };\n\n public override ChessPieceType Type =&gt; ChessPieceType.King;\n\n public override IEnumerable&lt;Move&gt; GetValidMoves(ChessBoard board)\n {\n return ChessMoveUtilities.GetMoves(board, this, 1, MoveTemplates);\n }\n}\n\npublic class Queen : ChessPiece\n{\n private readonly static int[][] MoveTemplates = new int[][]\n {\n new [] { 1, -1 },\n new [] { 1, 0 },\n new [] { 1, 1 },\n new [] { 0, -1 },\n new [] { 0, 1 },\n new [] { -1, -1 },\n new [] { -1, 0 },\n new [] { -1, 1 },\n\n };\n\n public override ChessPieceType Type =&gt; ChessPieceType.King;\n\n public override IEnumerable&lt;Move&gt; GetValidMoves(ChessBoard board)\n {\n return ChessMoveUtilities.GetMoves(board, this, board.Size, MoveTemplates);\n }\n}\n\ninternal static class ChessMoveUtilities\n{\n private static bool IsValid(ChessBoard board, BoardLocation current, int deltaRow, int deltaCol, out BoardLocation location)\n {\n location = null;\n var newRow = current.Row + deltaRow;\n if ((newRow &lt;= 0) ||(newRow &gt; board.Size)) return false;\n\n var newCol = current.Column + deltaCol;\n if ((newCol &lt;=0) || (newCol &gt; board.Size)) return false;\n\n location = new BoardLocation(newRow, newCol);\n return true;\n }\n\n internal static IEnumerable&lt;Move&gt; GetMoves(ChessBoard board, IChessPiece piece, int range, IEnumerable&lt;int[]&gt; mults)\n {\n if (board == null) throw new ArgumentNullException(\"board\");\n if (piece == null) throw new ArgumentNullException(\"piece\");\n if (range &lt; 1) throw new ArgumentOutOfRangeException(\"range\");\n if (mults == null || !mults.Any()) throw new ArgumentException(\"mults\");\n\n var ret = new List&lt;Move&gt;();\n\n foreach( var mult in mults)\n {\n for (var radius = 1; radius &lt;= range; radius++)\n {\n\n var deltaX = radius * mult[0];\n var deltaY = radius * mult[1];\n if(IsValid(board, piece.CurrentLocation, deltaX, deltaY, out BoardLocation newLocation))\n {\n ret.Add(new Move (piece, newLocation));\n }\n else\n {\n break;\n }\n }\n }\n return ret;\n\n }\n\n}\n</code></pre>\n\n<p><strong>Notes:</strong><br/>\nIt is possible (at the moment) to replace the individual classes for King, Queen, Rook and Bishop with instances of a common base class which takes in the ChessPieceType and MoveTemplates as parameters, but knowing about chess and thinking ahead, if we add in Castling and 'not moving into check' rules then the King and Rook need to be separate classes and merging the Queen and Bishop seems like overkill.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T10:32:56.340", "Id": "237487", "ParentId": "237356", "Score": "2" } }, { "body": "<blockquote>\n <p>Reviewer will be looking for correct functionality, use of design\n patterns, use of unit testing, use of object oriented programming,\n code re-use, etc. Each stage may be represented with a new project in\n the single solution.</p>\n</blockquote>\n\n<p>And </p>\n\n<blockquote>\n <p>Create a C# 7 .net core class library project with model classes for\n the chess pieces and the algorithms for determining the possible\n moves.</p>\n</blockquote>\n\n<p><strong>Requirements :</strong></p>\n\n<ul>\n<li>Design (how much do you enforce this concept in your work(mainly <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/object-oriented-programming\" rel=\"nofollow noreferrer\">OOP</a>).</li>\n<li>Functionality (how many bugs are there ? )</li>\n<li>Code Reuse (how much do you apply this concept?)</li>\n<li>Unit Test (how much do you use it ? ).</li>\n<li>C# 7 .NET Core (Familiarity with <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7\" rel=\"nofollow noreferrer\">C# 7 updates</a> and <a href=\"https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0\" rel=\"nofollow noreferrer\">.NET Core updates</a>)</li>\n<li>Model Classes (this is important)</li>\n<li>algorithms for determining the possible moves. (this would show how do you handle code complicity).</li>\n</ul>\n\n<p><strong>At this stage :</strong></p>\n\n<p>You're missing some of the requirements (some headlines). </p>\n\n<ul>\n<li>Naming convention (like <code>Board</code>, <code>Square</code> ..etc).</li>\n<li>Models (no models)</li>\n<li>Algorithms (more on that is below)</li>\n<li>Missing some fundamental game logic (like pieces sets (white, black)).</li>\n<li>Missing Code Flexibility (will be not feasible to add more requirements).</li>\n<li>Comments (something you want to consider all along). </li>\n</ul>\n\n<p>Currently, I believe most of code parts can be improved.</p>\n\n<p><strong>Chess Rules</strong></p>\n\n<p>We need to know the basic requirements : </p>\n\n<ul>\n<li>Board is a grid of 8x8 squares (total of 64 square).</li>\n<li>It has two groups (black/white) of (one king, queen, and two kights, rooks, bishops, and 8 pawns).</li>\n<li>Game starts with 2 moves</li>\n<li>Each piece set has its own movements rules\n\n<ul>\n<li>King : One Step on (Vertical,Horizontal,Diagonal) directions</li>\n<li>Queen : Open-Steps on (Vertical,Horizontal,Diagonal) directions</li>\n<li>Rook : Open-Steps on (Vertical,Horizontal) directions</li>\n<li>Bishop : Open-Steps on (Diagonal) directions</li>\n<li>Knight : 3 Steps in <code>L</code>Shape directions</li>\n<li>Pawn : One-Step (Vertical) and can go One-Step (Diagonal) to eliminate another piece.</li>\n</ul></li>\n</ul>\n\n<p>So, based on that we need :</p>\n\n<ul>\n<li><code>ChessBoard</code> : To hold the layout, pieces, positions, and the default startup game settings. </li>\n<li><code>ChessPiece</code> : Model which will hold each piece information plus the location. </li>\n<li><code>ChessPieceMove</code> class to hold the movement logic and used on moving the pieces, you can also name it <code>ChessPieceMovement</code>.</li>\n<li><code>IChessPieceType</code> an inteface which would be implemented on each piece type.</li>\n<li><code>ChessPieceKing</code>, <code>ChessPieceQueen</code>, <code>ChessPieceRook</code>, <code>ChessPieceKnight</code> ..etc. a class for each piece, which inherits <code>IChessPieceType</code>.</li>\n</ul>\n\n<p>All of these are just the base requirements, we still need to implement game rule handler to be easier to add new requirements in the upcoming stages. </p>\n\n<p>For now, we will make <code>ChessBoard</code> the main class to initiate a new game. </p>\n\n<pre><code>public class ChessBoard\n{\n // Initiate a private new ChessPiece array\n private ChessPiece[] pieces = new ChessPiece[64];\n\n\n public ChessBoard()\n {\n // callback the initiation process\n Initiate();\n }\n\n // initiation process (To initiate the ChessPiece compenents)\n private void Initiate() { ... }\n\n // Dummy : To get the on-board pieces (playable peices)\n public IEnumerable&lt;ChessPiece&gt; GetAvailablePieces() { ... }\n\n // Dummy : To get the open-squares that can accept new ChessPiece \n public IEnumerable&lt;int&gt; GetAvailablePositions(){ ... }\n}\n\n// Model \npublic class ChessPiece\n{\n // Enum : To define a color for each piece.\n public ChessPieceColor Color { get; set; }\n\n // stores piece's position\n public int Position { get; set; }\n\n // stores piece type or kind (Rook, Bishop, Knight, Queen, King, or Pawn) \n // Note : they're concrete classes sharing the same interface\n public IChessPieceType PieceType { get; set; }\n\n // a flag to distinguish the playable pieces from the elementated ones\n public bool IsDistroyed { get; set; }\n\n public ChessPiece() { }\n\n public ChessPiece(int position, ChessPieceColor color, IChessPieceType pieceType) \n {\n Color = color;\n Position = position;\n PieceType = pieceType;\n }\n}\n</code></pre>\n\n<p>When initiate a new board, it should initiate an array of <code>ChessPiece</code> with length of 64 elements. Which is the total number of board squares. While using <code>ChessPiece</code> it would make it easier to just add the model in each element and then loop over them.</p>\n\n<p>This is simple enough. Now, we need to setup the startup pieces, but we need to visualize the grid and see which element index in the array should have a actual piece at startup, and which element should be null. Because we're dealing with a fixed rule here, which would be easy enough to just number the elements on-top of a chess grid. From top-left-corner to the bottom-left-corner it would holds elements from 0 to 63. Using these we can figure out which index should have an item.</p>\n\n<p>So, in your board initiation process you should have something like : </p>\n\n<pre><code>private void Initiate()\n{\n IChessPieceType chessPiece = null;\n ChessPieceColor color = ChessPieceColor.Undefined;\n\n for (int x = 0; x &lt; pieces.Length; x++)\n {\n // colors \n switch (x)\n {\n case 0:\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n color = ChessPieceColor.White;\n break;\n case 56:\n case 57:\n case 58:\n case 59:\n case 60:\n case 61:\n case 62:\n case 63:\n color = ChessPieceColor.Black;\n break;\n }\n\n // pieces\n switch (x)\n {\n case 0:\n case 7:\n case 56:\n case 63:\n chessPiece = new ChessPieceRook(x);\n break;\n case 1:\n case 6:\n case 57:\n case 62:\n chessPiece = new ChessPieceKnight(x);\n break;\n case 2:\n case 5:\n case 58:\n case 61:\n chessPiece = new ChessPieceBishop(x);\n break;\n case 3:\n case 59:\n chessPiece = new ChessPieceQueen(x);\n break;\n case 4:\n case 60:\n chessPiece = new ChessPieceKing(x);\n break;\n }\n\n // Pawns\n if ((x &gt;= 8 &amp;&amp; x &lt;= 15) || (x &gt;= 48 &amp;&amp; x &lt;= 55))\n {\n color = x &gt;= 8 &amp;&amp; x &lt;= 15 ? ChessPieceColor.White : ChessPieceColor.Black;\n chessPiece = new ChessPiecePawn(x);\n }\n\n pieces[x] = new ChessPiece(x, color, chessPiece);\n }\n}\n</code></pre>\n\n<p>Doing that, would setup the board and its pieces. We can also get the available positions (empty squares) like this : </p>\n\n<pre><code>public IEnumerable&lt;int&gt; GetAvailablePositions()\n{\n for (int x = 0; x &lt; pieces.Length; x++)\n {\n if (pieces[x] == null) { yield return x; }\n }\n}\n</code></pre>\n\n<p>From there, we can implement <code>ChessPieceMove</code> which will be used internally with the pieces. Since we are using one-dimensional array, it's a matter of simple math to know which and where the next move. </p>\n\n<pre><code>public class ChessPieceMove\n{\n private const int MAX_ROW_SIZE = 8;\n\n private const int MAX_COLUMN_SIZE = 8;\n\n private int _position;\n\n private int _row;\n\n private int _column;\n\n public ChessPieceMove(int position)\n {\n Move(position, 0);\n }\n\n private void Move(int steps)\n {\n Move(_position, steps);\n }\n\n private void Move(int position, int steps)\n {\n _position = position + steps;\n _column = _position % MAX_COLUMN_SIZE;\n _row = (MAX_COLUMN_SIZE - _column + _position) / MAX_ROW_SIZE;\n }\n\n public ChessPieceMove Forward(int steps)\n {\n Move(steps * 8);\n return this;\n }\n\n public ChessPieceMove Backward(int steps)\n {\n Move(steps * 8 * -1);\n return this;\n }\n\n public ChessPieceMove Left(int steps)\n {\n Move(steps * -1); \n return this;\n }\n\n public ChessPieceMove Right(int steps)\n {\n Move(steps);\n return this;\n }\n\n public ChessPieceMove Oppsite()\n {\n _position = ((MAX_ROW_SIZE - _row + 1) * MAX_ROW_SIZE) - (MAX_COLUMN_SIZE - _column);\n return this;\n }\n\n public int Save()\n {\n return _position;\n }\n\n}\n</code></pre>\n\n<p>This class can be used to get the element index for next move like : </p>\n\n<pre><code>// Move a Knight example : \nvar index = new ChessPieceMove(12).Forward(2).Right(1).Save();\n// returns index 29\n</code></pre>\n\n<p>So, this <code>ChessPieceMove</code> simple API would be very helpful to retrieve the element index. You can get the opposite index which is the square index that faces the current from the opponent view. TO get that you can use <code>Oppsite()</code> like : </p>\n\n<pre><code>// Move a Knight example : \nvar index = new ChessPieceMove(12).Forward(2).Right(1).Oppsite().Save();\n// returns index 37\n</code></pre>\n\n<p>So, square number 29 from player 1 view is equal to square number 37 from player 2 view.</p>\n\n<p>For the pieces, you would use an interface : </p>\n\n<pre><code>public interface IChessPieceType\n{\n int Position { get; set; }\n}\n</code></pre>\n\n<p>and implement the pieces classes like : </p>\n\n<pre><code>public class ChessPiecePawn : IChessPieceType\n{\n\n public int Position { get; set; }\n\n public ChessPiecePawn(int position)\n {\n Position = position;\n }\n\n public int MoveForward()\n { \n return new ChessPieceMove(Position).Forward(1).Save();\n }\n public int MoveDiagonalRightFoward()\n {\n return new ChessPieceMove(Position).Forward(1).Right(1).Save();\n }\n public int MoveDiagonalLeftFoward()\n {\n return new ChessPieceMove(Position).Forward(1).Left(1).Save();\n }\n}\n</code></pre>\n\n<p>Now, you can use <code>ChessPiecePawn</code> for instance, on the board, and get the move index, validate it, and execute the process you need (e.g. change the current index to the new one, return an error since it's not valid ...etc). </p>\n\n<p>I have intentionally left off the validation process in the above codes for demonstration purpose. So, you have something you can work on and make your own project. </p>\n\n<p>A few notes on the above process : </p>\n\n<ul>\n<li>You have fixed 64 elements, so do some validation on that </li>\n<li>some elements on the board would be out-of-range movements (for instance index 7 cannot accept <code>Right</code> move as it's on the board's edge. </li>\n<li>Make use of generic interfaces like <code>IEnumerable</code> and <code>IDisposable</code> this is a must use.</li>\n<li>You can implement another interface or abstract class for the movements class. </li>\n<li><p>using <code>const</code> at this stage is just for <code>Readability</code> purpose.</p></li>\n<li><p>for validations, start with the standard validations, then go for game validation. </p></li>\n<li>Keep in mind that you would need a wrapper class to wrap your project like <code>ChessGame</code> so it would be more appropriate to initiate the game instead of calling <code>ChessBoard</code>. This wrapper can also have new functionalities, like specifying players name or timing ..etc.</li>\n<li><p>Keep it simple and open for new requirements. </p></li>\n<li><p><strong>MOST IMPORTANTLY TAKE NOTES OF OTHER ANSWERS AS EACH ANSWER COVERS SOME PART OF YOUR QUESTION</strong> . gathering all answers points would give you a full answer.</p></li>\n</ul>\n\n<p>I hope this would benefit you, and I wish you a good luck on your upcoming job. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T06:36:45.633", "Id": "237738", "ParentId": "237356", "Score": "1" } } ]
{ "AcceptedAnswerId": "237487", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T03:30:09.053", "Id": "237356", "Score": "1", "Tags": [ "c#" ], "Title": "Chess Model in C# to GetAvailableMoves" }
237356
<p>I'm trying to set up some code to first test if the Vanilla JavaScript <code>.animate()</code> API is Supported, then if it's not check if <code>requestAnimationFrame</code> is supported and if it's not fallback to either <code>setTimeout</code>, <code>setInterval</code> or <code>setImmediate</code>.</p> <p>I've been reading this e-book on google <a href="https://books.google.co.uk/books?id=mrOV4XzstOQC&amp;pg=PA100&amp;lpg=PA100&amp;dq=mozAnimate()&amp;source=bl&amp;ots=qXmFP64H7s&amp;sig=ACfU3U12ACjbnBTwBSFpADAWfr_tj4rheQ&amp;hl=en&amp;sa=X&amp;ved=2ahUKEwj_o6iL4tXnAhUkQUEAHf5CBlAQ6AEwAHoECAcQAQ#v=onepage&amp;q=mozAnimate()&amp;f=false" rel="nofollow noreferrer">Smashing Webkit</a>, which says that its always best practice to check for feature support before actually implementing it, so I'm trying to move all my App Animations inside of the checks below, and then implement fallbacks for backwards compatibility and older browsers.</p> <p>I'm not 100% sure if this has any security concerns as I'm not a web security expert nor am I an expert coder by any standards. I'm still trying to learn JS and am wondering if this code block could be made better, more secure or to run more optimally i.e. removing unnecessary <code>if</code> statements or reworking the code so it is less verbose.</p> <pre><code> document.addEventListener(&quot;DOMContentLoaded&quot;,(()=&gt; { // ::&gt;&gt;. Notes:: ...................... // ::&gt;&gt;. A Handy Function to get the Browser Prefix ~ // Gets the browser prefix var brsrPrefix; navigator.sayswho= (function(){ var N = navigator.appName, ua = navigator.userAgent, tem; var M = ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i); if(M &amp;&amp; (tem = ua.match(/version\/([\.\d]+)/i))!= null) M[2] = tem[1]; M = M? [M[1], M[2]]: [N, navigator.appVersion,'-?']; M = M[0]; if(M == &quot;Chrome&quot;) { brsrPrefix = &quot;webkit&quot;; } if(M == &quot;Firefox&quot;) { brsrPrefix = &quot;moz&quot;; } if(M == &quot;Safari&quot;) { brsrPrefix = &quot;webkit&quot;; } if(M == &quot;MSIE&quot;) { brsrPrefix = &quot;ms&quot;; } })(); // ::&gt;&gt;. A Handy Function to get the Browser Prefix ~ try{ if(window.animate){ console.log('.animate() API is Supported') // My Current Animations will be in here. } if(window.requestAnimationFrame){ console.log('RequestAF is Supported') // 1st fallback in here. } if(!window.requestAnimationFrame) { window.requestAnimationFrame = window.setImmediate } else { let requestAnimationFrame= window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { return window.setTimeout(callback, 1000/60) }; console.log(requestAnimationFrame); } } // ::&gt;&gt;. Closing Bracket for First Try Catch............. catch(err){ console.log(err) } // ::&gt;&gt;. Closing Bracket for First Catch............. // ::&gt;&gt;. RequestAnimation FramePolyFill (function() { var lastTime = 0; var vendors = ['webkit', 'moz', 'ms']; for(var x = 0; x &lt; vendors.length &amp;&amp; !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); // ::&gt;&gt;. RequestAnimation FramePolyFill })) </code></pre> <p>My concerns with the code is that I copied the first snippet from a blog post and I don't fully understand the RegEx that is used within it. I'm finding Regex very, very difficult to learn and is kinda confusing. Can anyone point out to me what <code>tem</code> and <code>ua</code> mean? I'm guessing <code>ua</code> is shorthand for user-agent.</p> <p>Also, the code above is repeating itself in that its declaring var brsrPrefix &amp; also var vendors = ['webkit', 'moz', 'ms']; Will look into trying to attempt to merge these two functions and compact the code as much as I can.</p> <p>In my try catch if else statement it's checking to see if <code>window.requestAnimationFrame</code> is supported and then if it's not, its setting let <code>requestAnimationFrame</code> to be any of the browser specific versions. However, if I attempted to call or attach this let to an item it would end up being <code>element.window.requestAnimationFrame</code> which is the wrong syntax.</p> <p>Also, Firefox Quantum supports the experimental <code>.animate()</code> API (not the jQuery version) but it is not console logging anything for this part, only logs that RAF is enabled.</p> <p>Is this far too much code, just for doing a simple task such as checking browser support?</p> <p>No errors in console so far. Can anyone help and review this and post meaningful comments so I can learn better and become a better developer?</p> <p>ideally the code would test support for:</p> <pre><code> -&gt; .animate() -&gt; .requestAnimationFrame() -&gt; .setInterval() -&gt; .setTimeout() -&gt; .setImmediate </code></pre> <p>in that Order, and Append Browser prefix Where necessary, but might have to research a whole lot more.</p> <p>this post looks like it will be handy for reference <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Detecting_CSS_animation_support" rel="nofollow noreferrer">Detecting_CSS_animation_support</a> its has a similar implementation with Js, &amp; Another Js Script on GitHub Similar <a href="https://gist.github.com/Integralist/3938408" rel="nofollow noreferrer">Detect CSS Animation support and provide object of normalised properties</a></p> <p>Here is a new question I asked with Similar Theme but A different Implementation to try and Achieve the same end goal, Using Switch statements instead:<br /> <a href="https://codereview.stackexchange.com/questions/238500/javascript-anime-support-switch-statement-for-animate-api">Javascript Anime Support Switch Statement for .animate() Api</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T19:00:34.000", "Id": "466368", "Score": "0", "body": "Still gonna wait for a little while before I decide to mark any answers as the right answer as I like to see what other people have to say aswell. not 100% I've got it down as the right approach yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T21:39:30.310", "Id": "467756", "Score": "1", "body": "\"_My concerns with the code is that I copied the first snippet from a blog post and I don't fully understand the RegEx that is used within it. I'm finding Regex very, very difficult to learn and is kinda confusing. Can anyone point out to me what tem and ua mean? guessing ua is shorthand for user-agent._\" - this is not on-topic for this site. [\"_For licensing, moral, and procedural reasons, we cannot review code written by other programmers. We expect you, as the author, to understand why the code is written the way that it is._\"](https://codereview.stackexchange.com/help/on-topic)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T21:46:34.157", "Id": "467757", "Score": "0", "body": "@Sᴀᴍ Onᴇᴌᴀ I do understand `Why` the code is wriiten the way it is, I understand also why regex has been used, but it is like an alien language to me & struggleing to learn it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T21:47:38.400", "Id": "467759", "Score": "0", "body": "The Same as Javascript was when I first Started learning that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-06T21:50:19.847", "Id": "467761", "Score": "0", "body": "& Technically speaking `All` Code, ever written is or has been previously written by someone else..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-07T08:14:10.497", "Id": "467790", "Score": "0", "body": "The point is that reviewers aren't here to explain what your code does, as the reviewee it's *your* job to tell the reviewers what your code does, like `ua` and `tem` being local variables, `ua` for `navigator.userAgent`, and `tem` to hold a *temporary* collection of regex matches... but none of that is on-topic here, is what Sam was correctly pointing out; that's why we ask that it's *your* code under review. Side note, did you mean to post [the updated code](https://codereview.stackexchange.com/a/238443/23788) as a [follow-up](https://codereview.meta.stackexchange.com/q/1065/23788) question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-07T09:31:27.423", "Id": "467793", "Score": "0", "body": "@Mathieu Guindon yes that was my updated attempt after learning more & trying to incorporate Answerrs & comments." } ]
[ { "body": "<p>Firstly, before I start, I'd like to mention that you might not need these JS animation functions. A lot of animations can be achieved through CSS transitions and keyframes, using JS to toggle classes where needed. In my opinion, JS should only step in when the animation becomes too intensive for CSS to handle.</p>\n\n<p>There appears to be a lot of duplication here. I'm going to simplify a lot of it for these reasons:</p>\n\n<ul>\n<li>requestAnimationFrame has <a href=\"https://caniuse.com/#feat=requestanimationframe\" rel=\"nofollow noreferrer\">great browser support</a> and shouldn't need to be polyfilled. That said, I do still like consolidating the browser prefixed versions into one just to be on the safe side.</li>\n<li>Most functionality is standardised so you shouldn't need to know the browser prefix.</li>\n<li>Your support checks should exist separately to your animation code, meaning they can be reused for multiple animation blocks.</li>\n</ul>\n\n<p>The support checks look like this (include at the top of your file):</p>\n\n<pre><code>// test for Web Animations API (.animate) support\n// test from Modernizr.js\nconst WEB_ANIMATIONS_API_SUPPORTED = 'animate' in document.createElement('div');\n\n// consolidate browser prefixed versions into one function\nlet requestAnimationFrame = (\n window.requestAnimationFrame ||\n window.mozRequestAnimationFrame ||\n window.webkitRequestAnimationFrame ||\n window.msRequestAnimationFrame ||\n function(callback) {\n return window.setTimeout(callback, 1000 / 60)\n }\n);\n</code></pre>\n\n<p>Then when you want to create an animation, you can do:</p>\n\n<pre><code>if ( WEB_ANIMATIONS_API_SUPPORTED ) {\n // your .animate call\n} else {\n requestAnimationFrame(function() {\n // your fallback function\n });\n}\n</code></pre>\n\n<hr>\n\n<p>I'll also try and answer your other questions as best as I can here.</p>\n\n<blockquote>\n <p>its always best practice to check for feature support before actually\n implementing it,</p>\n</blockquote>\n\n<p>Absolutely correct and it's a very good practice to get into.</p>\n\n<blockquote>\n <p>and then implement fallbacks for backwards compatibility and older\n browsers.</p>\n</blockquote>\n\n<p>Again this is the best way to handle using new functionality. It's called progressive enhancement - use the lowest level technology to build a base experience and then enhance if the newer functions are available.</p>\n\n<blockquote>\n <p>I'm not 100% sure if this has any security concerns</p>\n</blockquote>\n\n<p>I can reliably say there are no security concerns here. If you want to know more about security in JS start by reading around XSS vulnerabilities.</p>\n\n<p>Regex can be difficult to learn and even experienced devs struggle with it. I like to use a visual interface like <a href=\"https://regexr.com/\" rel=\"nofollow noreferrer\">https://regexr.com/</a> to see the matches in real time. You can also hover over each regex character to see what it means and how it interacts with characters before and after it.</p>\n\n<p>Yes, <code>ua</code> is shorthand for User Agent, and <code>tem</code> appears to be short for temporary. It's only used to quickly hold the matches from the Regex. Personally, I hate this style of variable naming and always go for longer, self-documenting ones where possible.</p>\n\n<p>As you mention the browser prefix is repeating itself. This is likely because the <code>requestAnimationFrame</code> polyfill you're using is a packaged polyfill, and comes with it's own browser prefix checking. If you were doing a lot of tests, then it would make sense to abstract this out to a separate browser prefixing function.</p>\n\n<blockquote>\n <p>However, if I attempted to call or attach this let to an item it would\n end up being element.window.requestAnimationFrame which is the wrong\n syntax.</p>\n</blockquote>\n\n<p>I'm not sure what you mean here. If you can give me more info, I'll try and provide an answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T01:38:35.247", "Id": "465812", "Score": "0", "body": "Tyler Thanks for the Answer, I will read through it fully in a short while, I'm trying to use Js instead of Pure Css As Css does not generally match the browsers refresh rate as far as I know, & you don't get as much control or customization through pure css." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T01:43:33.123", "Id": "465814", "Score": "0", "body": "Good response, much appreciated. Ideally I would like to move 'All' my animations into there own worker thread, and just have the browser support checks in my main .js file. But I'm still a far way away from learning all of that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T01:45:17.423", "Id": "465815", "Score": "0", "body": "Do i need to include Modernizr.js for that test to work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T02:10:19.997", "Id": "465816", "Score": "0", "body": "also the reasoning behind trying to use .animate() is because this is the newer version and is More Performant than requestAnimationFrame which in turn is Better suited to animation than Pure CSS. I understand your point that for basic non cpu/gpu animations I can just stick with Css, but the ones I was attempting are very Cpu intensive. Sorry for calling you Tyler. lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T10:42:17.107", "Id": "465857", "Score": "0", "body": "No you don't need to include Modernizr for that - I extracted the relevant parts, so that'll run as a one-liner" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T19:02:04.030", "Id": "466369", "Score": "0", "body": "what does the `in` part do, could you explain this a bit more, not sure i fully understand how that works." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T16:30:53.367", "Id": "466462", "Score": "0", "body": "It checks if an `animate` property is present on the `Element` interface by creating a temporary `div`. If that property exists then we can say the browser supports that feature." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T00:03:06.867", "Id": "237522", "ParentId": "237357", "Score": "4" } }, { "body": "<p>This is the Secondary Attempt that I have made &amp; will Add more to it when I have learnt a bit more JS</p>\n\n<pre><code> let webAnimationsSupport = (window.Element.prototype.animate !== undefined);\n let rafSupport = (window.requestAnimationFrame !== undefined);\n let cssFallback = false;\n\n switch(webAnimationsSupport ? 'true' : 'false'){\n case \"true\":\n // Run .animate() functions as normal via Callbacks.\n console.log('.animate(); = true');\n break;\n case \"false\":\n console.log('.animate(); Support = false');\n animeFallBack();\n // Move onto requestAnimationFrame();\n break;\n\n default:\n // Default to Css Fallback. ie ``Add Back in the Classes`` That governed the original Animation.\n }\n function animeFallBack(){\n switch(rafSupport ? 'true' : 'false'){\n case \"true\":\n // .animate Not Supported Fallback to `request animation frame`.\n // Add Callback here which holds RAF Anime Code.\n console.log('.raf(); = true');\n break;\n case \"false\":\n // Fallback option or alert enable Js\n console.log('.raf(); = false');\n let requestAnimationFrame = (\n window.requestAnimationFrame ||\n window.mozRequestAnimationFrame ||\n window.webkitRequestAnimationFrame ||\n window.msRequestAnimationFrame ||\n function(callback) {\n return window.setTimeout(callback, 1000 / 60)\n }\n );\n break;\n\n default:\n // Default to Css Fallback.\n }\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T10:12:51.627", "Id": "467942", "Score": "1", "body": "What's up with those `switch`statements? The comments seem to indicate that the `default` clause can be executed, however that is not the case, so they could just be removed. The mapping to `\"true\"`/`\"false\"` strings is strange. Boolean values can be used just as well: `switch (!!rafSupport) { case true: /* ... */ case false: /*...*/`. But why not just use an `if`/`else` statement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T12:18:18.047", "Id": "467955", "Score": "0", "body": "@RoToRa Only tried to use switch statement because i'm trying to learn Javascript & these were something that I had not learnt yet. Maybe needs refactoring alot but I prefer them to if/else's for some reason." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T17:38:42.473", "Id": "467993", "Score": "0", "body": "@RotoRa you could (and should) add those comments in an answer to [the follow-up question](https://codereview.stackexchange.com/q/238500/120114) where this code appears." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T20:10:58.573", "Id": "467996", "Score": "0", "body": "@RoToRa this secondary attempt was just a work in progress & still needs refactoring. Probably Might get it correct on the 3rd, 4th, 5th, 6th or 8th attempt." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-05T17:36:47.453", "Id": "238443", "ParentId": "237357", "Score": "0" } }, { "body": "<h1>Initial thoughts</h1>\n\n<p>Looking at the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/animate\" rel=\"nofollow noreferrer\">MDN documentation for <code>Element.animate()</code></a> I see this warning at the top:</p>\n\n<blockquote>\n <p><strong>This is an <a href=\"https://developer.mozilla.org/en-US/docs/MDN/Contribute/Guidelines/Conventions_definitions#Experimental\" rel=\"nofollow noreferrer\">experimental technology</a></strong><br>\n Check the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/animate#Browser_compatibility\" rel=\"nofollow noreferrer\">Browser compatibility table</a> carefully before using this in production.</p>\n</blockquote>\n\n<p>Looking at that compatibility table we see it isn't supported at all by a couple browsers...</p>\n\n<p><a href=\"https://i.stack.imgur.com/Uz8p9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Uz8p9.png\" alt=\"browser compatibility\"></a></p>\n\n<p>I searched for \"<em>navigator.sayswho</em>\" online and found snippets like <a href=\"https://gist.github.com/msrafi/5135669\" rel=\"nofollow noreferrer\">this gist</a> that matches most of the first function, and I also see <a href=\"https://gist.github.com/paulirish/1579671\" rel=\"nofollow noreferrer\">this gist for the requestAnimationFrame polyfill\n by Paul Irish</a>. I read over the comments and noted <a href=\"https://gist.github.com/paulirish/1579671#gistcomment-2976376\" rel=\"nofollow noreferrer\">the comment 7/21/2019 by jalbam</a> claims to have an adaptation that has improved performance. I haven't tested it out but it may work slightly better than the original.</p>\n\n<p>My conclusion is that you basically wrapped those two snippets in a DOM loaded callback (and perhaps modified the variable name <code>browserPrefix</code> to <code>brsrPrefix</code>. </p>\n\n<blockquote>\n <p>\"...<em>am wondering if this code block could be made better, more secure or to run more optimally i.e. removing unnecessary <code>if</code> statements or reworking the code so it is less verbose</em>\"</p>\n</blockquote>\n\n<p>It seems that the first snippet is pointless because: </p>\n\n<ul>\n<li>nothing is returned from the IIFE that is used to assign <code>navigator.sayswho</code> and thus that is <code>undefined</code>, and</li>\n<li><code>brsrPrefix</code> doesn’t appear to be used and its scope is limited to the anonymous/lambda function/closure passed to the DOM loaded event handler.</li>\n</ul>\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>document.addEventListener(\"DOMContentLoaded\",(()=&gt; {\n // ::&gt;&gt;. Notes:: ......................\n // ::&gt;&gt;. A Handy Function to get the Browser Prefix ~\n // Gets the browser prefix\n var brsrPrefix;\n navigator.sayswho= (function(){\n var N = navigator.appName, ua = navigator.userAgent, tem;\n var M = ua.match(/(opera|chrome|safari|firefox|msie)\\/?\\s*(\\.?\\d+(\\.\\d+)*)/i);\n if(M &amp;&amp; (tem = ua.match(/version\\/([\\.\\d]+)/i))!= null) M[2] = tem[1];\n M = M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];\n M = M[0];\n if(M == \"Chrome\") { brsrPrefix = \"webkit\"; }\n if(M == \"Firefox\") { brsrPrefix = \"moz\"; }\n if(M == \"Safari\") { brsrPrefix = \"webkit\"; }\n if(M == \"MSIE\") { brsrPrefix = \"ms\"; }\n })();\n \n console.log(' inside DOM Loaded callback - brsrPrefix', brsrPrefix, 'navigator.sayswho: ', navigator.sayswho);\n}))\nsetTimeout(function() {\nconsole.log(' outside DOM Loaded callback - brsrPrefix', brsrPrefix, 'navigator.sayswho: ', navigator.sayswho);\n}, 3000);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><a href=\"https://medium.com/hackernoon/polyfills-everything-you-ever-wanted-to-know-or-maybe-a-bit-less-7c8de164e423\" rel=\"nofollow noreferrer\">This hackernoon article about polyfills and transpilers</a> might likely be interesting.</p>\n\n<h1>Suggestions</h1>\n\n<h2>Avoid Es6 features when attempting to target older browsers</h2>\n\n<p>The first thing I noticed is that the first line contains an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">arrow function expression</a>: </p>\n\n<blockquote>\n<pre><code> document.addEventListener(\"DOMContentLoaded\",(()=&gt; {\n</code></pre>\n</blockquote>\n\n<p>Bear in mind the browser support for those- some browsers that <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/animate#Browser_compatibility\" rel=\"nofollow noreferrer\">wouldn’t support <code>Element.animate()</code></a> but would support <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame#Browser_compatibility\" rel=\"nofollow noreferrer\"><code>requestAnimationFrame()</code></a> would not support the syntax of an arrow function. </p>\n\n<p>I tried running the code as is in IE 11 but set to emulate version 10 (both in Document mode and user agent string) since version 10 is the earliest version to support <code>requestAnimationFrame()</code>. </p>\n\n<p><a href=\"https://i.stack.imgur.com/AGULl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AGULl.png\" alt=\"emulation mode in IE 11\"></a></p>\n\n<p>It showed a syntax error in the console:</p>\n\n<p><a href=\"https://i.stack.imgur.com/9kZuF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9kZuF.png\" alt=\"syntax error in IE 10 emulation\"></a></p>\n\n<p>There is another es6 feature that leads to an error in IE version 10 and earlier: the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Browser_compatibility\" rel=\"nofollow noreferrer\"><code>let</code></a> keyword is used:</p>\n\n<blockquote>\n<pre><code> let requestAnimationFrame= window.requestAnimationFrame ||\n window.mozRequestAnimationFrame ||\n window.webkitRequestAnimationFrame ||\n window.msRequestAnimationFrame ||\n function(callback) {\n return window.setTimeout(callback, 1000/60)\n };\n</code></pre>\n</blockquote>\n\n<p>Note the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Browser_compatibility\" rel=\"nofollow noreferrer\">browser support for that keyword</a>. So use a <a href=\"https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function\" rel=\"nofollow noreferrer\">traditional function expression</a> instead of an arrow function and the <code>var</code> keyword instead of <code>let</code>.</p>\n\n<h2>Users can modify the User agent of their browser</h2>\n\n<p>As described above with the IE 10/11 test, users can modify the user agent - including a completely different vendor - <a href=\"https://www.howtogeek.com/113439/how-to-change-your-browsers-user-agent-without-installing-any-extensions/\" rel=\"nofollow noreferrer\">this post describes how to change the user agent in Chrome, Firefox and Safari</a>. Because of this it is best to limit dependence on detection using the user agent string.</p>\n\n<h2>Browser support for <code>addEventListener()</code></h2>\n\n<p>Another thing to consider is the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Browser_compatibility\" rel=\"nofollow noreferrer\">browser support for <code>addEventListener()</code></a></p>\n\n<blockquote>\n <p>In Internet Explorer versions before IE 9, you have to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/attachEvent\" rel=\"nofollow noreferrer\"><code>attachEvent()</code></a>, rather than the standard <code>addEventListener()</code>. For IE, we modify the preceding example to:</p>\n\n<pre><code>if (el.addEventListener) {\n el.addEventListener('click', modifyText, false); \n} else if (el.attachEvent) {\n el.attachEvent('onclick', modifyText);\n}\n</code></pre>\n</blockquote>\n\n<p><sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Legacy_Internet_Explorer_and_attachEvent\" rel=\"nofollow noreferrer\">2</a></sup></p>\n\n<p>If you want to support those versions of IE then you would likely want to modify the code to add the DOM-loaded callback accordingly. Note that whle IE supports <code>DOMContentLoaded</code> starting with version 9<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event#Browser_compatibility\" rel=\"nofollow noreferrer\">3</a></sup>, <a href=\"https://stackoverflow.com/q/24904010/1575353\">events tied to that event don't always get triggered in IE</a>. You may have to do something like this:</p>\n\n<pre><code>function checkBrowser() {\n // code currently in the anonymous callback to ocument.addEventListener(\"DOMContentLoaded\"\n}\n\n// in case the document is already rendered\nif (document.readyState!='loading') checkBrowser();\n// modern browsers\nelse if (document.addEventListener) document.addEventListener('DOMContentLoaded', checkBrowser);\n// IE &lt;= 8\nelse document.attachEvent('onreadystatechange', function(){\n if (document.readyState=='complete') checkBrowser();\n});\n</code></pre>\n\n<p>-from <a href=\"https://plainjs.com/javascript/events/running-code-when-the-document-is-ready-15/\" rel=\"nofollow noreferrer\">plainJS.com</a></p>\n\n<p>Are you sure that code needs to be executed after the DOM has loaded? if not, it could be put into an IIFE to preserve the scope limitation the variables in the callback function.</p>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Other_notes\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Other_notes</a></sub></p>\n\n<p><sup>2</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Legacy_Internet_Explorer_and_attachEvent\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Legacy_Internet_Explorer_and_attachEvent</a>)</sub></p>\n\n<p><sup>3</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event#Browser_compatibility\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event#Browser_compatibility</a></sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T02:56:57.560", "Id": "468429", "Score": "1", "body": "Given the bounty to you for the most indepth answer on here... Thanks for the input, will use some of your suggestion to build upon my next iterations & code attempts." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-09T06:17:52.427", "Id": "238606", "ParentId": "237357", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T06:01:09.200", "Id": "237357", "Score": "1", "Tags": [ "javascript", "performance", "regex", "animation", "cross-browser" ], "Title": "Check browser compatibility for RequestAnimationFrame and Vanilla JavaScript .animate() API" }
237357
<p>I'm trying to solve a programming challenge where I have to find the median of given subarrays of an array. I have used <code>std::vector</code>'s <code>n_th element</code> for this. But the evaluator fails some test cases as "time limit exceeded".</p> <pre><code>#include &lt;iostream&gt; #include &lt;bits/stdc++.h&gt; using namespace std; /* In 6 2 4 5 3 1 6 3 1 6 2 4 3 3 Out 3 4 5 */ int get_ceil(int length) { if (length % 2 == 0) { return length/2; } else { return (length+1)/2; } } int get_median_of_subarray(std::vector&lt;int&gt; &amp; full_array, int lo, int hi) { std::vector&lt;int&gt;::const_iterator begin = full_array.begin() + lo; std::vector&lt;int&gt;::const_iterator end = full_array.begin() + hi + 1; std::vector&lt;int&gt; sub_array(begin, end); int median_pos = get_ceil(hi - lo + 1); std::nth_element (sub_array.begin(), sub_array.begin() + median_pos -1, sub_array.end()); return sub_array[median_pos - 1]; } int main() { ios_base::sync_with_stdio(false); int array_size = 0; std::vector&lt;int&gt; input_array; cin &gt;&gt; array_size; for(int i = 0; i &lt; array_size; i++) { int x; cin &gt;&gt; x; input_array.push_back(x); } int query_size = 0; cin &gt;&gt; query_size; int lo = 0; int hi = 0; for(int i = 0; i &lt; query_size; i++) { cin &gt;&gt; lo &gt;&gt; hi; std::cout &lt;&lt; get_median_of_subarray(input_array, --lo, --hi) &lt;&lt; std::endl; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T13:20:41.800", "Id": "465445", "Score": "1", "body": "`full_array` should be a reference-to-const, it isn't modified inside your function. This just clarifies your code a bit. The median of [2, 10] is 6, which your algorithm ignores. Since you get a timeout and not a test failure, I guess that all this is just about odd-sized sequences." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T13:43:25.337", "Id": "465447", "Score": "1", "body": "Also not performance-related: `get_ceil()` is a bit overcomplicated. If `length = 3`, `(length + 1) / 2 = 2`. If `length = 4`, `(length + 1) / 2 = 2`, due to integer division. C++ doesn't round but truncate the result. Therefore, you can always `return (length + 1) / 2;`. I'd also call this `get_half_ceil()`, because that's closer to what it does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T18:13:57.193", "Id": "465456", "Score": "1", "body": "Could you please copy the question from the code challenge and add a link to it as well." } ]
[ { "body": "<p>Not related to performance, but never ever do this:</p>\n\n<pre><code>#include &lt;bits/stdc++.h&gt;\n\nusing namespace std;\n</code></pre>\n\n<p>For reference see these Q&amp;A at Stack Overflow:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h\">Why should I not #include <code>&lt;bits/stdc++.h&gt;</code>?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std;” considered bad practice?</a></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T07:40:58.557", "Id": "237361", "ParentId": "237360", "Score": "7" } }, { "body": "<ul>\n<li>One performance problem is the overhead of allocating and resizing a vector. Since you read the size up front, why not simply <code>reserve()</code> enough space?</li>\n</ul>\n\n<pre><code> cin &gt;&gt; array_size;\n input_array.reserve(array_size);\n</code></pre>\n\n<ul>\n<li><p>If you sorted the sequence, computing the median would become dead simple and very fast (O(1)). This may be a better approach. However, you can't sort the sequence once and then run different queries, because the subsequence applies to the unsorted sequence. I haven't thought this through completely, but when removing two elements from the sequence, there are several possible ways it can affect the median:</p>\n\n<ul>\n<li>If both elements are larger, the median becomes the previous value in the sorted sequence.</li>\n<li>If both elements are smaller, the median becomes the next value in the sorted sequence.</li>\n<li>If one element element is smaller and one is larger, the median remains the same.</li>\n<li>If one element is equal to the median, it moves opposite to the other value.</li>\n</ul>\n\n<p>The problem here is that the \"new\" median can easily be one that's should be removed already, so this simple approach is not yet enough, but it might serve as a start to a better algorithm. In any case, what you need to keep in mind is the complexity and the variables that affect it. For your task, you have the number of values <code>n</code> and the number of queries <code>m</code>. Your algorithm is almost optimal for the case that <code>m = 1</code>. In order to improve the overall performance, you can actually optimize the performance for the case of <code>m &gt; 1</code>, even at the expense of the the <code>m = 1</code> case! Often, you can improve the performance by first sorting the data and then switching to a different (faster) algorithm for the actual work.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T13:38:24.003", "Id": "237375", "ParentId": "237360", "Score": "4" } } ]
{ "AcceptedAnswerId": "237375", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T07:03:58.027", "Id": "237360", "Score": "3", "Tags": [ "c++", "programming-challenge", "c++11", "time-limit-exceeded", "vectors" ], "Title": "Finding median of sub arrays taking too much time" }
237360
<p>I am going to undergo a code review shortly at work. I feel that my code is too verbose, could log more sensibly, and I feel that my if/else statements are somewhat duplicative/repetitive and can be done better. But I can't seem to be able to put my finger on what I am missing. How would you clean this up such that the code isn't verbose, logs sensible stuff and doesn't look kiddish. I would also like to make it simpler, in case additional filters need to be added in future.</p> <p>FYI - getDetails method used in the following code, merely contains code for constructing a customer specific "Details" object that contains just 2 things, the name of the customer and a corresponding schedule for invocation. </p> <pre><code> /* Filters out invokes that havent reached a size threshold.*/ private boolean filterBySize(CustomerUnit Customer) { CustomerData customerData = new CustomerData(Customer); if (customerData.getUsage() &gt; USAGE_THRESHOLD) { LOGGER.info("Customer's data usage of " + customerData.getUsage() + "is higher than threshold of " + USAGE_THRESHOLD + " percent for " + Customer.getId()); return true; } else { LOGGER.info("Customer's data usage of " + customerData.getUsage() + "is lower than threshold of " + USAGE_THRESHOLD + " percent for " + Customer.getId()); return false; } } /* Filters out invokes that aren't slated for today.*/ private boolean filterByDate(CustomerUnit Customer) { if (getDetails(Customer).getDOW().equalsIgnoreCase(LocalDate.now().getDayOfWeek().name())) { LOGGER.info("Customer : " + getDetails(Customer).getName() + " is invoked to run import today"); return true; } else { LOGGER.info("Customer : " + getDetails(Customer).getName() + " isn't invoked to run import today, "); return false; } } /* Applies aforesaid filters */ private void invokeRequestByCustomer(CustomerUnit Customer) throws InterruptedException, UnexpectedDateOrderException { if (filterByDate(Customer) &amp;&amp; filterBySize(Customer)) { invoker.invoke(getDetails(Customer)); LOGGER.info("Scheduled Customer : " + getDetails(Customer).getName() + " to run import operations at" + getDetails(Customer).getDOW()); } else { LOGGER.info("Customer : " + getDetails(Customer).getName() + " was filtered, no invoke will be executed for it"); } } </code></pre> <p>As of now, I have thought about using an IfThenElse function, somewhat similar to the following: <a href="https://www.javaworld.com/article/3319078/functional-programming-for-java-developers-part-2.html" rel="nofollow noreferrer">IfThenElse example</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T08:34:30.640", "Id": "465428", "Score": "0", "body": "I understand marking it down - but it would help me if you were to tell me the reason for doing so. I went through the guidelines and asked my question as per my understanding of those guidelines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T09:27:45.973", "Id": "465431", "Score": "4", "body": "The close vote is for needing detail / clarity. This may be related to your title, which doesn't reflect what the code is trying to achieve. \"Filter customers by date and size\" may be a better description of what the codes doing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T12:24:59.087", "Id": "465441", "Score": "3", "body": "Next time, please post a complete class (including the import declarations) and provide interfaces (or classes) for all mentioned types, to allow us reviewers to paste the code into our IDE and be ready to try it out. If you had done this for this question, you might have received some helpful tips for using the logging framework more efficiently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T22:03:58.260", "Id": "465474", "Score": "0", "body": "Thanks for your comments - I understand. My initial thought was that it might become too much text for the review, but I guess it is helpful if it provides clarity and context. It would be nice if I could just attach the files with the post and only post the textual description of what I am trying to focus on, with some way of displaying the attached files on the side, if needed anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T12:30:45.633", "Id": "465559", "Score": "1", "body": "We're not easily scared and our character limit is over 65k characters. Next time, don't be afraid to show us more context." } ]
[ { "body": "<p>The comments seem redundant, I'm assuming they're just for this review, if not, I would remove them. The basically just duplicate what the code says.</p>\n\n<p>Your function names seem misleading. <code>filterBySize</code> seems to be filtering by data usage. <code>filterByDate</code> seems to be filtering by the day of the week. It would be better if they said what they did.</p>\n\n<p>Your filtration functions contain two branches, both of which return. Generally you would only wrap the <code>if</code> side. Everything that doesn't trigger the <code>if</code> would be the <code>else</code>... </p>\n\n<pre><code>CustomerData customerData = new CustomerData(Customer);\nif (customerData.getUsage() &gt; USAGE_THRESHOLD) {\n return true;\n}\n// The else is implicit... so just noise\nreturn false;\n</code></pre>\n\n<p>For me, there's an awful lot of logging across these methods. Maybe that's what's required by your processes, but it seems excessive. We don't have the context for how the code is going to be called, however I would expect that 'USAGE_THRESHOLD' is the same for every invocation, do you really need to log it for each custom to say if they are above/below it? The current day of the week is the same for each invocation, again do you really need to output it for every customer that's selected? Each of your filters logs the specific reason that the customer has been rejected do you need to log the generic message at the top level saying they are being skipped. If you're looking for reuse, then maybe your <code>filterByDate</code> method shouldn't mention the <code>import</code>, that way it could be reused to filter other things (export perhaps) in the future...</p>\n\n<p>As an aside, I'm not sure about this:</p>\n\n<pre><code>CustomerData customerData = new CustomerData(Customer);\n</code></pre>\n\n<p>It makes me wonder what the constructor for <code>CustomerData</code> is doing... If the information needed for the filtration isn't in the <code>Customer</code>, then is it reading that extra data in the the constructor for <code>CustomerData</code>? That seems wrong...</p>\n\n<p>Another small issue is naming.... variables should start with lower case in java.... <code>CustomerUnit Customer</code> should be <code>CustomerUnit customer</code>, you can see it's confusing the code preview...</p>\n\n<p>It would also be interesting to see how <code>invokeRequestByCustomer</code> is being called... It looks a lot like it could fit into a stream something like:</p>\n\n<pre><code>allCustomers.stream()\n .filter(CustomerFilters::byUsage)\n .filter(CustomerFilters::byDay)\n .foreach(c-&gt;invoke(c));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T09:44:22.897", "Id": "237366", "ParentId": "237362", "Score": "5" } }, { "body": "<p>I'm agree with considerations by @forsvarir and I'm writing a possible example on how to simplify your messages, you have the following method:</p>\n\n<blockquote>\n<pre><code>private boolean filterBySize(CustomerUnit Customer) {\n CustomerData customerData = new CustomerData(Customer);\n if (customerData.getUsage() &gt; USAGE_THRESHOLD) {\n LOGGER.info(\"Customer's data usage of \" + customerData.getUsage()\n + \"is higher than threshold of \" + USAGE_THRESHOLD + \" percent for \" + Customer.getId());\n return true;\n } else {\n LOGGER.info(\"Customer's data usage of \" + customerData.getUsage()\n + \"is lower than threshold of \" + USAGE_THRESHOLD + \" percent for \" + Customer.getId());\n return false;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The two messages differs just for the use of word \"lower\" in one branch and \"higher\" in the other: in this case you can rewrite your method using a ternary operator and <code>String.format</code>:</p>\n\n<pre><code>private boolean filterBySize(CustomerUnit Customer) {\n CustomerData customerData = new CustomerData(Customer);\n String template = \"Customer's data usage is %s than threshold of %f percent for %d\";\n boolean condition = customerData.getUsage() &gt; USAGE_THRESHOLD;\n String s = condition ? \"lower\" : \"higher\";\n LOGGER.info(String.format(template, s, customerData.getUsage(), Customer.getId()));\n return condition;\n}\n</code></pre>\n\n<p>I don't know the exact types of your data so I used %f and %d inside <code>String.format</code> and I chose to preserve the name <code>Customer</code> for the parameter for this example, but as highlighted by @forsvarir change it to lowercase.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T20:03:52.780", "Id": "465776", "Score": "0", "body": "I like your inputs as well. It is just that @forsvarir had a suggestion about using the stream which I found quite useful in addition to the inputs about the methods. Appreciate your help still though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:04:18.830", "Id": "465794", "Score": "0", "body": "@NotACodeNinja You are welcome, if you have other questions post them here in the Code Review site." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T11:49:39.650", "Id": "237371", "ParentId": "237362", "Score": "5" } } ]
{ "AcceptedAnswerId": "237366", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T07:52:20.690", "Id": "237362", "Score": "4", "Tags": [ "java" ], "Title": "How can this code for applying filters to data by date and size be improved?" }
237362
<p>Recently got rejected in a code challenge that was a very simple WebService with 3 endpoins: </p> <ul> <li><code>POST /transactions</code> to add transactions with an ammount and timestamp.</li> <li><code>GET /statistics</code> to query the statistics of the transactions of the last minute.</li> <li><code>DELETE /transactions</code>.</li> </ul> <p>I just pasted below Service object because the API controller is irrelevant:</p> <pre><code>data class Transaction(val amount: BigDecimal, val timestamp: Instant) data class Statistics(val sum: String, val min: String, val max: String, val avg: String, val count: Int) class TransactionInFutureException(message: String) : Exception(message) class TransactionBeforeThreshold(message: String) : Exception(message) const val THRESHOLD_SEC = 60L const val CLEANER_INTERVAL_MS = 5000L const val AMOUNT_SCALE = 2 class TransactionsService { protected val transactions = ArrayList&lt;Transaction&gt;() init { thread(start = true) { Thread.sleep(CLEANER_INTERVAL_MS) synchronized(transactions) { val threshold = getCurrentThreshold() transactions.removeAll { it.timestamp &lt; threshold } } } } fun add(amount: BigDecimal, timestamp: Instant) { if (timestamp &gt; Instant.now()) throw TransactionInFutureException("transaction timestamp cannot be in future") else if (timestamp &lt; getCurrentThreshold()) throw TransactionBeforeThreshold("transaction timestamp cannot be before threshold") synchronized(transactions) { transactions.add(Transaction(amount, timestamp)) } } fun clear() { synchronized(transactions) { transactions.clear() } } fun statistics(): Statistics { synchronized(transactions) { val threshold = getCurrentThreshold() val liveTransactions = transactions.filter { it.timestamp &gt; threshold } val count = liveTransactions.count() var sum = BigDecimal(0) var max = if (count &gt; 0) liveTransactions.first().amount else BigDecimal(0) var min = if (count &gt; 0) liveTransactions.first().amount else BigDecimal(0) liveTransactions.forEach { sum += it.amount max = max.max(it.amount) min = min.min(it.amount) } var avg = BigDecimal(0) if (count &gt; 0) avg = sum.setScale(AMOUNT_SCALE, BigDecimal.ROUND_HALF_UP). divide(BigDecimal(count), BigDecimal.ROUND_HALF_UP) return Statistics(format(sum), format(min), format(max), format(avg), count) } } protected fun getCurrentThreshold() = Instant.now().minusSeconds(THRESHOLD_SEC) protected fun format(value: BigDecimal) = value.setScale(AMOUNT_SCALE, BigDecimal.ROUND_HALF_UP).toString() } </code></pre> <p>The two main points because I got rejected were:</p> <blockquote> <p>There was no separation of concerns; Most of the logic is in just one class.</p> <p>We felt there was excessive use of Synchronized blocks - which could be replaced with a synchronized or concurrent collection</p> </blockquote> <p>Looks like they were expecting me to split the functionality of <code>TransactionService</code> into a kind of <code>StatisticsCalculator</code> class that will do what the <code>statistics()</code> method does.</p> <p>To be honest, for the requirements given, I felt like this is overengineering from here to mars and I will apply the <code>Yagni</code> principle:</p> <ul> <li><p><code>TransactionsService</code> as it is, is a 50L of code class. It fits in one screen and is easy to follow. There is not cognitive overload reading it.</p></li> <li><p>There is anything to be gained by splitting the class in two right now? I hardly can tell but for sure you will have to add more complexity to the public API of <code>TransactionService</code> to allow to iterate over the stored transactions from <code>StastisticsCalculator</code>.</p></li> <li><p>As programmers we make trade-offs all the time, between complexity, maintainability, time to build and so forth. I will state that following the Single-responsability-principle is pushing too much the <code>SOLID</code> envelope and I will just adhere to <code>YAGNI</code> and <code>KISS</code>.</p></li> <li><p>When complexity arises in the future refactoring and splitting will be my first option.</p></li> </ul> <p>What do you think?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T16:19:03.710", "Id": "465451", "Score": "3", "body": "Maybe people who is downvoting can explain why? Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T18:06:49.810", "Id": "465455", "Score": "1", "body": "I haven't voted yet. However, your title should reflect what your code does, not what you want for the review. Something like 'statistical transaction analysis' perhaps. You've also tagged both Java and kotlin, even though the code appears to only be kotlin. Both close votes are asking for additional clarity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T19:16:07.433", "Id": "465460", "Score": "0", "body": "@forsvarir true, but the underlying code challenge problem here is not the most important issue here I believe." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T22:00:19.423", "Id": "465472", "Score": "2", "body": "Your question could be improved by giving a bit of context in the beginning. Right now you throw us right into the code and we're left with wondering things like \"What is a transaction?\" and \"What statistics do you want to return?\" The more context you can give us before you show the code, the easier it is to understand your code and the easier for us it will be to help you with better answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T22:03:45.420", "Id": "465473", "Score": "0", "body": "@pragmatic_programmer The thing about titles on Code Review is that everyone wants to improve their code in one way or another, which is why most titles are too generic and can be applied to many questions. *Rejected at code challenge because of lack of separations of concerns but I feel like YAGNI* is not the most common title I've seen, but still applies to quite many questions. Therefore, the custom here is to write titles that summarizes what your code does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T22:14:48.317", "Id": "465475", "Score": "1", "body": "What is the purpose of `transactions.removeAll { it.timestamp < threshold }` inside the `thread` in the `init`? What requirement did you have that made you implement this code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T06:37:26.540", "Id": "465509", "Score": "0", "body": "@SimonForsberg transactions longer than a minute should be discarded at some point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T11:58:22.520", "Id": "465551", "Score": "1", "body": "@pragmatic_programmer As I read it, `transactions` will only be cleaned up once, 5 seconds after the class is instantiated?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T12:10:57.593", "Id": "465554", "Score": "0", "body": "Classes are not simpler (Kiss) if you add all the functions inside the same class. Having two even more stupid classes can make the program even more stupid.\nSplitting up classes based on level of abstraction (in this case storage and representation) will create two very dumb small classes without having thought about adding new code (Yagni)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T12:21:22.103", "Id": "465555", "Score": "0", "body": "@SimonForsberg true, forget to sorround all around a while true! looks like the evaluator missed that part. LOL" } ]
[ { "body": "<p>Disclaimer... I have very little experience with Kotlin.</p>\n\n<p>Not really the focus of your question, but <code>synchronized</code> blocks should be only as big as they need to be. Looking at your statistics code, you put the whole thing in the block.:</p>\n\n<blockquote>\n<pre><code>synchronized(transactions) {\n val threshold = getCurrentThreshold()\n val liveTransactions = transactions.filter { it.timestamp &gt; threshold }\n</code></pre>\n</blockquote>\n\n<p>I'm not sure if the threshold needs to be in the block or not, it depends what your goal with it is... however I think it's probably arbitrary so could be outside the block. Putting that to the side, <code>filter</code> returns a copy of the collection. Everything in your transactions collections is immutable, which means that <code>liveTransactions</code> is its own copy of data that won't change. I don't see any reason for anything after this line to still be in the synchronised block. Another call to <code>statistics</code> seems perfectly reasonable in this situation.</p>\n\n<p>The way you initialise <code>max</code> and <code>min</code> seems unnecessarily complicated</p>\n\n<blockquote>\n<pre><code>var max = if (count &gt; 0) liveTransactions.first().amount else BigDecimal(0)\n</code></pre>\n</blockquote>\n\n<p>You might as well be always setting it to <code>0</code>, since you don't then skip the first item in the list.</p>\n\n<p>I think there's a bit more to separation of concerns than cognitive overload. Part of the benefit is that it becomes easier to test the code that you've written. To test your statistics code at the moment, you need to create the array list, via the <code>add</code> method on your TransactionService, making sure your timestamps are all correct for the current time. If instead of your statistics method, you separate the calculation portion out, something like this:</p>\n\n<pre><code>public inline fun &lt;T&gt; Iterable&lt;T&gt;.buildStatistics(selector: (T) -&gt; BigDecimal): Statistics {\n var sum: BigDecimal = BigDecimal(0)\n var count = 0\n var max = BigDecimal(0)\n var min = BigDecimal(0)\n var avg = BigDecimal(0)\n\n for (element in this) {\n sum += selector(element)\n max = max.max(selector(element))\n min = min.min(selector(element))\n count++\n }\n if (count &gt; 0)\n avg = sum.setScale(AMOUNT_SCALE, BigDecimal.ROUND_HALF_UP).divide(BigDecimal(count), BigDecimal.ROUND_HALF_UP)\n return Statistics(sum, min, max, avg, count)\n}\n</code></pre>\n\n<p>Which can then be called...</p>\n\n<pre><code>val stats = filteredTransactions.buildStatistics { t -&gt; t.amount}\n</code></pre>\n\n<p>The calculation code then becomes pretty trivial to test, construct an array list of transactions, then call call the <code>buildStatistics</code> method on it, then see if the calculated statistics are correct.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T20:08:46.323", "Id": "237396", "ParentId": "237374", "Score": "4" } }, { "body": "<p>I will have to agree that you do have a bit much <code>synchronized</code> blocks. All of them could go away if you would use for example <code>Collections.synchronizedList</code> around your <code>ArrayList</code> or <code>CopyOnWriteArrayList</code>.</p>\n\n<p>Your <code>fun statistics()</code> could be an alternative constructor to <code>Statistics</code></p>\n\n<p>A few other Kotlin-related tips:</p>\n\n<pre><code>var max = if (count &gt; 0) liveTransactions.first().amount else BigDecimal(0)\n</code></pre>\n\n<p>Can be written as <code>liveTransactions.firstOrNull()?.amount ?: BigDecimal(0)</code></p>\n\n<p>Actually:</p>\n\n<pre><code>val amounts = liveTransactions.map {it.amount}\nval max = amounts.fold(BigDecimal(0)) { a, b -&gt; a.max(b) }\nval sum = amounts.fold(BigDecimal(0)) { a, b -&gt; a.plus(b) }\n</code></pre>\n\n<p>I would recommend against the <code>forEach</code>. Sure, you need to loop through the array three times, but right now you're doing one loop and three things in every iteration so effectively it has about the same performance.</p>\n\n<hr>\n\n<p><code>TransactionInFutureException</code> and <code>TransactionBeforeThreshold</code> are really just different versions of <code>IllegalArgumentException</code>, so I would not add my own exceptions here but just use the existing <code>IllegalArgumentException</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T22:29:33.217", "Id": "237399", "ParentId": "237374", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T13:31:56.573", "Id": "237374", "Score": "3", "Tags": [ "programming-challenge", "design-patterns", "kotlin" ], "Title": "WebService to calculate transaction statistics" }
237374
<p>For practicing purposes, I had the idea of making a sorting algorithm in Python.</p> <p>My approach to it was to iterate through a given unsorted list to find the shortest number in it, add the number to a second list, remove shortest number from unsorted list, do that until the unsorted list is empty and return the sorted list.</p> <p>How could my code be improved?</p> <pre><code>from math import inf from random import randint def my_sort(my_list): """ Iterate through list and find shortest number, add shortest number to list until there are none left, return sorted list (shortest to highest). """ unsorted_list = [*my_list] sorted_list = [] for item in my_list: shortest_num = inf for num in unsorted_list: if num &lt; shortest_num: shortest_num = num unsorted_list.remove(shortest_num) sorted_list.append(shortest_num) return sorted_list # Randomly generate a list of 20 numbers ranging from -20 to 20 random_list = [randint(-20, 20) for i in range(20)] print(random_list) print(my_sort(random_list)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T15:34:17.740", "Id": "465581", "Score": "6", "body": "This algorithm is called *selection sort*, you may find more information and ideas on the efficient implementation by using that as search term." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T17:17:38.717", "Id": "465600", "Score": "0", "body": "Thx, I'll take a look at it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T02:14:19.217", "Id": "465650", "Score": "1", "body": "[Selection sort is O(N^2)](https://en.wikipedia.org/wiki/Selection_sort) rather than O(N log N), so it's inefficient and non-scalable, that's why it's not used. Moreover, you're iterating over the list but you throw away the index of `shortest_num` and call `unsorted_list.remove()`, which is [itself O(N)](https://wiki.python.org/moin/TimeComplexity), and will be slower and non-scalable. I presume you want to know that, rather than comments on your syntax." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T08:14:54.057", "Id": "466110", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. 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)*." } ]
[ { "body": "<p>Since the goal is the best possible implementation of this algorithm, I'd suggest the following. However, faster <a href=\"https://en.wikipedia.org/wiki/Sorting_algorithm\" rel=\"noreferrer\">algorithms</a> do exist.</p>\n\n<ol>\n<li>To conform to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> make sure you have two blank lines after your imports and surrounding function definitions.</li>\n<li>Since, you aren't editing each item, but rather adding and removing items until the list is sorted, I'd use the <em>while</em> keyword.</li>\n<li>The builtin min function is faster than looping through yourself. If you want to make your own minimum function as an exercise you can always do that and replace <em>min</em> with your own <em>my_min</em> say</li>\n</ol>\n\n<p>My Code:</p>\n\n<pre><code>def my_sort2(my_list):\n unsorted_list = [*my_list]\n sorted_list = []\n while len(unsorted_list) &gt; 0:\n shortest_num = min(unsorted_list)\n sorted_list.append(shortest_num)\n unsorted_list.remove(shortest_num)\n return sorted_list\n</code></pre>\n\n<p>When timing mysort2 vs your mysort, I get a 12% improvement on my machine.</p>\n\n<p>Timing code: (Not the nicest but it does the job)</p>\n\n<pre><code>t1 = inf\nt2 = inf\nfor _ in range(1000):\n t1 = min(t1, timeit.timeit(\n stmt=f'my_sort(random_list)',\n setup=f'from __main__ import my_sort, random_list',\n number=100))\n t2 = min(t2, timeit.timeit(\n stmt=f'my_sort2(random_list)',\n setup=f'from __main__ import my_sort2, random_list',\n number=100))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T15:43:28.917", "Id": "237380", "ParentId": "237378", "Score": "12" } }, { "body": "<p>Your code looks well-formatted, it's easy to read and to follow, and the explanation you gave matches the code exactly. Well done. :)</p>\n\n<pre><code>for item in my_list:\n</code></pre>\n\n<p>This statement looks strange since in the body of this <code>for</code> loop, you neither use <code>item</code> nor <code>my_list</code>. You can express the idea of that code more directly:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for _ in range(len(my_list)):\n</code></pre>\n\n<p>The variable <code>_</code> is just a normal variable, and you could even access its value. By convention though, the variable <code>_</code> means an unused variable.</p>\n\n<p>Or, alternatively, you could express it even shorter:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>while len(unsorted_list) &gt; 0:\n</code></pre>\n\n<p>This wording matches the body of the loop, where you remove an element from <code>unsorted_list</code> in each iteration. This is good. It's still quite long though, therefore the idiomatic way to test whether a list is empty is:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>while unsorted_list:\n</code></pre>\n\n<p>This makes your code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def my_sort(my_list):\n unsorted_list = [*my_list]\n sorted_list = []\n while unsorted_list:\n shortest_num = inf\n for num in unsorted_list:\n if num &lt; shortest_num:\n shortest_num = num\n unsorted_list.remove(shortest_num)\n sorted_list.append(shortest_num)\n return sorted_list\n</code></pre>\n\n<p>This code can be made much shorter since Python has a <a href=\"https://docs.python.org/3/library/functions.html#min\" rel=\"noreferrer\">built-in function called min</a>. By using it you can transform your code to:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def my_sort(my_list):\n unsorted_list = [*my_list]\n sorted_list = []\n while unsorted_list:\n shortest_num = min(unsorted_list)\n unsorted_list.remove(shortest_num)\n sorted_list.append(shortest_num)\n return sorted_list\n</code></pre>\n\n<p>This is already much shorter than before, and you don't need to import <code>math.inf</code> anymore, which is good, since it was a placeholder anyway that was not really necessary from a high-level point of view.</p>\n\n<p>This is about as elegant as it gets. You should not use this sorting algorithm for sorting large data since for a list of <span class=\"math-container\">\\$n\\$</span> elements it requires <span class=\"math-container\">\\$ n + n \\cdot (\\frac n2 + \\frac n2 + 1) \\$</span> steps, or a bit more compressed, it has the time complexity <span class=\"math-container\">\\$\\mathcal O(n^2)\\$</span>. There are faster sorting algorithms out there. These are more complicated to implement, but once they are implemented and tested, they are as easy to use as your algorithm.</p>\n\n<p>Regarding the variable names: <code>shortest_num</code> should better be <code>smallest_num</code>, since <code>0</code> is shorter than <code>-12345</code>, and you probably didn't mean that. Your documentation comment should be more like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>\"\"\"\nReturn a sorted copy of the given list, from smallest to largest.\n\"\"\"\n\n# Sorting is done by repeatedly removing the smallest\n# number from the list and adding it to the sorted list.\n</code></pre>\n\n<p>Note how I split the comment into two separate parts.\nThe upper half in the <code>\"\"\" triple quotes \"\"\"</code> is meant to document the behavior of the code, while the lower half explains the implementation. For the code that uses this sorting function, it doesn't matter how the list is sorted, it just matters <em>that</em> it is sorted.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T20:04:49.490", "Id": "465468", "Score": "0", "body": "Ooh, I had forgotten about ```min```, thanks for the advice!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T15:50:01.453", "Id": "237381", "ParentId": "237378", "Score": "9" } }, { "body": "<p>First I got same approach than previous answers (@Roland Illig &amp; Luapulu) that are very similar.</p>\n<p>But then I remembered Item 72 of <a href=\"https://effectivepython.com\" rel=\"nofollow noreferrer\">Effective Python (Brett Slatkin's book)</a>:</p>\n<blockquote>\n<p>72: Consider Searching Sorted Sequences with bisect. Python’s built-in bisect module provides better ways to accomplish these types of searches through ordered lists. You can use the bisect_left function to do an efficient binary search through any sequence of sorted items. The index it returns will either be where the item is already present in the list or where you’d want to insert the item in the list to keep it in sorted order</p>\n</blockquote>\n<pre><code>from bisect import bisect_left\ndef my_sort_2(my_list):\n sorted_list = []\n for value in my_list:\n index = bisect_left(sorted_list, value)\n sorted_list.insert(index, value)\n return sorted_list\n</code></pre>\n<p><a href=\"https://docs.python.org/2/library/bisect.html#module-bisect\" rel=\"nofollow noreferrer\">bisect</a> is part of standard lib since Python 2.1:</p>\n<blockquote>\n<p>This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over the more common approach. The module is called bisect because it uses a basic bisection algorithm to do its work.</p>\n<p>bisect.<strong>bisect_left</strong>(a, x, lo=0, hi=len(a)) Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted.</p>\n</blockquote>\n<p>And now it's time to check performance of available solutions for the list of 20 numbers:</p>\n<ul>\n<li>Min time with my_sort =0.0126 ms</li>\n<li>Min time with my_sort_luapulu =0.0114 ms</li>\n<li>Min time with my_sort_roland =0.0105 ms</li>\n<li>Min time with my_sort_2 =0.0048 ms</li>\n</ul>\n<p>According just to this case, improvement in my machine with Python 3.8 is (compared to my_sort, from original question):</p>\n<ul>\n<li>Luapulu takes - 9,4% time</li>\n<li>Roland Illig takes - 16,4% time</li>\n<li><strong>My proposal takes -61,7% time, What's a real difference for a list of 20</strong></li>\n</ul>\n<hr />\n<p>Note: this part has been edited, after learning from comments received, the way to make a complexity analysis (please let me know if I am wrong):</p>\n<p>Nº steps required for a list of n elements: <span class=\"math-container\">\\$ n \\cdot (\\frac n2 \\cdot \\frac 12 + \\frac n2) \\$</span> = <span class=\"math-container\">\\$ n^2 \\cdot \\frac 34 \\$</span></p>\n<ul>\n<li>bisect_left takes <span class=\"math-container\">\\$ \\frac 12 \\$</span> of sorted list length <span class=\"math-container\">\\$ \\frac n2 \\$</span></li>\n<li>insert in sorted list is <span class=\"math-container\">\\$ \\frac n2 \\$</span></li>\n</ul>\n<p>So you neither should use this solution for sorting large data, as for large numbers it has also a time complexity of <span class=\"math-container\">\\$ \\mathcal O(n^2) \\$</span></p>\n<h2>Thanks all for make me see that my previous time analysis was wrong.</h2>\n<p>Note: Code used to check answers on my windows PC:</p>\n<pre><code>def print_min_time(description, func, *args, setup='pass'):\n min_time = min(timeit.repeat(lambda: func(*args), setup))\n print(f'Min time with {description} ={min_time/1000} ms')\n\nrandom_list = [randint(-20, 20) for i in range(20)]\nprint_min_time('my_sort', my_sort, random_list, setup='from math import inf')\nprint_min_time('my_sort_2', my_sort_2, random_list, setup='from bisect import bisect_left')\nprint_min_time('my_sort_luapulu', my_sort_luapulu, random_list)\nprint_min_time('my_sort_roland', my_sort_roland, random_list)\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T19:15:41.313", "Id": "465459", "Score": "1", "body": "You have an impressing system clock if it has indeed sub-attosecond resolution. In other words, you should format the measurement results with only as many digits as sensible. This makes the results both easier to read and believable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T19:18:51.097", "Id": "465461", "Score": "1", "body": "In your measurement, how large is the `random_list`? Just to get an impression at how much \\$\\mathcal O(n^2)\\$ and \\$\\mathcal O(\\log n)\\$ differ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T19:34:24.227", "Id": "465463", "Score": "0", "body": "Thanks Rolland for your comments: I used same random list from the question (20). I am going to measure time using 40 and I will edit my answer with results" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T20:03:52.167", "Id": "465467", "Score": "0", "body": "Thx for your help :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T23:27:29.097", "Id": "465483", "Score": "14", "body": "How does this answer the question? This algorithm is completely different from that of the OP. His was essentially a selection sort, yours an insertion sort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T09:20:57.620", "Id": "465529", "Score": "8", "body": "There are multiple issues with this answer but the most prominent issue is: it performs an incomplete and incorrect [complexity analysis](https://en.wikipedia.org/wiki/Analysis_of_algorithms#Run-time_analysis) and an invalid benchmark, and the performance numbers are consequently meaningless and misleading." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T09:50:09.263", "Id": "465693", "Score": "0", "body": "Thanks for your changes, it’s a much better answer now; I’ve converted my voted." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T17:34:16.003", "Id": "237389", "ParentId": "237378", "Score": "2" } } ]
{ "AcceptedAnswerId": "237389", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T14:48:52.390", "Id": "237378", "Score": "10", "Tags": [ "python", "beginner", "python-3.x", "sorting", "reinventing-the-wheel" ], "Title": "My approach to sorting algorithm" }
237378
<p>I have a little dilema with such if statement, I have tried optimizing it in order to remove some checks, but could not think of how to make this code part cleaner. Can someone please make a review, and tell if it's possible to optimize such statement of maybe there is some law for this? Thank you</p> <pre><code>//letter = 'E' or 'R' ( char ) //second letter = 'Q' or 'A' ( char ) //DoFlip = false or true ( bool ) if((letter == 'E' &amp;&amp; secondLetter == 'Q' &amp;&amp; DoFlip == false) || (letter == 'E' &amp;&amp; secondLetter == 'A' &amp;&amp; DoFlip == true) || (letter == 'R' &amp;&amp; secondLetter == 'Q' &amp;&amp; DoFlip == false)|| (letter == 'R' &amp;&amp; secondLetter == 'A' &amp;&amp; DoFlip== true)) { //DoSmth here } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T18:02:08.930", "Id": "465454", "Score": "0", "body": "Welcome to code review. This question is off topic because there isn't enough code to review. It might be better to ask it on stackoverflow.com, but try searching stackoverflow first to see if it has been answered already." } ]
[ { "body": "<p>Firstly, this can be rewritten as:</p>\n\n<pre><code>\nif(((letter == 'E' || letter == 'R')&amp;&amp; secondLetter == 'Q' &amp;&amp; DoFlip == false)|| \n ((letter == 'E' || letter == 'R') &amp;&amp; secondLetter == 'A' &amp;&amp; DoFlip == true)\n {\n //DoSmth here\n }\n</code></pre>\n\n<p>According to distributive law - </p>\n\n<pre><code>A &amp;&amp; B || A &amp;&amp; C = (B || C) &amp;&amp; A\n</code></pre>\n\n<p>In your logic - (letter == 'E' || letter == 'R') can take place of A with (secondLetter == 'Q' &amp;&amp; DoFlip == false) as B and (secondLetter == 'A' &amp;&amp; DoFlip == true) as C.</p>\n\n<p>So your logic can be simplified to - </p>\n\n<pre><code>if((letter == 'E' || letter == 'R') &amp;&amp; \n ((secondLetter == 'Q' &amp;&amp; DoFlip == false) || \n (secondLetter == 'A' &amp;&amp; DoFlip == true))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T17:14:11.900", "Id": "237385", "ParentId": "237379", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T15:40:59.893", "Id": "237379", "Score": "1", "Tags": [ "c++", "performance" ], "Title": "Optmize logic IF statement" }
237379
<p>I am working through the K&amp;R and just finished exercise 1-12 and below is my solution. Exercise1-12: Write a program that prints input one word per line.</p> <pre><code>#include &lt;stdio.h&gt; main() { int c; while((c = getchar()) != EOF) { if(c == ' ' || c == '\t' || c == '\n') { putchar('\n'); while(c == ' '|| c == '\t' || c == '\n') c = getchar(); } putchar(c); } } </code></pre> <p>My question is both author and solutions <a href="https://clc-wiki.net/wiki/K%26R2_solutions:Chapter_1:Exercise_12" rel="noreferrer">here</a> defined and used the state variable. when we compare my solution is pretty simple but it works. am I missing something? maybe there is a case that my solution won't work well?</p> <p>Looking for your comments to improve, Thanks</p>
[]
[ { "body": "<p>To get a historically correct impression of programming in C, K&amp;R is probably the best book available. In addition to that book, you should also get a more modern book about C since K&amp;R doesn't teach you anything about function prototypes and buffer overflows (one of the main reasons that software written in C is often unreliable).</p>\n\n<p>For example, <a href=\"https://clc-wiki.net/wiki/K%26R2_solutions:Chapter_1:Exercise_12\" rel=\"nofollow noreferrer\">the page you linked</a> has a solution containing <code>char buffer[1024];</code>. That solution will fail with unpredictable behavior as soon as you pass it a file containing very long words, as the buffer will overflow and the C program will not reliably crash but is free to do anything it wants, including crashing or making daemons fly out of your nose. This is called <a href=\"https://en.wikipedia.org/wiki/Undefined_behavior\" rel=\"nofollow noreferrer\"><em>undefined behavior</em></a>.</p>\n\n<p>There's not much to improve about your code. To make it modern, you simply have to replace one line:</p>\n\n<pre><code>main() // before\nint main(void) // after\n</code></pre>\n\n<p>After that, you should tell your editor to <em>format the source code</em>. This will indent the innermost line <code>c = getchar()</code> a bit more, so that it is clearly inside the <code>while</code> loop.</p>\n\n<pre><code>// before:\nwhile(c == ' '|| c == '\\t' || c == '\\n')\n c = getchar();\n\n// after:\nwhile (c == ' '|| c == '\\t' || c == '\\n')\n c = getchar();\n</code></pre>\n\n<p>Some other reviewers will say that you <em>must always use braces</em> in the <code>if</code> and <code>while</code> statements, but I disagree. It's enough to let your editor or <a href=\"https://en.wikipedia.org/wiki/Integrated_development_environment\" rel=\"nofollow noreferrer\">IDE</a> format the source code automatically, this will make it obvious when your code is indented wrongly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T17:57:55.703", "Id": "465453", "Score": "0", "body": "What about ctype.h and isspace(int c)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T19:10:10.187", "Id": "465458", "Score": "0", "body": "Indeed, that would have been simpler." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T16:13:31.960", "Id": "237383", "ParentId": "237382", "Score": "3" } } ]
{ "AcceptedAnswerId": "237383", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T15:52:34.017", "Id": "237382", "Score": "6", "Tags": [ "c" ], "Title": "K&R - The C programming language Exercise1-12" }
237382
<p>Tic-tac-toe is small enough to be solved completely but since I have a slow computer and this is an interesting exercise, I want to build the fastest possible minimax tic-tac-toe implementation in CPython.</p> <p>I welcome any comments on style, performance and cleaning up code. Here are some points I'm particularly unsure about:</p> <p><strong>TicTacToe</strong></p> <ul> <li>I currently have functions to undo (<code>TicTacToe.unmark()</code>) and do (<code>TicTacToe.mark()</code>) a move. I worry, that this is unneeded repetition.</li> <li>I use the '@property' decorator when a method is more like a fundamental property of the game then an action taken. Am I using the decorator correctly?</li> </ul> <p><strong>MiniMax</strong></p> <ul> <li>Should I separate out code storing symmetric boards into a new method for readability?</li> <li>What can I do about my <code>MiniMax.best_move()</code> method. While it is short, I feel it could be more readable.</li> </ul> <p><strong>Code</strong></p> <p>tictactoe.py</p> <pre><code>import numpy as np class TicTacToe: def __init__(self, board=None): if board is None: self.board = np.zeros((3, 3), dtype=np.int8) elif self._check_board_valid(board): self.board = board.astype(dtype=np.int8) def mark(self, pos, inplace=True): if self.winner is None: if pos in self.zero_positions: if inplace: self.board[pos] = self.player else: b = self.board.copy() b[pos] = self.player return TicTacToe(board=b) elif 0 &gt; pos[0] or pos[0] &gt;= 3 or 0 &gt; pos[1] or pos[1] &gt;= 3: raise IndexError(f"{pos} is outside board") else: raise IndexError(f"board marked at {pos} already") def un_mark(self, pos, inplace=True): if pos in self.possible_undos: if inplace: self.board[pos] = 0 else: b = self.board.copy() b[pos] = 0 return TicTacToe(board=b) elif 0 &gt; pos[0] or pos[0] &gt;= 3 or 0 &gt; pos[1] or pos[1] &gt;= 3: raise IndexError(f"{pos} is outside board") else: raise IndexError(f"Player {-1 * self.player} cannot un-mark board at {pos}") @property def winner(self): """Returns winner of game 1 : Player 1 has won -1 : PLayer 2 has won 0 : Draw None: No winner yet""" # check rows if any(abs(self.board.sum(axis=1)) == 3): s = self.board.sum(axis=1) return s[abs(s) == 3][0] // 3 # check columns if any(abs(self.board.sum(axis=0)) == 3): s = self.board.sum(axis=0) return s[abs(s) == 3][0] // 3 # check diagonal 0 elif abs(np.diag(self.board).sum()) == 3: return np.diag(self.board).sum() // 3 # check other diagonal elif abs(np.diag(np.fliplr(self.board)).sum()) == 3: return np.diag(np.fliplr(self.board)).sum() // 3 # draw if all positions filled but still no winner elif not (self.board == 0).any(): return 0 # None is returned automatically if no other condition has been met @property def zero_positions(self): return tuple(zip(*np.where(self.board == 0))) @property def possible_undos(self): return tuple(zip(*np.where(self.board == -1 * self.player))) @property def player(self): try: sum_turn_dict = { 0: 1, 1: -1 } return sum_turn_dict[self.board.sum()] except KeyError: raise ValueError("Invalid board: cannot determine whose turn it is") @staticmethod def _check_board_valid(board): if type(board) is np.ndarray: if board.shape == (3, 3): if np.logical_or(abs(board) == 1, board == 0).all(): if board.sum() in [0, 1]: return True else: raise ValueError("Invalid board: cannot determine whose turn it is") else: raise ValueError("Board must contain only 1, -1 and 0") else: raise ValueError(f"Board must have shape (3, 3), not {board.shape}") else: raise TypeError(f"Board must be ndarray, not {type(board)}") def __repr__(self): return self.board.__repr__() def __str__(self): return str(self.board) </code></pre> <p>minimax.py</p> <pre><code>from TicTacToe.tictactoe import TicTacToe import numpy as np class MiniMax: def __init__(self): self.rate_dict = {} self.optimal = { 1: max, -1: min } self.positions_evaluated = 0 def rate(self, game): if str(game) in self.rate_dict: value = self.rate_dict[str(game)] elif game.winner is not None: value = game.winner else: value = -1 * game.player for pos in game.zero_positions: game.mark(pos) r = self.rate(game=game) game.un_mark(pos) value = self.optimal[game.player](value, r) if value == game.player: break self.rate_dict[str(game)] = value # Use symmetry (flip and three rotations) self.rate_dict[str(np.rot90(game.board, k=1))] = value self.rate_dict[str(np.rot90(game.board, k=2))] = value self.rate_dict[str(np.rot90(game.board, k=3))] = value flipped_board = game.board.T self.rate_dict[str(flipped_board)] = value self.rate_dict[str(np.rot90(flipped_board, k=1))] = value self.rate_dict[str(np.rot90(flipped_board, k=2))] = value self.rate_dict[str(np.rot90(flipped_board, k=3))] = value self.positions_evaluated += 1 return value def best_move(self, board): game = TicTacToe(board) pos_list = ((pos, self.rate(game.mark(pos, inplace=False))) for pos in game.zero_positions) return self.optimal[game.player](pos_list, key=lambda tup: tup[1])[0] </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T16:42:49.457", "Id": "237384", "Score": "3", "Tags": [ "python", "python-3.x", "game", "numpy" ], "Title": "Clean and fast MiniMax for numpy implementation of Tic-Tac-Toe" }
237384
<p>Given two input arrays <code>[-1, 8, 3]</code> and <code>[3, 7, 2]</code> your function will return true if any two of the numbers in the first array add up to the any numbers in the second array.</p> <p><span class="math-container">\$-1 + 3 = 2 \therefore \text{True}\$</span></p> <p>My algorithm simply takes all the pairs from the first input and check if they exist in second array set which the complexity of set lookup is <span class="math-container">\$O(1)\$</span>. Overall complexity is <span class="math-container">\$O(n^2)\$</span> I'm pretty sure there should be a better algorithm leveraging hash tables or sorting and doing a binary search. Is there a way to make time complexity more efficient?</p> <p>My code:</p> <pre><code>def arraySum(inputs, tests): # iterating through all possible sums and check if it exists in test by using a test set which #makes the complexity better with O(1) lookup in set. my_set=set(tests) for i in range(len(inputs)-1): for j in range(i+1,len(inputs)): my_sum=inputs[i]+inputs[j] if my_sum in my_set: return True return False #this will take care of an edge case when there is one input from each arr </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T13:36:54.847", "Id": "465713", "Score": "0", "body": "OK Hash set creation for a list of size n will be \\$O(n)\\$, but the check will only be \\$O(1)\\$ if the data distributes well over the hash buckets. If this is part of a challenge with python specified, expect at least one dataset with rigged data that gets you an \\$O(n)\\$ check." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T14:27:59.273", "Id": "465715", "Score": "0", "body": "if python2 is possible, you may want to use xrange() instead of range()." } ]
[ { "body": "<p>Instead of using nested <code>for</code> loops for your case - Python provides a more flexible and performant features with <code>itertools</code> module, suitably - <a href=\"https://docs.python.org/3/library/itertools.html#itertools.combinations\" rel=\"nofollow noreferrer\"><code>itertools.combinations(iterable, r)</code></a> which returns generator of <code>r</code> length subsequences of elements from the input <code>iterable</code>.</p>\n\n<p>Besides, don't forget about good naming: <code>arraySum</code> is not a good one (at least <code>array_sum</code>). I'd suggest <code>check_sum</code> as alternative.</p>\n\n<p>Optimized version:</p>\n\n<pre><code>import timeit\nfrom itertools import combinations\n\n\ndef check_sum(input_lst, test_lst):\n search_set = set(test_lst)\n for pair in combinations(input_lst, 2):\n if (pair[0] + pair[1]) in search_set:\n return True\n return False\n\n\nlst1 = [-1, 8, 3]\nlst2 = [3, 7, 2]\n</code></pre>\n\n<hr>\n\n<p>Now, let's compare <em>running time</em> performance between <code>arraySum</code> and <code>check_sum</code>:</p>\n\n<pre><code>print(timeit.timeit('arraySum(lst1, lst2)', globals=globals(), number=1))\nprint(timeit.timeit('check_sum(lst1, lst2)', globals=globals(), number=1))\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>2.621993189677596e-06\n1.6039994079619646e-06\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T20:30:56.130", "Id": "237397", "ParentId": "237386", "Score": "4" } }, { "body": "<p>Your function code can be simplified to one line.</p>\n\n<pre><code>from itertools import combinations\nfrom typing import List\n\ndef array_sum(inputs: List[int], tests: List[int]) -&gt; bool:\n \"\"\"\n Determines if any two integers in `inputs` \n add up to any integer in `tests`.\n\n :param List[int] inputs: Input data\n :param List[int] tests: Numbers to test against input data\n\n :return bool: True if combination is found, False otherwise\n \"\"\"\n return any(sum(pair) in set(tests) for pair in combinations(inputs, 2))\n</code></pre>\n\n<p>This uses docstrings to document what the function does, and what types the function accepts and returns.</p>\n\n<p>The main meat of the function occurs in one line. <a href=\"https://docs.python.org/3/library/functions.html#any\" rel=\"noreferrer\"><code>any()</code></a> returns <code>True</code> if any element in the given iterable is <code>True</code>. Converting <code>tests</code> to a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#sets\" rel=\"noreferrer\"><code>set</code></a> removes any duplicate values, possibly reducing the number of iterations. The <a href=\"https://docs.python.org/2/library/itertools.html#itertools.combinations\" rel=\"noreferrer\"><code>combinations</code></a> returns subsequences of the iterable. Because you want two numbers to add up to one number in the test set, the value <code>2</code> is passed to the function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T23:11:55.407", "Id": "465480", "Score": "7", "body": "And the fact that you didn't cache `set(tests)` means this might be \\$O(n^{2} m)\\$ instead of \\$O(n^{2} + m)\\$, depending on if the compiler decides it can cache this for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T15:07:39.823", "Id": "465574", "Score": "5", "body": "@DavidG. Code Review is about improving code quality. Knocking an answer because it's not improving complexity and is instead making code more Pythonic, is not a site I want to contribute." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T17:08:52.140", "Id": "465598", "Score": "0", "body": "@Peilonrayz In David's defense, OP very clearly asks for an improvement to complexity: \"Is there a way to make time complexity more efficient?\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T17:15:43.330", "Id": "465599", "Score": "1", "body": "@AleksandrH A core part of Code Review is \"do you want any and all of your code reviewed\". We allow specific questions, but by posting you allow a review of anything." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T22:31:44.803", "Id": "237400", "ParentId": "237386", "Score": "7" } }, { "body": "<p>I believe you could reduce it to <span class=\"math-container\">\\$O(n\\log{n}+m\\log{n}+n m)\\$</span> if you want. </p>\n\n<p>Sort the inputs, then iterate over the tests and for each one, do a two variable iteration over the inputs, where you start as close to the test value/2, and move one index in the increasing direction and the other in the decreasing direction depending on whether the sum is less than or greater than the test value. </p>\n\n<p>This is somewhat confusing, so a partial implementation is:</p>\n\n<pre><code>def one_test(sorted_array, test_value):\n\n index1 = index_just_under(sorted_array, test_value/2)\n index2 = index1 + 1\n\n while (index1&gt;=0) and (index2 &lt; len(sorted_array)):\n sum = sorted_array[index1] + sorted_array[index2];\n if sum == test_value:\n return True\n if sum &gt; test_value:\n index1 = index1 - 1\n else:\n index2 = index2 + 1\n\n return False\n</code></pre>\n\n<p>Function <code>index_just_under</code> would be an <span class=\"math-container\">\\$O(\\log{n})\\$</span> method to find our initial cut point. It returns the number of entries in the array below the second parameter, minus 1. Given a sorted array, a binary search can be used.</p>\n\n<p>The rest of this <code>one_test</code> function is <span class=\"math-container\">\\$O(n)\\$</span>. This function is executed <span class=\"math-container\">\\$m\\$</span> times, and the initial sort is <span class=\"math-container\">\\$O(n\\log{n})\\$</span>.</p>\n\n<p>While this might be a poor savings of the two input arrays are the same size, if tests array is much smaller, this could be a big saving.</p>\n\n<p>If you start the indexes at the <code>0</code> and <code>len(sorted array) - 1</code>, you might be able to eliminate the <code>index_just_under()</code> call, reducing the time by <span class=\"math-container\">\\$O(m\\log{n})\\$</span>. On the other hand, it would eliminate any early-outs in the <span class=\"math-container\">\\$O(n m)\\$</span> loops. Effectiveness could depend on your expected number ranges.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T13:20:28.727", "Id": "465560", "Score": "2", "body": "@DavidG., ok, as the OP mentioned *time complexity* (citing), have you measured time performance on 2 input lists, how fast is it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T23:35:47.770", "Id": "465641", "Score": "0", "body": "@RomanPerekhrest I have not timed the code because I have not written a complete implementation. I *have* calculated time complexity. Note all the \\$O(...)\\$ in the text. And depending on the list sizes, his implementation may well be the fastest, just as bubble sort can easily be the fastest sort." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T22:44:55.547", "Id": "237401", "ParentId": "237386", "Score": "8" } }, { "body": "<p>Your problem is at least as hard as 3SUM, <a href=\"https://en.wikipedia.org/wiki/3SUM\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/3SUM</a> (in fact it is very likely equivalent with a little thought).</p>\n\n<p>Let us first see how to reduce a 3SUM problem to your problem.</p>\n\n<p>3SUM says I have an array <span class=\"math-container\">\\$X\\$</span>, and I want to find out if there are <span class=\"math-container\">\\$x\\$</span>, <span class=\"math-container\">\\$y\\$</span>, <span class=\"math-container\">\\$z\\$</span> in <span class=\"math-container\">\\$X\\$</span> such that <span class=\"math-container\">$$x + y + z = 0$$</span></p>\n\n<p>Let us define <span class=\"math-container\">\\$A = X\\$</span> and <span class=\"math-container\">\\$B = [-a\\ \\$</span> for <span class=\"math-container\">\\$ a \\$</span> in <span class=\"math-container\">\\$ A]\\$</span></p>\n\n<p>Then let us solve your problem, i.e. determine if there are <span class=\"math-container\">\\$x\\$</span> and <span class=\"math-container\">\\$y\\$</span> in <span class=\"math-container\">\\$A\\$</span> such that <span class=\"math-container\">\\$x + y\\$</span> is in <span class=\"math-container\">\\$B\\$</span>, that is, there is some <span class=\"math-container\">\\$z\\$</span> in <span class=\"math-container\">\\$A\\$</span> such that <span class=\"math-container\">\\$x + y = -z\\$</span>, then we have determined whether <span class=\"math-container\">\\$X\\$</span> has <span class=\"math-container\">\\$x\\$</span>, <span class=\"math-container\">\\$y\\$</span>, <span class=\"math-container\">\\$z\\$</span> such that <span class=\"math-container\">\\$x+y+z=0\\$</span>.</p>\n\n<p>Ergo, suppose we can solve your problem in better than <span class=\"math-container\">\\$O(nm)\\$</span> time (and not such that the case <span class=\"math-container\">\\$n=m\\$</span> doesn't magically reduce to <span class=\"math-container\">\\$n^2\\$</span>) where <span class=\"math-container\">\\$|A| = n\\$</span> and <span class=\"math-container\">\\$|B| = m\\$</span></p>\n\n<p>Then for a 3SUM problem we could reduce it to your problem and solve that, thus solving the 3SUM problem in better than <span class=\"math-container\">\\$O(n^2)\\$</span> time (in this case <span class=\"math-container\">\\$n = m\\$</span>)</p>\n\n<p>Given that it's a long standing conjecture whether you can do <span class=\"math-container\">\\$O(n^{2-e})\\$</span> for some <span class=\"math-container\">\\$e &gt; 0\\$</span> for 3SUM I'm inclined to suggest you aren't going to find better than <span class=\"math-container\">\\$O(nm)\\$</span>, ignoring that as detailed in the wikipedia link above there are actually marginally better time complexities which have been achieved.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T20:47:11.343", "Id": "465628", "Score": "0", "body": "No, I am saying that I have some problem like 'making a friend', and I have another problem like 'sharing my feelings', and let's say that I can work out a simple (i.e. not time complex) way to turn 'making a friend' into 'sharing my feelings' (presumably the process is I make a friend and then corner them in a room and tell them all the things that make me sad). Then since making a friend implies I can share my feelings, if I know that sharing my feelings is very hard, then making a friend must be very hard. In this analogy making a friend is OPs problem and sharing my feelings is 3SUM." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T20:53:03.087", "Id": "465629", "Score": "0", "body": "Sorry, I feel like I'm wasting your time. I posted my previous comment and decided it wouldn't result in a good outcome, so deleted it. But you read it too fast ‎" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T00:29:52.223", "Id": "465644", "Score": "0", "body": "Nice analysis, and I agree, if \\$n=m\\$ then you can't do better than \\$O(n^2)\\$. On the other hand, if m is comparatively tiny, you can do fairly well." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T20:02:19.493", "Id": "237454", "ParentId": "237386", "Score": "3" } }, { "body": "<p>I think I overlooked the obvious. Without sorting, if you do the loops as:</p>\n\n<pre><code>def arraySum2(inputs, tests):\n my_set=set(inputs)\n for a in inputs:\n for b in tests:\n if (b-a) in my_set:\n return True\n return False\n</code></pre>\n\n<p>Then you get <span class=\"math-container\">\\$O(n m + n)\\$</span></p>\n\n<p>This will be faster than the original (or itertools based variants) around <span class=\"math-container\">\\$m&lt;{{n-1}\\over{2}}\\$</span> as the original does <span class=\"math-container\">\\${n(n-1)}\\over2\\$</span> tests and this does <span class=\"math-container\">\\$n m\\$</span>.</p>\n\n<p>If you are doing the test a lot, it is thus worth implementing both forms, with a test to decide which form to use.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T13:30:25.327", "Id": "237493", "ParentId": "237386", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T17:17:18.990", "Id": "237386", "Score": "11", "Tags": [ "python", "performance", "algorithm", "complexity" ], "Title": "Are the sum of two numbers desired?" }
237386
<p>I am quite a novice. The below code does what I require but I was hoping you could help me speeding it up and simplifying it please. I know should start with basics when learning VBA..but it's just so exciting. Probably it would be faster if I applied For i to x, next i method</p> <p>Could you please help or guide me to a better solution, simplify/speed up? Thank you in advance </p> <p>I have:</p> <ol> <li><strong>Results</strong> sheet2 Range A7:BM107</li> <li><strong>Branches</strong> sheet2 B7:B107</li> <li><strong>Questions</strong> sheet2 D6:BM6</li> <li><strong>Poor to N/A</strong> is rated from 1 to 6</li> <li><strong>Option Labels</strong> sheet4 range K23:K28</li> <li><strong>Option Score</strong> sheet4 range N23:N28</li> </ol> <p>The code:</p> <ul> <li>Extracts unique branch names from B7:B110</li> <li>Lists them starting from B110</li> <li>For each Option Label (Poor, Average,Adequate, Good, Very Good, N/A") it creates Branch List</li> <li>For each Branch List under corresponding question it counts Option Score Occurence</li> <li>then creates another group for Option 2 and repeats the process</li> <li>then creates another group for Option 3 and so on</li> <li>Results Look Like this: <a href="https://i.stack.imgur.com/n0rVv.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/n0rVv.jpg" alt="Results"></a></li> <li>Count looks like this:</li> </ul> <p><a href="https://i.stack.imgur.com/rUTK2.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/rUTK2.jpg" alt="Count"></a></p> <pre><code>Sub GetResults() Dim vaData As Variant Dim colUnique As Collection Dim aOutput() As Variant Dim i As Long Dim start As Range Dim BranchesList As Range Dim LastRow As Long Dim BC As Integer 'count of dynamic branches Application.ScreenUpdating = False Sheet2.Range("B110:Bm500").ClearContents Sheet2.Range("B110:Bm500").ClearFormats '///////////////////////// EXTRACT UNIQUE BRANCHES //////////////////// 'Put the data in an array BranchesSurveyed = Sheet2.Range("b7:b107").Value 'Create a new collection Set colUnique = New Collection 'Loop through the data For i = LBound(BranchesSurveyed, 1) To UBound(BranchesSurveyed, 1) 'Collections can't have duplicate keys, so try to 'add each item to the collection ignoring errors. 'Only unique items will be added On Error Resume Next colUnique.Add BranchesSurveyed(i, 1), CStr(BranchesSurveyed(i, 1)) On Error GoTo 0 Next i 'size an array to write out to the sheet ReDim aOutput(1 To colUnique.Count, 1 To 1) 'Loop through the collection and fill the output array For i = 1 To colUnique.Count aOutput(i, 1) = colUnique.Item(i) Next i Set start = Range("b110") 'first cell to contain the list 'Write the unique values to column B start.Resize(UBound(aOutput, 1), UBound(aOutput, 2)).Value = aOutput 'set range containing current brancheslist Set BranchesList = Range(start, start.Offset(colUnique.Count - 2, 0)) 'sort names of branches used BranchesList.Select With Selection .Sort key1:=start, order1:=xlAscending, Header:=xlNo End With '////////////////////////// COUNT EACH OPTION FOR EACH BRANCH ///////////////// BC = colUnique.Count 'count option 1 'add title "Poor" With start.Offset(-1) .Value = "Count " &amp; Sheet4.Range("K23").Value .Font.Bold = True End With 'fill next column with title With start.Offset(0, 1).Resize(BC - 1, 1) .Value = Sheet4.Range("K23").Value End With 'fill formula for title in question rows With start.Offset(0, 2).Resize(BC - 1, 62) .FormulaR1C1 = "=IFERROR(IF(RC2="""",0,COUNTIFS(R7C:R107C,Control!R23C14,R7C2:R107C2,RC2)),0)" End With 'count option 2 'add title With start.Offset(BC - 1) .Value = "Count " &amp; Sheet4.Range("K24").Value .Font.Bold = True End With 'copy branches list BranchesList.Select Selection.Copy start.End(xlDown).Offset(1) Application.CutCopyMode = False 'fill next column with title With start.Offset(BC, 1).Resize(BC - 1, 1) .Value = Sheet4.Range("K24").Value End With 'fill formula for title in question rows With start.Offset(BC, 2).Resize(BC - 1, 62) .FormulaR1C1 = "=IFERROR(IF(RC2="""",0,COUNTIFS(R7C:R107C,Control!R24C14,R7C2:R107C2,RC2)),0)" End With 'count option 3 'add title With start.Offset(BC * 2 - 1) .Value = "Count " &amp; Sheet4.Range("K25").Value .Font.Bold = True End With 'copy branches list BranchesList.Select Selection.Copy start.End(xlDown).Offset(1) Application.CutCopyMode = False 'fill next column with title With start.Offset(BC * 2, 1).Resize(BC - 1, 1) .Value = Sheet4.Range("K25").Value End With 'fill formula for title in question rows With start.Offset(BC * 2, 2).Resize(BC - 1, 62) .FormulaR1C1 = "=IFERROR(IF(RC2="""",0,COUNTIFS(R7C:R107C,Control!R25C14,R7C2:R107C2,RC2)),0)" End With 'count option 4 'add title With start.Offset(BC * 3 - 1) .Value = "Count " &amp; Sheet4.Range("K26").Value .Font.Bold = True End With 'copy branches list BranchesList.Select Selection.Copy start.End(xlDown).Offset(1) Application.CutCopyMode = False 'fill next column with title With start.Offset(BC * 3, 1).Resize(BC - 1, 1) .Value = Sheet4.Range("K26").Value End With 'fill formula for title in question rows With start.Offset(BC * 3, 2).Resize(BC - 1, 62) .FormulaR1C1 = "=IFERROR(IF(RC2="""",0,COUNTIFS(R7C:R107C,Control!R26C14,R7C2:R107C2,RC2)),0)" End With 'count option 5 'add title With start.Offset(BC * 4 - 1) .Value = "Count " &amp; Sheet4.Range("K27").Value .Font.Bold = True End With 'copy branches list BranchesList.Select Selection.Copy start.End(xlDown).Offset(1) Application.CutCopyMode = False 'fill next column with title With start.Offset(BC * 4, 1).Resize(BC - 1, 1) .Value = Sheet4.Range("K27").Value End With 'fill formula for title in question rows With start.Offset(BC * 4, 2).Resize(BC - 1, 62) .FormulaR1C1 = "=IFERROR(IF(RC2="""",0,COUNTIFS(R7C:R107C,Control!R27C14,R7C2:R107C2,RC2)),0)" End With 'count option 6 'add title With start.Offset(BC * 5 - 1) .Value = "Count " &amp; Sheet4.Range("K28").Value .Font.Bold = True End With 'copy branches list BranchesList.Select Selection.Copy start.End(xlDown).Offset(1) Application.CutCopyMode = False 'fill next column with title With start.Offset(BC * 5, 1).Resize(BC - 1, 1) .Value = Sheet4.Range("K28").Value End With 'fill formula for title in question rows With start.Offset(BC * 5, 2).Resize(BC - 1, 62) .FormulaR1C1 = "=IFERROR(IF(RC2="""",0,COUNTIFS(R7C:R107C,Control!R28C14,R7C2:R107C2,RC2)),0)" End With Application.ScreenUpdating = True End Sub </code></pre>
[]
[ { "body": "<p>Turn on <a href=\"https://docs.microsoft.com/en-us/office/vba/Language/Reference/User-Interface-Help/option-explicit-statement\" rel=\"noreferrer\">Option Explicit</a>. From the VBIDE menu at the top Tools>Options to display the Options dialog>Editor tab>Code Settings group>Require Variable Declaration.</p>\n\n<p><a href=\"https://i.stack.imgur.com/SVPZa.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/SVPZa.png\" alt=\"enter image description here\"></a></p>\n\n<p>Tick that check box. From that point on <code>Option Explicit</code> will always be added to the top of every new (Standard, Form, Class) module you create. Future-you will thank you. This mandates that all your variables are declared before use IE <code>Dim branchesSurveyed As Range</code> before they can be used. For any existing modules you'll need to go back and add them by hand. Well worth doing because once you do you'll notice that your variable <code>BranchesSurveyed</code> is never actually declared anywhere which means it's a Variant. You can confirm this by stepping into your code (Hotkey: <code>F8</code>) and examining the locals window View>Locals Window.</p>\n\n<hr>\n\n<p>Explicitly declare your Subs as Public. This is achieved by including <code>Public</code> when you declare it as part of the <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/sub-statement\" rel=\"noreferrer\">Sub statement</a>. <code>Sub Foo()</code> and <code>Public Sub Foo()</code> are both public but the latter makes your intent explicitly clear because you included the Public keyword.</p>\n\n<hr>\n\n<p>Indentation. You have extra indentation under your EXTRACT UNIQUE BRANCHES banner. No need for that. You will actually refactor that and pull it into its own private method which I'll explain later. Keep indentation consistent, typically 1 TAB within each logical block. The example code block below shows this. The <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/fornext-statement\" rel=\"noreferrer\">For...Next statement</a> is a logical block, the <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/with-statement\" rel=\"noreferrer\">With statement</a> is another.</p>\n\n<pre><code>Public Sub Foo()\n Dim bar As String\n bar = Sheet1.Range(\"A1\").Value2\n\n Debug.Print bar\n\n Dim counter As Long\n For counter = 1 To 10\n Sheet1.Cells(counter, \"C\").Value2 = counter\n Next\n\n With Sheet2.Range(\"A1:A10\")\n .NumberFormat = \"General\"\n .Font.Bold = True\n .Font.Italic = True\n .BorderAround XlLineStyle.xlContinuous, XlBorderWeight.xlThick, Color:=RGB(120, 255, 18)\n End With\nEnd Sub\n</code></pre>\n\n<p><a href=\"http://rubberduckvba.com/\" rel=\"noreferrer\">http://rubberduckvba.com/</a> can help you with that. It's an open source COM add-in for VBA hosts. Take your original code and paste it into <a href=\"http://rubberduckvba.com/Indentation\" rel=\"noreferrer\">http://rubberduckvba.com/Indentation</a> to indent it an example. Rubberduck (RD) does a lot more than that too.</p>\n\n<p>***Note: I'm a contributing member to RD and openly biased in favor of it.</p>\n\n<hr>\n\n<p>Hungarian Notation (HN) is a holdover from a time long ago. <code>vaData</code>, <code>colUnique</code>, <code>aOutput</code> I'm assuming are using this for Variant, Collection, and Array. If you need to know the type of a variable place your cursor on or within the variable and from the menu Edit>Quick Info (Hotkey: <code>Ctrl+I</code>) to display its type, as shown below. RD warns about common HN prefixes.</p>\n\n<p><a href=\"https://i.stack.imgur.com/06qnS.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/06qnS.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>You have a Wall-of-Declarations at the top. Declare variables right before their use. This has a few benefits. One is it aids in refactoring/restructuring your code by allowing you to get the declaration and first use without a lot of scrolling. A second is it allows you to see unused variables easier. Notice that <code>vaData</code> and <code>LastRow</code> aren't actually used anywhere. They're declared but, never used. With a wall of declarations at the top this is something commonly missed. RD gives code inspections about these unused variables.</p>\n\n<hr>\n\n<p>Static cell references. <code>Sheet2.Range(\"b7:b107\")</code> will break if a row is entered above or a column to the left. How? The cells will shift but your text <code>\"b7:b107\"</code> won't. To protect yourself from this breaking change use named ranges. These can be added from the Formulas tab>Defined Names group>Name Manager button to display the Name Manager dialog (Hotkey: <code>Ctrl+F3</code>). Click New to display the New Name dialog and enter in the name you want to use. I've assumed the name is <code>BranchLocations</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/J4VcA.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/J4VcA.png\" alt=\"enter image description here\"></a></p>\n\n<p>There are also static references <code>\"K23\"</code> through <code>\"K28\"</code>. Your variable names are already good. Descriptive variable names make understanding the code a lot easier. Keep it up by doing this with your named ranges too. Future-you will thank present-you for doing so.</p>\n\n<hr>\n\n<p>Headers like <code>'///////////////////////// EXTRACT UNIQUE BRANCHES ////////////////////</code> are a signpost/trail-marker for a dedicated Sub/Function through <a href=\"https://en.wikipedia.org/wiki/Code_refactoring\" rel=\"noreferrer\">refactoring</a>. What's refactoring?</p>\n\n<blockquote>\n <p>Change <strong>how</strong> somethings being done without changing the result it produces.</p>\n</blockquote>\n\n<p>You still end up the same result but it's now achieved in a better/improved way. Do this by adding a reference. Do that from the menu Tools>References to display the References dialog. Scroll down to the M's and look for <code>Microsoft Scripting Runtime</code>. Add a check mark and accept with OK.</p>\n\n<p><a href=\"https://i.stack.imgur.com/q2ER2.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/q2ER2.png\" alt=\"enter image description here\"></a></p>\n\n<p>This new reference gives you access to another assembly (think toolbox as a layman's analogy) that has just the tool you need, a <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dictionary-object\" rel=\"noreferrer\">Dictionary object</a>. The Dictionary object has an <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/exists-method\" rel=\"noreferrer\">Exists method</a> (in VBA terms a boolean function) which allows you to check if it already contains the item. As I mentioned previously about the banner comment refactoring, here it is below. The refactoring using the new Dictionary object.</p>\n\n<pre><code>Private Function GetUniqueBranches(ByVal sourceArea As Range) As Scripting.Dictionary\n Set GetUniqueBranches = New Scripting.Dictionary\n Dim surveyCell As Range\n For Each surveyCell In sourceArea\n If Not GetUniqueBranches.Exists(surveyCell.Value2) Then\n GetUniqueBranches.Add surveyCell.Value2, CStr(surveyCell.Value2)\n End If\n Next\nEnd Function\n</code></pre>\n\n<p>This function is now called as shown below. You supply a source area that is a Range object and it returns you a Dictionary object with the unique values.</p>\n\n<pre><code>Dim uniqueBranches As Scripting.Dictionary\nSet uniqueBranches = GetUniqueBranches(Sheet2.Range(\"BranchLocations\"))\n</code></pre>\n\n<hr>\n\n<p>Implicit sheet references. <code>Set start = Range(\"b110\")</code> is implicitly accessing whatever sheet happens-to-be the active sheet when this code is run. These are ticking time bombs waiting to blow up at the least convenient moment possible. Qualify them with the sheet it's on <code>Sheet2.Range(\"b110\")</code>. Another static cell reference. The unqualified Range also occurs when <code>BranchesList</code> is assigned <code>Set BranchesList = Range(...)</code>. And looking at your code that can be condensed down to the code below</p>\n\n<pre><code>Dim branchCount As Long\nbranchCount = uniqueBranches.Count\n\nDim start As Range\nSet start = Sheet2.Range(\"UniqueBranchLocations\").Cells(1, 1)\n\n'set range containing current brancheslist\nDim BranchesList As Range\nSet BranchesList = start.Resize(RowSize:=branchCount)\nBranchesList.Value2 = Application.WorksheetFunction.Transpose(uniqueBranches.Items)\n</code></pre>\n\n<hr>\n\n<p><code>Range.Select</code> immediately followed by <code>Selection.Anything</code> is another signpost. <em>Rarely</em> is <code>.Select</code> required. Cut out <code>Select</code> and <code>Selection</code> to end up with <code>BranchesList.Sort ...</code></p>\n\n<hr>\n\n<p>The rest of your logic with Option 1-6 extract that into its own Sub and refactor the logic a bit. It looks/feels like you can consolidate some of the logic into helper functions. Putting all that together you end up with the code below. </p>\n\n<pre><code>Option Explicit\n\nPublic Sub GetResults()\n Application.ScreenUpdating = False\n\n With Sheet2.Range(\"UniqueBranchLocations\")\n .ClearContents\n .ClearFormats\n End With\n\n Dim uniqueBranches As Scripting.Dictionary\n Set uniqueBranches = GetUniqueBranches(Sheet2.Range(\"BranchLocations\"))\n Dim branchCount As Long\n branchCount = uniqueBranches.Count\n\n Dim start As Range\n Set start = Sheet2.Range(\"UniqueBranchLocations\").Cells(1, 1)\n\n Dim BranchesList As Range\n Set BranchesList = start.Resize(RowSize:=branchCount)\n BranchesList.Value2 = Application.WorksheetFunction.Transpose(uniqueBranches.Items)\n\n BranchesList.Sort key1:=start, order1:=xlAscending, Header:=xlNo\n\n CountEachOptionForEachBranch start, BranchesList, branchCount\n\n Application.ScreenUpdating = True\n\nEnd Sub\n\nPrivate Function GetUniqueBranches(ByVal sourceArea As Range) As Scripting.Dictionary\n Set GetUniqueBranches = New Scripting.Dictionary\n Dim surveyCell As Range\n For Each surveyCell In sourceArea\n If Not GetUniqueBranches.Exists(surveyCell.Value2) Then\n GetUniqueBranches.Add surveyCell.Value2, CStr(surveyCell.Value2)\n End If\n Next\nEnd Function\n\nPrivate Sub CountEachOptionForEachBranch(ByVal start As Range, ByVal BranchesList As Range, ByVal branchCount As Long)\n 'Refactored code with simplified logic.\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T18:13:07.020", "Id": "465611", "Score": "1", "body": "Hello. I didn't expect such a response. You've put so much helpful concise and detailed information that it feels like Christmas. I couldn't wait to get home and get through it. I'll definitely learn lots altho surely come back with more questions.. Thank you!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T05:03:24.117", "Id": "237415", "ParentId": "237388", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T17:23:42.797", "Id": "237388", "Score": "6", "Tags": [ "vba", "statistics" ], "Title": "Survey Populate with List, Option Label and Formula, VBA" }
237388
<p>I segmented an image into N superpixels and constructed a graph based on that in which each superpixel is considered as a node. The information about neighbor superpixels is stored in <code>glcms</code> array. The weight between each pair of neighboring superpixels is stored in matrix <code>W</code>. </p> <p>Finally, I want to compute <a href="https://math.stackexchange.com/q/728061">geodesic distance</a> between non-adjacent superpixels using <code>graphshortestpath</code> function. The following code does the mentioned process, however it is very time-consuming. Specifically, the last section of the code that computes geodesic distance takes more time than expected (more than 15 sec). </p> <pre class="lang-matlab prettyprint-override"><code> Img=imread('input.jpg'); [rows, columns, numberOfColorChannels] = size(Img); [L,N] = superpixels(Img,250); %Identifying neighborhood relationships glcms = graycomatrix(L,'NumLevels',N,'GrayLimits',[1,N],'Offset', [0,1;1,0]); %Create gray-level co-occurrence matrix from image glcms = sum(glcms,3); % add together the two matrices glcms = glcms + glcms.'; % add upper and lower triangles together, make it symmetric glcms(1:N+1:end) = 0; % set the diagonal to zero, we don't want to see "1 is neighbor of 1" data = zeros(N,3); for labelVal = 1:N redIdx = idx{labelVal}; greenIdx = idx{labelVal}+numRows*numCols; blueIdx = idx{labelVal}+2*numRows*numCols; data(labelVal,1) = mean(Img(redIdx)); data(labelVal,2) = mean(Img(greenIdx)); data(labelVal,3) = mean(Img(blueIdx)); end Euc=zeros(N); % Euclidean Distance for i=1:N for j=1:N if glcms(i,j)~=0 Euc(i,j)=sqrt(((data(i,1)-data(j,1))^2)+((data(i,2)-data(j,2))^2)+((data(i,3)-data(j,3))^2)); end end end W=zeros(N); W_num=zeros(N); W_den=zeros(N); OMG1=0.1; for i=1:N for j=1:N if(Euc(i,j)~=0) W_num(i,j)=exp(-OMG1*(Euc(i,j))); W_den(i,i)=W_num(i,j)+W_den(i,i); end end end for i=1:N for j=1:N if(Euc(i,j)~=0) W(i,j)=(W_num(i,j))/(W_den(i,i)); % Connectivity Matrix W end end end s_star_temp=zeros(N); %temporary variable for geodesic distance measurement W_sparse=zeros(N); W_sparse=sparse(W); for i=1:N for j=1:N if W(i,j)==0 &amp; i~=j; s_star_temp(i,j)=graphshortestpath(W_sparse,i,j); % Geodesic Distance end end end </code></pre> <p>The question is how to optimize the code to be more efficient , i.e. less time-consuming.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T19:28:35.967", "Id": "465462", "Score": "0", "body": "Please [format the code](https://stackoverflow.com/questions/23960822/how-can-i-reformat-code-in-matlab-editor/37362250) to make its structure clear to your potential reviewers. Having well-formatted and consistently indented code will help the reviewers concentrate on the more interesting topics." } ]
[ { "body": "<p>I'll first go through the different section and outline possible improvements, then give some general comments at the end. I am not checking the algorithm for correctness, as I don't know it.</p>\n\n<pre><code>Img=imread('input.jpg');\n[rows, columns, numberOfColorChannels] = size(Img);\n[L,N] = superpixels(Img,250);\n\n%Identifying neighborhood relationships\nglcms = graycomatrix(L,'NumLevels',N,'GrayLimits',[1,N],'Offset', [0,1;1,0]); %Create gray-level co-occurrence matrix from image\nglcms = sum(glcms,3); % add together the two matrices\nglcms = glcms + glcms.'; % add upper and lower triangles together, make it symmetric\nglcms(1:N+1:end) = 0; % set the diagonal to zero, we don't want to see \"1 is neighbor of 1\"\n</code></pre>\n\n<p>You need to have defined <code>idx</code> by now, but you haven't, so the code doesn't run. Based on the <code>superpixels</code> documentation, you need to add <code>idx = label2idx(L);</code></p>\n\n<pre><code>data = zeros(N,3);\nfor labelVal = 1:N\n redIdx = idx{labelVal};\n greenIdx = idx{labelVal}+numRows*numCols;\n blueIdx = idx{labelVal}+2*numRows*numCols;\n data(labelVal,1) = mean(Img(redIdx));\n data(labelVal,2) = mean(Img(greenIdx));\n data(labelVal,3) = mean(Img(blueIdx));\nend \n</code></pre>\n\n<p>This is fine, it probably is fine to just write <code>data(labelVal,1) = mean(Img(idx{1:N}))</code>, etc. but the performance should be similar.</p>\n\n<pre><code>Euc = zeros(N);\n% Euclidean Distance\nfor i=1:N\n for j=1:N\n if glcms(i,j)~=0\n Euc(i,j)=sqrt(((data(i,1)-data(j,1))^2)+((data(i,2)-data(j,2))^2)+((data(i,3)-data(j,3))^2));\n end\n end\nend\n</code></pre>\n\n<p>This can be replaced by <code>Euc = pdist2(data,data).*(glcms~=0);</code></p>\n\n<pre><code>W=zeros(N);\nW_num=zeros(N);\n\nW_den=zeros(N);\nOMG1=0.1;\nfor i=1:N\n for j=1:N\n if(Euc(i,j)~=0)\n W_num(i,j)=exp(-OMG1*(Euc(i,j)));\n W_den(i,i)=W_num(i,j)+W_den(i,i);\n end\n end\nend\n</code></pre>\n\n<p>This can be replaced by <code>W_num = exp(-OMG1*Euc).*(Euc~=0);</code> and <code>W_den = sum(W_num);</code> (here <code>W_den</code> is a vector, not a matrix, but that's what you want because you were only using diagonal elements of your <code>W_den</code> matrix).</p>\n\n<pre><code>for i=1:N\n for j=1:N\n if(Euc(i,j)~=0)\n W(i,j)=(W_num(i,j))/(W_den(i,i)); % Connectivity Matrix W\n end\n end\nend\n</code></pre>\n\n<p>This can be replace by <code>W = W_num./W_den.';</code> and <code>W(isnan(W)) = 0;</code>.</p>\n\n<pre><code>s_star_temp=zeros(N); %temporary variable for geodesic distance measurement\nW_sparse=zeros(N);\nW_sparse=sparse(W);\nfor i=1:N\n for j=1:N\n if W(i,j)==0 &amp; i~=j;\n s_star_temp(i,j)=graphshortestpath(W_sparse,i,j); % Geodesic Distance\n end\n end\nend\n</code></pre>\n\n<p>Here you define <code>W_sparse</code> twice, you don't need to initialise it with <code>zeros(N)</code>. This part is finding all shortest paths, and there is a builtin for that (which is probably a lot more efficient that generating the paths independently). Replace this whole section with <code>s_star_temp = graphallshortestpaths(W).*(W==0);</code> This seems to speed it up from ~15 seconds to 0.005 seconds.</p>\n\n<hr>\n\n<p>So this is how I would write your algorithm</p>\n\n<pre><code>Img = imread('input.jpg');\n[rows, columns, numberOfColorChannels] = size(Img);\n[L,N] = superpixels(Img,250);\n\nidx = label2idx(L);\n\n%Identifying neighborhood relationships\nglcms = graycomatrix(L,'NumLevels',N,'GrayLimits',[1,N],'Offset', [0,1;1,0]); %Create gray-level co-occurrence matrix from image\nglcms = sum(glcms,3); % add together the two matrices\nglcms = glcms + glcms.'; % add upper and lower triangles together, make it symmetric\nglcms(1:N+1:end) = 0; % set the diagonal to zero, we don't want to see \"1 is neighbor of 1\"\n\ndata = zeros(N,3);\nfor labelVal = 1:N\n data(labelVal,1) = mean(Img(idx{labelVal}));\n data(labelVal,2) = mean(Img(idx{labelVal}+rows*columns));\n data(labelVal,3) = mean(Img(idx{labelVal}+2*rows*columns));\nend\n\nEuc = sparse(pdist2(data,data).*(glcms~=0));\n\nOMG1 = 0.1;\n\nW_num = exp(-OMG1*Euc).*(Euc~=0);\nW_den = sum(W_num);\n\nW = W_num./W_den.';\nW(isnan(W)) = 0;\n\ns_star_temp = graphallshortestpaths(W).*(W==0);\n</code></pre>\n\n<p>Notice that I made <code>Euc</code> a sparse matrix. This makes the resulting matrices (<code>W_num</code>, <code>W_den</code>, <code>W</code>) also sparse. Your original code left them as full matrices, which was unnecessary. This code runs in about 1.3 seconds on my machine, compared to about 16 for your original code (with the picture I used).</p>\n\n<hr>\n\n<p>Minor general comments on your code:</p>\n\n<ul>\n<li>Use spaces around your <code>=</code> signs, it makes things easier to read</li>\n<li>Try to avoid very long lines, for example the <code>graycomatrix</code> line with its comment will go over the end of the window and be lost</li>\n<li>Write more comments</li>\n<li>Matlab best practice is to avoid using <code>i</code> and <code>j</code> for loop variables, prefer <code>ii</code> and <code>jj</code>. It's not very important, but <code>i</code> and <code>j</code> can also mean the imaginary unit.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:33:46.080", "Id": "465801", "Score": "0", "body": "@CrisLuengo `Euc` is symmetric so it doesn't matter, but it does let you do `W = W_num./W_den;` on the next line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:36:39.487", "Id": "465802", "Score": "0", "body": "You're absolutely right, didn't notice that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T23:33:17.933", "Id": "237402", "ParentId": "237390", "Score": "3" } }, { "body": "<p>Just a few tips and tricks to add to <a href=\"https://codereview.stackexchange.com/a/237402/151754\">David's excellent answer</a>.</p>\n\n<hr>\n\n<hr>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>data = zeros(N,3);\nfor labelVal = 1:N\n redIdx = idx{labelVal};\n greenIdx = idx{labelVal}+numRows*numCols;\n blueIdx = idx{labelVal}+2*numRows*numCols;\n data(labelVal,1) = mean(Img(redIdx));\n data(labelVal,2) = mean(Img(greenIdx));\n data(labelVal,3) = mean(Img(blueIdx));\nend \n</code></pre>\n\n<p>Here, <code>idx</code> is linear indices into the first channel of <code>Img</code>. <code>Img</code> is a 3D array, with channels along the 3rd dimension. The indexing <code>Img(redIdx)</code>, <code>Img(greenIdx)</code> and <code>Img(blueIdx)</code> simply index into <code>idx</code>, <code>idx+number_of_pixels</code> and <code>idx+2*number_of_pixels</code>. Instead, we can transform <code>Img</code> into a 2D array, where all pixels are along one dimension and channels along the other. Now <code>idx</code> indexes the first dimension, and <code>Img(idx,:)</code> are the pixels given by <code>idx</code>. The code above simplifies to:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>data = zeros(N,3);\nImg = reshape(Img,[],3); % note that this is essentially free, no data is copied.\nfor labelVal = 1:N\n data(labelVal,:) = mean(Img(idx{labelVal},:),1); % compute mean along 1st dimension\nend \n</code></pre>\n\n<p>(Don't overwrite <code>Img</code> if you need it later, you can use a temporary variable instead, in either case there won't be any data copied.)</p>\n\n<hr>\n\n<hr>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>W_den=zeros(N);\nfor i=1:N\n for j=1:N\n if(Euc(i,j)~=0)\n %...\n W_den(i,i)=W_num(i,j)+W_den(i,i);\n end\n end\nend\n</code></pre>\n\n<p>Here you only use the diagonal elements of <code>W_den</code>, the other <code>N*(N-1)</code> elements are never used. Instead, define <code>W_den</code> as a vector:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>W_den = zeros(N,1);\nfor i=1:N\n for j=1:N\n if(Euc(i,j)~=0)\n %...\n W_den(i) = W_num(i,j) + W_den(i);\n end\n end\nend\n</code></pre>\n\n<p>This saves a lot of memory, and also speeds up computation because of the reduced cache pressure.</p>\n\n<p>Written this way, it is trival to see that we can rewrite:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>W_den = zeros(N,1);\nfor i=1:N\n W_den(i) = sum(W_num(i,Euc(i,:)~=0));\nend\n</code></pre>\n\n<p>But David already showed how to simplify this bit of code even further by using the knowledge that <code>W_num</code> is zero where <code>Euc</code> is zero. In this case, <code>W_den = sum(W_num,2)</code>.</p>\n\n<hr>\n\n<hr>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>Euc=zeros(N);\n% Euclidean Distance\nfor i=1:N\n for j=1:N\n if glcms(i,j)~=0\n Euc(i,j)=sqrt(((data(i,1)-data(j,1))^2)+((data(i,2)-data(j,2))^2)+((data(i,3)-data(j,3))^2));\n end\n end\nend\n</code></pre>\n\n<p>David suggested using <code>pdist</code>, but we can also do this manually, which I show here to illustrate how to compute with matrices in MATLAB avoiding loops. I'll simplify the code step by step. First the expression within the inner loop can be simplified using vector operations:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>Euc=zeros(N);\n% Euclidean Distance\nfor i=1:N\n for j=1:N\n if glcms(i,j)~=0\n Euc(i,j)=sqrt(sum((data(i,:)-data(j,:)).^2));\n end\n end\nend\n</code></pre>\n\n<p>Next we remove the <code>if</code> statement:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>Euc=zeros(N);\n% Euclidean Distance\nfor i=1:N\n for j=1:N\n Euc(i,j) = (glcms(i,j)~=0) * sqrt(sum((data(i,:)-data(j,:)).^2));\n end\nend\n</code></pre>\n\n<p>Multiplying by the logical value <code>glcms(i,j)~=0</code> will set any elements where <code>glcms</code> is zero to 0. Next we remove the inner loop:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>Euc=zeros(N);\n% Euclidean Distance\nfor i=1:N\n Euc(i,:) = (glcms(i,:)~=0) .* sqrt(sum((data(i,:)-data).^2,2));\nend\n</code></pre>\n\n<p>Here we explicitly sum over the 2nd dimension, by default MATLAB sums over the first non-singleton dimension (dimension with more than one element). It is good practice to always explicitly state which dimension to sum over.</p>\n\n<p>Finally, removing the outer loop is more complicated because it requires reshaping arrays:</p>\n\n<pre class=\"lang-matlab prettyprint-override\"><code>% Euclidean Distance\nEuc = (glcms~=0) .* sqrt(sum((reshape(data,[],1,3)-reshape(data,1,[],3)).^2,3));\n</code></pre>\n\n<p>We've reshaped <code>data</code> in two different ways, to a <code>N</code>x1x3 array and to a 1x<code>N</code>x3 array. Subtracting these two arrays leads to a <code>N</code>x<code>N</code>x3 array. We take the square of the array, then sum along the new 3rd dimension (which corresponds to the original 2nd dimension).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T17:59:29.320", "Id": "237503", "ParentId": "237390", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T17:34:36.677", "Id": "237390", "Score": "4", "Tags": [ "performance", "graph", "matlab" ], "Title": "Optimizing nested loop for calculating geodesic distance" }
237390
<p>I am trying to create a list based on some data, but the code I am using is very slow when I run it on large data. So I suspect I am not using all of the Python power for this task. Is there a more efficient and faster way of doing this in Python?</p> <p>Here an explanantion of the code:</p> <blockquote> <p>You can think of this problem as a list of games (list_type) each with a list of participating teams and the scores for each team in the game (list_xx).For each of the pairs in the current game it first calculate the sum of the differences in score from the previous competitions (win_comp_past_difs); including only the pairs in the current game. Then it update each pair in the current game with the difference in scores. Using a defaultdict keeps track of the scores for each pair in each game and update this score as each game is played.</p> </blockquote> <p>In the example below, based on some data, there are for-loops used to create a new variable <code>list_zz</code>.</p> <p>The data and the for-loop code:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import numpy as np from collections import defaultdict from itertools import permutations list_type = [['A', 'B'], ['B'], ['A', 'B', 'C', 'D', 'E'], ['B'], ['A', 'B', 'C'], ['A'], ['B', 'C'], ['A', 'B'], ['C', 'A', 'B'], ['A'], ['B', 'C']] list_xx = [[1.0, 5.0], [3.0], [2.0, 7.0, 3.0, 1.0, 6.0], [3.0], [5.0, 2.0, 3.0], [1.0], [9.0, 3.0], [2.0, 7.0], [3.0, 6.0, 8.0], [2.0], [7.0, 9.0]] list_zz= [] #for-loop wd = defaultdict(float) for i, x in zip(list_type, list_xx): # staff 1 if len(i) == 1: #print('NaN') list_zz.append(np.nan) continue # Pairs and difference generator for current game (i) pairs = list(permutations(i, 2)) dgen = (value[0] - value[1] for value in permutations(x, 2)) # Sum of differences from previous games incluiding only pair of teams in the current game for team, result in zip(i, x): win_comp_past_difs = sum(wd[key] for key in pairs if key[0] == team) #print(win_comp_past_difs) list_zz.append(win_comp_past_difs) # Update pair differences for current game for pair, diff in zip(pairs, dgen): wd[pair] += diff print(list_zz) </code></pre> <p>Which looks like this:</p> <pre class="lang-py prettyprint-override"><code>[0.0, 0.0, nan, -4.0, 4.0, 0.0, 0.0, 0.0, nan, -10.0, 13.0, -3.0, nan, 3.0, -3.0, -6.0, 6.0, -10.0, -10.0, 20.0, nan, 14.0, -14.0] </code></pre> <p>If you could elaborate on the code to make it more efficient and execute faster, I would really appreciate it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T06:14:18.503", "Id": "465505", "Score": "0", "body": "Why `import pandas`? You don’t use it. Why `import numpy` just for `nan`, when you could simply use `math.nan`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T08:44:00.110", "Id": "465526", "Score": "0", "body": "I usually put it in my code in case I try Pandas or Numpy codes. This time I used numpy, but I also tried things using Pandas." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T09:30:37.173", "Id": "465532", "Score": "0", "body": "Welcome to Code Review! Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:23:07.587", "Id": "465750", "Score": "0", "body": "I don't really understand what your output is describing - can you elaborate a little bit more on what those values are representing, please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:27:24.823", "Id": "465752", "Score": "0", "body": "These are games, where each team has score in a competition. The competition can be with many different players or even only one. What my code does is to create an indicator of the difference of the score in the past with the players that are playing." } ]
[ { "body": "<p>The main way to do this faster is to use fewer loops and to do more in each loop. (AFAICT)</p>\n\n<p>loops in there...</p>\n\n<ul>\n<li>A (for event)</li>\n<li>A.1 (make team pairs)</li>\n<li>A.2 (make dgen)</li>\n<li>A.3 (for team, result in event)</li>\n<li>A.3.1.1 (for key in pairs)</li>\n<li>A.3.1.2 (sum)</li>\n<li>A.4 (for pair diff)</li>\n</ul>\n\n<p>You have a lot more flexibility if you use the <code>for</code> loop instead of mostly comprehensions and permutations. And, permutations is wasteful, here, (as discussed, below) because it prevents a few optimisations.</p>\n\n<p>A key change is we can do A vs B and B vs A in the same pass of the loop. So, we can change our loop from \"for each team go through all teams\" to \"for each team go through all following teams\". It's a big improvement.</p>\n\n<p>For the line-up A, B, C, D, our iterations look like:</p>\n\n<ul>\n<li>AB &amp; BA</li>\n<li>AC &amp; CA</li>\n<li>AD &amp; DA</li>\n</ul>\n\n<p>.</p>\n\n<ul>\n<li>BC &amp; CB</li>\n<li>BD &amp; DB</li>\n</ul>\n\n<p>.</p>\n\n<ul>\n<li>CD &amp; DC</li>\n<li>(done)</li>\n</ul>\n\n<p>So, the algorithm might end up something like (in pseudo code):</p>\n\n<pre><code>past_score_differences = defaultDict(float)\n\nfor each event:\n\n team_outcomes = defaultDict(float)\n\n teams_len = len(teams in event)\n for i in range(teams_len - 1):\n home_team = teams[i]\n home_score = scores[i]\n\n for j in range(i+1, teams_len):\n away_team = teams[j]\n away_score = scores[j]\n\n team_outcomes[home_team] += past_score_differences[(home_team, away_team)]\n team_outcomes[away_team] += past_score_differences[(away_team, home_team)]\n\n past_score_differences[(home_team, away_team)] += home_score - away_score\n past_score_differences[(away_team, home_team)] += away_score - home_score\n\n list_zz.append(team_outcomes[home_team])\n\n # the last team doesn't go through the outer loop\n list_zz.append(team_outcomes[teams[-1]])\n</code></pre>\n\n<p>Still a lot of loops, but far fewer and with fewer iterations for the innermost loop.</p>\n\n<p>If there is a lot of consistency in the team IDs, then you might consider not using a tuple as the key but instead using a dict within a dict, e.g.</p>\n\n<pre><code>example_past_differences = {\n 'A': {\n 'B': 10,\n 'C': 11,\n 'Etc...': 99\n }\n}\n\n# later, when accessing\n\nhome_team = ...\nhome_score = ...\nhome_past_differences = past_score_differences[home_team]\nfor ...\n away_past_differences = past_score_differences[away_team]\n ...\n team_outcomes[home_team] += home_past_differences[away_team]\n team_outcomes[away_team] += away_past_differences[home_team]\n</code></pre>\n\n<p>One last thing, your variable names are not easy to understand. I made mine way too long for accesibility to understand, but generally I think the guidance in these slides is very useful: <a href=\"https://talks.golang.org/2014/names.slide#1\" rel=\"nofollow noreferrer\">https://talks.golang.org/2014/names.slide#1</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T01:28:59.027", "Id": "466097", "Score": "0", "body": "Thank you for your answer tiffon. Is it possible that you edit your answer with the names i have in my question. I get a little confused. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T10:51:59.787", "Id": "237624", "ParentId": "237392", "Score": "2" } }, { "body": "<p>Took a guess at better variable names, but no idea what <code>list_zz</code> or <code>wd</code> should be.</p>\n\n<p>Switched to <code>combinations()</code> instead of <code>permutations()</code> and process each player pair both ways (e.g. ('A','B') and ('B','A')).</p>\n\n<p>Do combinations of player,score tuples, so there is only one call to <code>combinations()</code>.</p>\n\n<p>Use nested dicts instead of dicts keyed by a tuple of players.</p>\n\n<p><code>Counter()</code> is handy because <code>.update()</code> adds values rather than replacing them.</p>\n\n<p>The code should be a function (or method).</p>\n\n<pre><code>from collections import Counter, defaultdict\nfrom itertools import combinations\nimport math\n\n# test data\ngames = [['A', 'B'], ['B'], ['A', 'B', 'C', 'D', 'E'], ['B'], ['A', 'B', 'C'], ['A'], ['B', 'C'], ['A', 'B'], ['C', 'A', 'B'], ['A'], ['B', 'C']]\n\ngamescores = [[1.0, 5.0], [3.0], [2.0, 7.0, 3.0, 1.0, 6.0], [3.0], [5.0, 2.0, 3.0], [1.0], [9.0, 3.0], [2.0, 7.0], [3.0, 6.0, 8.0], [2.0], [7.0, 9.0]]\n\nlist_zz= []\n\nwd = defaultdict(Counter)\npast_diffs = defaultdict(float)\nthis_diff = defaultdict(Counter)\n\nfor players, scores in zip(games, gamescores):\n if len(players) == 1:\n list_zz.append(math.nan)\n continue\n\n past_diffs.clear()\n this_diff.clear()\n\n for (player1, score1), (player2, score2) in combinations(zip(players, scores), 2):\n past_diffs[player1] += wd[player1][player2]\n past_diffs[player2] += wd[player2][player1]\n\n this_diff[player1][player2] = score1 - score2\n this_diff[player2][player1] = score2 - score1\n\n list_zz.extend(past_diffs[p] for p in players)\n\n for player in players:\n wd[player].update(this_diff[player])\n\nprint(list_zz)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T16:11:16.207", "Id": "237644", "ParentId": "237392", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T18:07:26.623", "Id": "237392", "Score": "5", "Tags": [ "python", "performance", "programming-challenge" ], "Title": "Creating a list from combinations of the original data" }
237392
<p>What is the best way to move <code>_add</code> and <code>_preorder</code> methods in class <code>Node</code> to <code>add_node</code> and <code>preorder</code> methods in class <code>BinaryTree</code> such that they have the below class structure:</p> <pre><code>class Node: __init__ __repr__ </code></pre> <pre><code>class BinaryTree: __init__ add_node preorder </code></pre> <p>Complete Code::</p> <pre><code>class Node(object): def __init__(self, item, left=None, right=None): self.item = item self.left = None self.right = None def __repr__(self): return '{}'.format(self.item) def _add(self, value): new_node = Node(value) if not self.item: self.item = new_node elif not self.left: self.left = new_node elif not self.right: self.right = new_node else: self.left = self.left._add(value) return self def _preorder(self): print(self.item) if self.left: self.left._preorder() if self.right: self.right._preorder() class BinaryTree(object): def __init__(self): self.root = None def add_node(self, value): if not self.root: self.root = Node(value) else: self.root._add(value) def preorder(self): if self.root: return self.root._preorder() if __name__ == '__main__': binary_tree = BinaryTree() print( "Adding nodes 1 to 10 in the tree...") for i in range(1, 11): binary_tree.add_node(i) print() print( "Printing preorder...") binary_tree.preorder() </code></pre>
[]
[ { "body": "<p>First, some general notes:</p>\n\n<ol>\n<li><p>Eliminate unused complexity. A couple of examples of this are your node constructor, which takes two optional arguments that you never use, and your <code>__repr__</code>, which specifies a format string but doesn't add any extra formatting -- if code is \"dead\" (i.e. no part of your program uses it), get rid of it so that human readers don't need to read it.</p></li>\n<li><p>You don't strictly need typing in Python code, but it's a good habit to build early since it makes your code easier to check for correctness and it makes it easier for a reader to understand quickly what it does -- for example, in your <code>__main__</code> function I see that you build a tree with integers in it, but could we pass other types of things as <code>item</code>s? Using a <code>TypeVar</code> lets you define what sorts of types it's okay to put in your container (or, if it's only supposed to hold one type, you could just annotate <code>item</code> with that type in order to make that explicit).</p></li>\n<li><p><code>preorder</code> doesn't seem like a good name for this function, since I don't see that it's \"ordering\" anything (usually a method name is a verb that says what you're doing, not how you're doing it); the actual effect is to print out the tree. I'd call it something more obvious like <code>print</code>.</p></li>\n</ol>\n\n<p>Now, as to your question of whether it makes sense to move logic from the <code>Node</code> to the <code>BinaryTree</code> -- IMO when you're working with trees it feels a lot more natural to have the nodes be \"smart\" so your top level methods can just figure out which subtree should handle a particular task and then delegate it. Here's what your tree might look like with more of the logic moved toward the top; you can judge for yourself whether having the logic in <code>BinaryTree</code> is any better than having it in <code>Node</code>:</p>\n\n<pre><code>from typing import Generic, Optional, TypeVar\n\n# These are the kinds of values that can go in our tree.\nV = TypeVar('V', int, float, str) \n\nclass Node(Generic[V]):\n \"\"\"A node in a binary tree.\"\"\"\n def __init__(self, item: V):\n self.item: V = item\n self.left: Optional['Node'] = None\n self.right: Optional['Node'] = None\n\n def __repr__(self) -&gt; str:\n return repr(self.item)\n\n\nclass BinaryTree(Generic[V]):\n \"\"\"A binary tree.\"\"\"\n def __init__(self):\n self.root: Optional[Node[V]] = None\n\n def add_node(self, value: V) -&gt; None:\n \"\"\"Add the given value to the tree.\"\"\"\n if not self.root:\n # This is the first node; make it the root.\n self.root = Node(value)\n return\n\n child = Node(value)\n # Find a spot under the root to add the new child node.\n node = self.root\n while node:\n if value &lt; node.item:\n if node.left:\n node = node.left\n else:\n node.left = child\n return\n elif value &gt; node.item:\n if node.right:\n node = node.right\n else:\n node.right = child\n return\n else:\n return\n\n def print(self):\n \"\"\"Print out the tree.\"\"\"\n def print_node(node: Optional[Node[V]]) -&gt; None:\n if not node:\n return\n print_node(node.left)\n print(node)\n print_node(node.right)\n print_node(self.root)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T02:08:52.197", "Id": "465493", "Score": "2", "body": "Preorder traversal of a tree is a well-known and well-defined term. I don't see anything wrong with it, although I do agree that the printing functionality is unnecessarily hard-coded. Your reimplementation prints the tree in-order, which is not what OP wanted. No offense intended, but I suggest you do some studying on basic algorithms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T02:33:58.057", "Id": "465495", "Score": "0", "body": "Made that comment a little clearer. Generally you want to name a function by what it does rather than how, why, or where it does it -- function names like `recursive` and `helper` and `iterate` show up a lot in sample code (and code written by new grads) but they're bad habits to get into. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T06:58:07.300", "Id": "465513", "Score": "2", "body": "You have completely changed the behaviour of `add_node()`. The OP’s code did not enforce a less-than/greater-than ordering to the left/right children. Probably a bug in the OP’s implementation, but you’ve altered the behaviour without even mentioning it. Additionally, your implementation does not allow the tree to contain duplicate values. Finally, the `__repr__` function is not “dead” code; it changes the representation of a node into the string of the value contained that node." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T23:08:00.247", "Id": "465638", "Score": "0", "body": "I agree with all your points, but the `add_node` method in your answer is for a binary search tree and NOT a binary tree. Also, the `print` method is inorder and NOT preorder." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T01:57:50.980", "Id": "237408", "ParentId": "237393", "Score": "2" } }, { "body": "<pre><code>class Node(object):\n\n def __init__(self, item, left=None, right=None):\n self.item = item\n self.left = None\n self.right = None\n</code></pre>\n\n<p>The parameters <code>left</code> and <code>right</code> are not used in the constructor! Remove them, or actually use them.</p>\n\n<hr>\n\n<pre><code> def _add(self, value):\n new_node = Node(value)\n\n if not self.item:\n self.item = new_node\n ...\n</code></pre>\n\n<p>Given <code>self.item</code> is unconditional set in the constructor, this first test seems unnecessary.</p>\n\n<pre><code> elif not self.left:\n self.left = new_node\n elif not self.right:\n self.right = new_node\n</code></pre>\n\n<p>Your binary tree does not seem to have any ordering imposed on the left/right nodes. If there is no left node, you create one even if the new value is larger than the current node. Similarly, if there is a left node, but no right node, you create a right node even if the value is smaller than the current node. </p>\n\n<pre><code> else:\n self.left = self.left._add(value)\n return self\n</code></pre>\n\n<p>Finally, if both left and right exist, you unconditionally add the new node to the left sub tree, which will create a very unbalanced tree. Moreover, the newly created <code>new_node</code> is discarded, to be recreated by the <code>_add()</code> method one level down, so is wasteful. And the sole purpose of <code>return self</code> seems to be so that there is a return value to assign to <code>self.left</code>, which results in the the original value <code>self.left</code> being assigned to itself, so again useless busy work.</p>\n\n<blockquote>\n <p>A binary tree does not have any ordering imposed - nodes are added in the following preference: <code>root</code> -> <code>left</code> -> <code>right</code>. Ordering is imposed i[sic] a binary search tree. – <a href=\"https://codereview.stackexchange.com/users/169130/saurabh\">Saurabh</a></p>\n</blockquote>\n\n<p>With your sample code, adding the values 1 to 10 to your <code>BinaryTree</code>, you get the following \"tree\":</p>\n\n<pre><code> 1\n / \\\n 2 3\n / \\\n 4 5\n / \\\n 6 7\n / \\\n 8 9\n /\n 10 \n</code></pre>\n\n<p>This is not really a binary tree; it is a stick with leaves. It could be represented as a list of tuples: <code>[(1,3), (2,5), (4,7), (6,9), (8,), (10,)]</code>.</p>\n\n<p>If you wish to create a general binary tree, which does not impose an ordering, you need to include methods for building the desired tree, such as finding the \"5\" node, and explicitly adding to the right branch. A generic <code>add_node()</code> doesn't have enough detail to control how the tree is built.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T23:43:18.713", "Id": "465642", "Score": "0", "body": "A binary tree does not have any ordering imposed - nodes are added in the following preference: `root` -> `left` -> `right`. Ordering is imposed i a binary search tree." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T06:52:37.093", "Id": "237419", "ParentId": "237393", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T18:18:47.307", "Id": "237393", "Score": "5", "Tags": [ "python", "algorithm", "tree" ], "Title": "Binary Tree Preorder Traversal" }
237393
<p>I have been teaching myself python in my spare time and so far I think I have figured out the basics. However, I am fairly certain that my code is extremely unprofessional and the way I write it is incorrect. So far, I have been going on a "If it works don't screw with it" philosophy but I would like to learn how to actually write Python correctly. If anyone could just take a look at what I have written that would be great.</p> <p>Here is my code that implements a voting machine, called "VoteBot":</p> <pre><code>import time import os #colors os.system('color') black = lambda text: '\033[0;30m' + text + '\033[0m' red = lambda text: '\033[0;31m' + text + '\033[0m' green = lambda text: '\033[0;32m' + text + '\033[0m' yellow = lambda text: '\033[0;33m' + text + '\033[0m' blue = lambda text: '\033[0;34m' + text + '\033[0m' magenta = lambda text: '\033[0;35m' + text + '\033[0m' cyan = lambda text: '\033[0;36m' + text + '\033[0m' white = lambda text: '\033[0;37m' + text + '\033[0m' #Start Menu print(' --------------------------------------------------------------------------------') print(' VoteBot v1.5.0') print(' Copyright 2020.') print(' Author:') print(' ') print(' Hit any key and press enter to begin.') print(' --------------------------------------------------------------------------------') vote = input(' ') #start of main code while vote == 'start' or '1' or '2' or '3' or '4': print("\n" * 5000) print(blue(' --------------------------------------------------------------------------------------------------------')) print(blue(' @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')) print(blue(' --------------------------------------------------------------------------------------------------------')) print(blue(' @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')) print(blue(' --------------------------------------------------------------------------------------------------------')) print(blue(' @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')) print(blue(' @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')) print(blue(' @@@@@@@ @@@@@ @@@@ #@@@ @@ /@@@@@@ %@@@@, @@@@@ #@@@ @@@@ @@@@ @@@@@@@')) print(blue(' @@@@@@@@ @@@&amp; @@&amp; @@@@ @@@@ @@@@@ @@@@@@@@@@@ @@@, @@% @@@@ @@ @@&amp; @@@ @@@@@@@@')) print(blue(' @@@@@@@@@ @@ %@@ @@@@@@ (@@@ @@@@@ @@@@@@@ @ @, @@ @@@@@@ (@@ @@ @ .@ /@@@@@@@@')) print(blue(' @@@@@@@@@@ @ *@@@ @@@@@ @@@@ @@@@@ @@@@@@@@@@@ @@@ * @@ @@@@@ @@@ #@@ @ @@@@@@@@@')) print(blue(' @@@@@@@@@@@ @@@@@% @@@@@ @@@@@ @@@@@@ @@@@. @@@% @@@@@ @@@/ @@@@@@@@@@')) print(blue(' @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')) print(blue(' @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')) print(blue(' --------------------------------------------------------------------------------------------------------')) print(blue(' @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')) print(blue(' --------------------------------------------------------------------------------------------------------')) print(blue(' @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')) print(blue(' --------------------------------------------------------------------------------------------------------')) print(' ') print(' --------------------------------------------------------------------------------------------------------') print(' Vote here to choose the winning team. Please choose by entering the number corresponding to your choice.') print(' --------------------------------------------------------------------------------------------------------') print(red(' 1. Team 1 (Cantidate 1, Cantidate 2)')) print(yellow(' 2. Team 2 (Cantidate 1, Cantidate 2)')) print(green(' 3. Team 3 (Cantidate 1, Cantidate 2)')) print(blue(' 4. Team 4 (Cantidate 1, Cantidate 2)')) print(' --------------------------------------------------------------------------------------------------------') print(' Please make your selection now. Remember, if you do not input a NUMBER your vote will not be counted.') vote = input(' Enter your vote: ') file = open('votedata.txt', 'a') file.write(vote + '\n') print(' The system is adding your vote. The next person can vote in 3 seconds.') time.sleep(3) if vote == 'tally': break #start of tally with open("votedata.txt") as fp: results = {} for row in fp: try: v = int(float(row)) if v not in results: results[v] = 0 results[v] += 1 except: print(red("Invalid Numeric entry")) print(results) print('The program will automatically shut down in 5 minutes.') time.sleep(300) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T21:29:13.397", "Id": "465471", "Score": "0", "body": "Can you please give a high level description of what votebot does?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T01:11:59.077", "Id": "465492", "Score": "0", "body": "Have you taken a look at streamlit library? I find it pretty nice." } ]
[ { "body": "<p>Some high level coding style notes:</p>\n\n<ol>\n<li><p>Try to eliminate code that looks like it's copied and pasted (DRY - Don't Repeat Yourself), and define it in functions. Your various color functions are mostly identical with the exception of one digit (the color code) -- you can avoid repeating yourself by defining a function that implements the shared part and defining the colors in terms of that.</p></li>\n<li><p>Professional coders (especially those working on large shared codebases) rely heavily on static typing to improve correctness and readability; modern Python has built in support for static typing, and while it's optional it goes a long way toward making code look professional IMO. If you get in the habit of using typing and a static type checker (<code>mypy</code>) you'll find that you spend a lot less time debugging silly typos too!</p></li>\n<li><p>It's generally considered good style to not have lines of code be super long -- opinion varies on this, but modern style guides usually suggest a maximum width of 120 characters, and I personally try to keep it under 80. The fact that your output contains lots of blank space that might make it annoying to view in a normal terminal is more of a UX issue than a code review one, but assuming it's actually a requirement to left-pad everything with 53 spaces, I think that should be implemented in code (again, in a reusable function because DRY) rather than copy+pasted into all your strings.</p></li>\n<li><p>Again this is more UX than actual coding, but: proofread! It's \"candidate\", not \"cantidate\". :)</p></li>\n</ol>\n\n<p>Here's how I'd apply those notes to the print statements in your code:</p>\n\n<pre><code>from enum import IntEnum\nfrom typing import Optional\n\n# Command prompt colors.\nclass Color(IntEnum):\n \"\"\"MS-DOS command prompt color codes.\"\"\"\n BLACK = 0\n RED = 1\n GREEN = 2\n YELLOW = 3\n BLUE = 4\n MAGENTA = 5\n CYAN = 6\n WHITE = 7\n GRAY = 8\n\ndef color_text(text: str, color: Optional[Color]) -&gt; str:\n \"\"\"Wraps text in the specified color.\"\"\"\n if color is None:\n return text\n return '\\033[0;3' + hex(color.value)[-1] + 'm' + text + '\\033[0m'\n\ndef pp(text: str, color: Optional[Color] = None, left_padding: int = 53) -&gt; None:\n \"\"\"Pretty-print text with optional coloring and default left-padding of 53 spaces.\"\"\"\n print(' ' * left_padding + color_text(text, color))\n\n#Start Menu\npp('-' * 80)\npp('VoteBot v1.5.0')\npp('Copyright 2020.')\npp('Author:')\npp('')\npp('Hit any key and press enter to begin.')\npp('-' * 80)\nvote = input(' ' * 53)\n\n#start of main code\nwhile vote == 'start' or '1' or '2' or '3' or '4':\n pp(\"\\n\" * 5000) # this is gross -- maybe use a system(\"cls\") instead?\n # ... etc\n pp('-' * 80)\n pp('Vote here to choose the winning team. '\n 'Please choose by entering the number corresponding to your choice.')\n pp('-' * 80)\n pp('1. Team 1 (Candidate 1, Candidate 2)', Color.RED)\n pp('2. Team 2 (Candidate 1, Candidate 2)', Color.YELLOW)\n pp('3. Team 3 (Candidate 1, Candidate 2)', Color.GREEN)\n pp('4. Team 4 (Candidate 1, Candidate 2)', Color.BLUE)\n # ... etc\n</code></pre>\n\n<p>The signature of <code>pp</code> is designed to narrow your output statements and keep the text aligned for readability; the function name itself is abbreviated, the padding is built into the function so the actual arguments don't need to include it, and the color argument goes at the end so that it doesn't cause the width of the line before the text to vary.</p>\n\n<p>Colors have been defined in an <code>IntEnum</code> because that makes it impossible (with static typechecking) to pass anything that's not a valid color into the <code>color_text</code> function; the alternative would be to use a regular <code>int</code> (or worse yet, the <code>str</code> representation) and then validate at runtime that it falls within the expected range.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T21:03:06.430", "Id": "237398", "ParentId": "237394", "Score": "6" } } ]
{ "AcceptedAnswerId": "237398", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T14:09:10.560", "Id": "237394", "Score": "3", "Tags": [ "python" ], "Title": "How can I make this Python code that implements a voting machine look more professional?" }
237394
<p>Here's an example how to construct an external sorting algorithm from the Quicksort. The method may be applicable to other known internal comparison sort algorithms. I have checked that it shows N*logN time complexity when fed with random file, and almost exactly 0.5 N square when input is already sorted. But I am not sure how to apply external sorts in real life. Maybe someone has a real life problem or test bench for external sort. Is this idea novel at all? So simple. May be parallelizable with some rework.</p> <pre><code>import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; /** * -- Big Q Sort -- * * A variation of Quicksort algorithm for in-place sorting of data that does not completely fit into RAM. * * The basic idea of this generalization is that pointers used for the partitioning are file block indexes. * A step of the original Quicksort algorithm takes two records to compare and conditionally swaps them. * This algorithm on the other hand, will take two blocks of records to fill a buffer in memory. * Instead of swapping, it runs a sorting algorithm on the buffer and then blocks are written back to the file * before the corresponding pointer is moved. * * Pointers used for the partitioning are file block indexes but pivot is still a single record like in Quicksort. * * Otherwise the program flow is similar to that of Quicksort. * * -- This Implementation -- * * Pivot selection saves block reads by selecting a record from the memory, which may not be an optimal pivot. * If there are repeated keys, the actual record that plays the pivot role may change while partitioning in this * implementation, it is only its key that needs to stay constant. * * In the demonstration, records are bytes of the file "sort_me.txt", key is the signed value, comparator is &lt; * * The buffer is assumed to be smaller than the file. * * The output file will be a multiple of the block size, therefore program adds some null bytes and orders them. In a * production implementation this would be bad; but there is no need to complicate this POC to prevent the issue. */ public class BigQ { private static final int BLOCK_SIZE = 11; private static byte[] buffer = new byte[2*BLOCK_SIZE]; private static final File SORT_ME = new File("sort_me.txt"); static class BlockInterval { long low; long high; public BlockInterval(long low, long high) { assert low &lt; high; this.low = low; this.high = high; } } public static void main(String[] args) throws IOException { BlockFile blockFile = new BlockFile(SORT_ME, "rws", BLOCK_SIZE, buffer); // divide et impera starts with the whole file as interval to sort Deque&lt;BlockInterval&gt; openList = new ArrayDeque&lt;&gt;(); openList.push(new BlockInterval(0L, blockFile.nBlocks - 1)); do { BlockInterval outerBounds = openList.poll(); // initial fill of buffer (both halves) assert outerBounds.low &lt; outerBounds.high; // assuming at least 2 blocks span blockFile.readBlock(outerBounds.low, BufferHalf.LEFT); blockFile.readBlock(outerBounds.high, BufferHalf.RIGHT); Arrays.sort(buffer); if (outerBounds.low + 1 &lt; outerBounds.high) { // interval that does not completely fit into one buffer - partitioning needed long doneBelow = outerBounds.low; long doneAbove = outerBounds.high; // select pivot (does not affect correctness but efficiency) int pivotIndex = BLOCK_SIZE - (int)System.currentTimeMillis()%2; byte pivotKey = buffer[pivotIndex]; partitioning: while (true) { // buffer is sorted at this point if (pivotIndex &gt;= BLOCK_SIZE) { // left half of buffer contains sub-pivot keys only, pivot is in the right half blockFile.writeBlock(doneBelow, BufferHalf.LEFT); doneBelow++; if (doneBelow &gt;= doneAbove) { // done pointers collide, conclude partitioning by writing out the rest of records blockFile.writeBlock(doneAbove, BufferHalf.RIGHT); break partitioning; } blockFile.readBlock(doneBelow, BufferHalf.LEFT); Arrays.sort(buffer); // by restoring sortedness of the buffer, pivot may have moved some positions left while (buffer[pivotIndex] &gt; pivotKey) { pivotIndex--; } } else { // right half of buffer contains super-pivot keys only, pivot is in the left half blockFile.writeBlock(doneAbove, BufferHalf.RIGHT); doneAbove--; if (doneAbove &lt;= doneBelow) { // done pointers collide, conclude partitioning by writing out the rest of records blockFile.writeBlock(doneBelow, BufferHalf.LEFT); break partitioning; } blockFile.readBlock(doneAbove, BufferHalf.RIGHT); Arrays.sort(buffer); // by restoring sortedness of the buffer, pivot may have moved some positions right while (buffer[pivotIndex] &lt; pivotKey) { pivotIndex++; } } } // found the final block for the pivot (may still move in the block since the block contains 0 or more // lower keys than the pivot, 1 or more pivot keys, and 0 or more higher keys) assert doneBelow == doneAbove; // when all records of a block are settled, exclude that block from further processing if (doneBelow == outerBounds.high &amp;&amp; buffer[BLOCK_SIZE] == pivotKey) { doneBelow--; } if (doneAbove == outerBounds.low &amp;&amp; buffer[BLOCK_SIZE - 1] == pivotKey) { doneAbove++; } // keep partly processed and undone blocks in circulation if (doneBelow &gt; outerBounds.low) { openList.push(new BlockInterval(outerBounds.low, doneBelow)); } if (doneAbove &lt; outerBounds.high) { openList.push(new BlockInterval(doneAbove, outerBounds.high)); } } else { // degenerate interval of 2 blocks - sort already done in memory, just persist the result blockFile.writeBlock(outerBounds.low, BufferHalf.LEFT); blockFile.writeBlock(outerBounds.high, BufferHalf.RIGHT); } } while (!openList.isEmpty()); blockFile.close(); } } enum BufferHalf { LEFT(0), RIGHT(1); int i; BufferHalf(int i) { this.i = i; } } class BlockFile extends RandomAccessFile { long nBlocks; private final int blockSize; private final byte[] buffer; // analysis stuff static int readCount = 0, writeCount = 0; public BlockFile(File file, String mode, int blockSize, byte[] buffer) throws FileNotFoundException { super(file, mode); this.blockSize = blockSize; this.buffer = buffer; nBlocks = (file.length() + blockSize - 1)/blockSize; } public void readBlock(long blockIndex, BufferHalf bufferHalf) throws IOException { seek(blockSize*blockIndex); read(buffer, blockSize*bufferHalf.i, blockSize); readCount++; } public void writeBlock(long blockIndex, BufferHalf bufferHalf) throws IOException { seek(blockSize*blockIndex); write(buffer, blockSize*bufferHalf.i, blockSize); writeCount++; } @Override public void close() throws IOException { super.close(); System.out.println("N = " + nBlocks); System.out.println("N*log(N) = " + nBlocks*Math.log(nBlocks)/0.2); System.out.println("N*N/2 = " + nBlocks*nBlocks/2); System.out.println(readCount + " reads"); System.out.println(writeCount + " writes"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T02:18:20.380", "Id": "465494", "Score": "3", "body": "I'm not sure if I'm reading this correctly but you seem to be sorting very small files, and sorting directly on disk. I don't think that's right. I'd like to see a test driver that reproduces some of the measurements you took." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T23:23:43.700", "Id": "465639", "Score": "0", "body": "Get a 100 gig file and set a 100 mega buffer size. Then it starts to make sense to sort externally. If I add a bigger structure and a comparator instead of byte comparison, the externalness is more justified but the number of IO won't change. So this is enough \n for counting block writes. Test was manual. I copied the source code to sort_me.txt and modified the buffer size several times. I got in the output datapoints for a scatter plot and saw the expected trend." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T18:57:54.633", "Id": "237395", "Score": "2", "Tags": [ "java", "performance", "sorting" ], "Title": "Construction of external sorts from comparison ones" }
237395
<p>How may this code be improved upon, the user inputs array of specified length and replaces each element that is smaller than the mean of the first and last element with the mean.</p> <p>Is there a better way to pass the array to the function (ref/ptr, etc.), or more efficient way to manage memory (when handling array)?</p> <p>I know the vector container from STL is ideal but just wanted to gain some insight on fundamentals.</p> <pre><code>#include &lt;iostream&gt; using namespace std; void replaverage(int arr[], size_t n){ cout&lt;&lt;"Enter array length"&lt;&lt;endl; cin&gt;&gt; n; for(int i=0; i&lt;n; i++){ cout&lt;&lt;"Enter the numbers"&lt;&lt;endl; cin&gt;&gt;arr[i]; cout&lt;&lt;endl; } int f=arr[0]; int l=arr[n-1]; double av=(f+l)/2; for(int j=0; j&lt;n; j++){ if(arr[j]&lt;av){ arr[j]=av; } } for (int i=0; i&lt;n; i++){ cout&lt;&lt;arr[i]&lt;&lt; " ";} } int main(int argc, char* argv[]){ size_t x=10; int arr[x]; replaverage(arr,x); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T00:11:28.217", "Id": "465489", "Score": "0", "body": "In c++ you should use a `vector<int>` instead of a raw c-style array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T05:06:04.677", "Id": "465501", "Score": "0", "body": "Welcome to Code Review! I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. 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)*." } ]
[ { "body": "<p>Something to keep in mind is that this statement is truncating data:</p>\n<pre><code> arr[j]=av;\n</code></pre>\n<p>because it is assigning a double to an int.</p>\n<p>As was mentioned in a comment there are c++ container types that would be better than a old C style array, two of these are <code>std::array&lt;type, arraySize&gt;</code> and <code>std::vector&lt;type&gt;</code>. <code>std::array</code> is a fixed size and <code>std::vector</code> is a variable size. Both would allow the use of iterators that might simplify the code.</p>\n<h2>Avoid <code>using namespace std;</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code>&lt;&lt;</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<h2>std::endl</h2>\n<p>It is better for performance if <code>&quot;\\n&quot;</code> is used rather than <code>std::endl</code> in output, <code>std::endl</code> flushes the output buffer as well as putting out a new line, and this can slow down loops.</p>\n<h2>Complexity</h2>\n<p>The function <code>replaverage</code> should really be 2 functions, one to input the data and a second to process the data. Perhaps a third to print the data.</p>\n<h2>Horizontal Spacing</h2>\n<p>It would be better if there were spaces around operators that separate operands.</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nstd::vector&lt;int&gt; getData()\n{\n int n;\n std::vector&lt;int&gt; intputData;\n std::cout &lt;&lt; &quot;Enter array length\\n&quot;;\n std::cin &gt;&gt; n;\n std::cout &lt;&lt; &quot;Enter the numbers\\n&quot;;\n for(int i = 0; i &lt; n; i++){\n int tmpIn;\n std::cin &gt;&gt; tmpIn;\n intputData.push_back(tmpIn);\n }\n\n return intputData;\n}\n\nvoid modifyData(std::vector&lt;int&gt; &amp;data)\n{\n int f=data[0];\n int l=data[data.size() - 1];\n double av = (f + l)/2;\n for (auto j: data)\n {\n if(j &lt; av){\n j = av;\n }\n }\n}\n\nvoid printData(std::vector&lt;int&gt; &amp;data)\n{\n for (auto i: data)\n {\n std::cout &lt;&lt; i &lt;&lt; &quot; &quot;;\n }\n}\n\nint main(int argc, char* argv[]){\n\n std::vector&lt;int&gt; data = getData();\n modifyData(data);\n printData(data);\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T11:03:59.120", "Id": "465541", "Score": "0", "body": "The two places where `std::endl` are used both immediately precede reading from `std::cin`, where a flush is clearly desirable. That said, I would prefer to see it written explicitly (`...\\n\" << std::flush`) to ensure readers know it's intended and not just a newline." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T01:37:31.657", "Id": "237406", "ParentId": "237403", "Score": "2" } }, { "body": "<p>Always check input succeeded. </p>\n\n<blockquote>\n<pre><code>std::cin &gt;&gt; n;\n</code></pre>\n</blockquote>\n\n\n\n<blockquote>\n<pre><code> std::cin &gt;&gt; arr[i];\n</code></pre>\n</blockquote>\n\n<p>In both these lines, we ignore all errors, and will produce the wrong output without any warnings, and happily return 0 from <code>main()</code>. This is bad for any program used as a processing step (e.g. driven by Make).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T09:14:00.607", "Id": "465846", "Score": "0", "body": "Check success of input via try-catch or throws?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T09:19:08.390", "Id": "465847", "Score": "0", "body": "Yes, you can check using exceptions, if you set the stream to throw on error (using `std::cin::exceptions(std::ifstream::eofbit | std::ifstream::badbit)`, for example). Or check explicitly with `if (!std::cin) { handle errors; }`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T09:39:21.703", "Id": "465853", "Score": "0", "body": "cin.fail() seems to be a good solution." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T11:00:46.543", "Id": "237430", "ParentId": "237403", "Score": "1" } }, { "body": "<p>I restructured the code into object oriented format.\nIncorporated changes suggested by pacmaninbw.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\nclass replace_avg{\n\n private:\n int n;\n int tmpIn;\n double f;\n double l;\n double av;\n std::vector&lt;double&gt; intputData;\n\n public:\n std::vector&lt;double&gt; getData()\n {\n std::cout &lt;&lt; \"Enter array length\\n\";\n std::cin &gt;&gt; n;\n std::cout &lt;&lt; \"Enter the numbers\\n\";\n for(int i = 0; i &lt; n; i++){\n std::cin &gt;&gt; tmpIn;\n intputData.push_back(tmpIn);\n }\n return intputData;\n }\n\n\n void modifyData(std::vector&lt;double&gt; &amp;inputData)\n {\n f = inputData[0];\n l = inputData[inputData.size() - 1];\n av = (f + l)/2;\n for (auto &amp;j: inputData)\n {\n if(j &lt; av){\n j = av;\n }\n }\n }\n\n void printData(const std::vector&lt;double&gt; &amp;inputData)\n {\n for (auto &amp;i: inputData)\n {\n std::cout &lt;&lt; i &lt;&lt; \" \";\n }\n std::cout &lt;&lt; '\\n';\n }\n};\n\nint main(){\n\n replace_avg vect;\n std::vector&lt;double&gt; v1 = vect.getData();\n vect.modifyData(v1);\n vect.printData(v1);\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T16:29:40.550", "Id": "237443", "ParentId": "237403", "Score": "1" } }, { "body": "<p>Consider <a href=\"https://github.com/abseil/abseil-cpp/blob/master/absl/types/span.h\" rel=\"nofollow noreferrer\"><code>absl::Span&lt;T&gt;</code></a>. (or boost's)\nIt may one day be replaced with <a href=\"https://en.cppreference.com/w/cpp/container/span\" rel=\"nofollow noreferrer\"><code>std::span</code></a></p>\n\n<p>It's actually quite hard to make what you're asking for, despite this being extremely useful and desired for a very long time.</p>\n\n<p>However, with it, you can write:</p>\n\n<pre><code>void ReadFromIntArray(absl::Span&lt;int const&gt; int_array);\nReadFromIntArray({1,2,3});\nReadFromIntArray(std::vector&lt;int&gt;{1,2,3});\nReadFromIntArray(std::array&lt;int, 3&gt;{1,2,3});\nReadFromIntArray(absl::MakeSpan(pointer_to_int_array, count_of_int_array));\n</code></pre>\n\n<hr>\n\n<p>There's tremendous downsides to using iterators or pointer+count. Pointer+count is wildly dangerous and severely impairs readability. Iterators impair readability further and may also obliterate an architecture; either the interface becomes tightly coupled with <code>std::vector</code>, or the interface requires a template parameter adding a huge unnecessary compilation cost to every client.</p>\n\n<hr>\n\n<p>In the <strong>very</strong> distant future, ranges will make things much more readable without a performance cost, and algorithms will be thought of as performing transformations on logical sets of data rather than doing logic within a loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T16:52:08.137", "Id": "465902", "Score": "0", "body": "How does passing a container by const ref differ from passing a span of said container apart from elements being modifiable in the latter case? What’s difference between non-const ref to the container and a span?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T18:42:32.523", "Id": "465920", "Score": "0", "body": "A mutable ref to a container means the implementation can resize the container, unlike a span. However a span of mutable items can modify the contents, unlike a const ref to a container. A span of const items is comparable to a const ref container, but works with any contiguous set of items in memory, not just one particular container type." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T00:51:51.217", "Id": "237526", "ParentId": "237403", "Score": "1" } } ]
{ "AcceptedAnswerId": "237406", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-16T23:41:16.390", "Id": "237403", "Score": "2", "Tags": [ "c++", "array", "stream" ], "Title": "User Specified Array Read and Modify" }
237403
<p>Is there a more idiomatic way to handle the following scenario? I'm open to <a href="https://lodash.com/" rel="nofollow noreferrer"><code>lodash</code></a>, etc. if needed. This does what I want, but I feel that there is probably a shortcut I'm missing:</p> <pre><code>const migrateValues = (obj, srcKey, destKey, value) =&gt; { updatedSrc = []; obj[srcKey].forEach(x =&gt; { if (x !== value) { updatedSrc.push(x); } }); obj[destKey].push(value); obj[srcKey] = updatedSrc; return obj; } obj = { "key1": [1, 2, 3], "key2": [4, 5, 6], "key3": [7, 8, 9], "key4": [10, 11, 12] }; valueToMove = 11; srcKey = "key4"; destKey = "key2"; console.log(obj); console.log(migrateValues(obj, srcKey, destKey, valueToMove)); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T01:10:46.333", "Id": "465491", "Score": "0", "body": "This assumes no empty lists, no dupes, etc." } ]
[ { "body": "<p>I would propose something like so (given that you have assumed no dupes, etc)</p>\n\n<pre><code>function migrateValues(obj, srcKey, destKey, value) {\n return {\n ...obj,\n [srcKey]: obj[srcKey].filter(w =&gt; w !== value),\n [destKey]: obj[destKey].concat(value)\n };\n}\n</code></pre>\n\n<p>We spread obj, and then overwrite the srcKey and destKey properties.</p>\n\n<p>There are several reasonable ways to make obj[srcKey].filter and obj[destKey].concat avoid TypeErrors, which is best is dependent on what you have planned for the function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:00:43.447", "Id": "465742", "Score": "0", "body": "Thanks, I like the key override pattern you've used" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T21:56:36.737", "Id": "237458", "ParentId": "237405", "Score": "3" } } ]
{ "AcceptedAnswerId": "237458", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T00:09:11.033", "Id": "237405", "Score": "1", "Tags": [ "javascript" ], "Title": "More idiomatic way to move item from one dict value(list) to another?" }
237405
<p>Often when I find myself working with magic number enum values and I want to know what they represent, so I create an array of strings in order to print out their label.</p> <p>This macro automates that process.</p> <pre><code>//#define DEBUG #define GENERATE_ENUM(ENUM) ENUM, #define GENERATE_STRING(STRING) #STRING, #define GENERATE_ENUM_LIST(MACRO, NAME) \ enum NAME \ { \ MACRO(GENERATE_ENUM) \ }; //#ifdef DEBUG #define GENERATE_ENUM_STRING_NAMES(MACRO, NAME) \ const char *NAME##_Strings[] = { \ MACRO(GENERATE_STRING) \ }; //#else //#define GENERATE_ENUM_STRING_NAMES(MACRO, NAME) //#endif </code></pre> <p>To use do:</p> <pre><code>#include &lt;stdio.h&gt; /* ~ The macro ~ */ #define nuclearLaunchCodes(T) \ T(ONE) \ T(TWO) \ T(THREE) GENERATE_ENUM_STRING_NAMES(nuclearLaunchCodes, nuclearLaunchCodesData) #undef nuclearLaunchCodes int main() { printf("%s\n", nuclearLaunchCodesData_Strings[0]); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T03:18:25.120", "Id": "465496", "Score": "0", "body": "C or C++? Please pick one tag. C and C++ are different languages with very different programming idioms and techniques, so reviewers can focus better if you choose only one language." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T03:22:41.757", "Id": "465497", "Score": "0", "body": "Figured this works in both but I'll change it to C" } ]
[ { "body": "<p>Most macro solutions are not readable nor maintainable. You should avoid macro solutions like this.</p>\n\n<p>The best way is to not use macros at all:</p>\n\n<pre><code>typedef enum\n{\n ZERO,\n ONE, \n TWO, \n THREE,\n NUMBERS_N\n} numbers_t;\n\nstatic const char* NUMBER_STR[NUMBERS_N] = \n{\n [ZERO] = \"ZERO\",\n [ONE] = \"ONE\",\n [TWO] = \"TWO\",\n [THREE] = \"THREE\",\n};\n\nputs(NUMBER_STR[1]); // prints ONE\n</code></pre>\n\n<p>This code is perfectly readable and it maintains the integrity between the enum and the array well. It only has one small problem and that is code repetition. </p>\n\n<p>Code repetition should be avoided, but programmers tend to exaggerate how bad it is. It is rarely ever so bad that it justifies turning your whole program into \"macro hell\". </p>\n\n<p>The reasons why code repetition should be avoided is that is leads to typo-like bugs and problems with maintenance. However, while a \"macro hell\" solution might rule out the typos, it makes the code difficult to maintain and the increased complexity increases the chance of other more serious bugs.</p>\n\n<p>Famous quote by Brian Kernighan:</p>\n\n<blockquote>\n <p>Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?</p>\n</blockquote>\n\n<p>That being said, there are valid cases where you must centralize data in one place, particularly when maintaining existing code that shouldn't be changed more than necessary. The macro you posted is a flavour of \"<a href=\"https://en.wikipedia.org/wiki/X_Macro\" rel=\"nofollow noreferrer\">X macros</a>\", which is the preferable way to write such macros - \"messy in a standardized way\" so to speak. X macros is about defining a list of data as you do, but to pass on that data to localized macros embedded into the code itself. To rewrite the above code with X macros, you'd do:</p>\n\n<pre><code>#define NUMBER_LIST \\\n X(ZERO) \\\n X(ONE) \\\n X(TWO) \\\n X(THREE) \\\n\ntypedef enum\n{\n #define X(name) name,\n NUMBER_LIST\n #undef X\n NUMBERS_N\n} numbers_t;\n\nstatic const char* NUMBER_STR[NUMBERS_N] = \n{\n #define X(name) [name] = #name,\n NUMBER_LIST\n #undef X\n};\n\nputs(NUMBER_STR[1]); // prints ONE\n</code></pre>\n\n<p>The advantage here is the flexibility to apply the same data in different ways, on case-by-case basis. A macro such as <code>#define X(name) [name] = #name,</code> is cryptic by itself, but when given the context of the surrounding array initializer list, one can easier understand the meaning. \"X macros\" can also be used to manually unroll loops:</p>\n\n<pre><code>#define X(name) puts(NUMBER_STR[name]);\n NUMBER_LIST\n#undef X\n</code></pre>\n\n<p>This is equivalent to iterating over the array and printing all items, but the loop is unrolled and we end up with a number of <code>puts</code> calls.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T14:35:49.117", "Id": "465567", "Score": "0", "body": "Using the C programming language there is no way to write generics except for macros." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T14:37:39.557", "Id": "465569", "Score": "0", "body": "@pacmaninbw There is _Generic but I'm not sure what that has to do with this post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T00:24:56.373", "Id": "466229", "Score": "0", "body": "Thank you, I'll keep this in mind as I'm working on a rather large side project that requires this sort of thing (https://github.com/BoredBored/Turtle/blob/master/failed-attempts/attempt5/token.h). Additionally, my example does not work as I forgot to put `GENERATE_ENUM_LIST()` before I undef-ed `nuclearLaunchCodes`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T08:09:53.073", "Id": "237424", "ParentId": "237410", "Score": "4" } } ]
{ "AcceptedAnswerId": "237424", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T03:09:03.247", "Id": "237410", "Score": "1", "Tags": [ "c", "enum", "macros" ], "Title": "Macro to generate an enum and an array of strings" }
237410
<p>I made this so I can feed it integers and return an array with all the divisors of that integer. I put checks in in case the integer is less than 2. Order of integers in the array must be smallest to largest. The code works. What I need is to optimize this code to be as fast as possible. Right now on an online IDE I am getting around 40ms combined against the given test. I need to trim this down as much as possible.</p> <pre><code>using System.Collections.Generic; public class Divisors { public static bool IsPrime(int n) { if (n == 2) return true; if (n % 2 == 0) return false; for (int x = 3; x * x &lt;= n; x += 2) if (n % x == 0) return false; return true; } public static int[] GetDivisors(int n) { List&lt;int&gt; divisors = new List&lt;int&gt;(); if (n &lt; 2) { return null; } else if (IsPrime(n)) { return null; } else { for (int i = 2; i &lt; n; i++) if (n % i == 0) divisors.Add(i); } return divisors.ToArray(); } } </code></pre> <pre><code>namespace Solution { using NUnit.Framework; using System; [TestFixture] public class SolutionTest { [Test] public void SampleTest() { Assert.AreEqual(new int[] {3, 5}, Divisors.Divisors(15)); Assert.AreEqual(new int[] {2, 4, 8}, Divisors.Divisors(16)); Assert.AreEqual(new int[] {11, 23}, Divisors.Divisors(253)); Assert.AreEqual(new int[] {2, 3, 4, 6, 8, 12}, Divisors.Divisors(24)); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T06:20:00.407", "Id": "465506", "Score": "0", "body": "Welcome to CodeReview@SE. If you are \"relatively new\" to programming *or* to coding in C#, consider tagging the question [tag:beginner]. I advise you to drop \"*C# Code to* \" from the title: that is sufficiently pointed out by the `c#` language tag." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T07:35:34.333", "Id": "465519", "Score": "2", "body": "Every natural number is divisible at least by 1 and itself. Have you omitted these divisors on purpose?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T13:54:45.180", "Id": "465564", "Score": "0", "body": "is `Divisors.Divisors` a typo?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T22:01:30.803", "Id": "465631", "Score": "0", "body": "Yes its a typo." } ]
[ { "body": "<h1>Style</h1>\n\n<p>As far as style goes, your code looks clean and readable, and follows the conventions, so good job for that.</p>\n\n<p>You may want to include documentation comments with <code>\\\\\\</code> four your class and methods. Although the method names are descriptive enough in this rather simple case, it is a good habit to take on.</p>\n\n<h1>Tests</h1>\n\n<p>It's nice you use a test framework to test your class. However, the methods name don't match (<code>Divisors</code> vs <code>GetDivisors</code>) and comparing arrays doesn't work that way.</p>\n\n<p>You could also benefit from including more tests for edge cases . What if the given argument is prime (since you make it a special case)? What if it is <code>int.MaxValue</code>? What if it is <code>0</code>? What if it is negative?</p>\n\n<h1>Make your class <code>static</code></h1>\n\n<p>Your <code>Divisors</code> class only has static methods. As such, it should be a <code>static</code> class. I might help the compiler with optimizations and can improve performance a little.</p>\n\n<h1>Unexpected behavior</h1>\n\n<p>As far as I know, 1 and <code>n</code> are always divisors of <code>n</code>, yet they are omitted from the returned array. You should probably include them, or at least document that they are omitted.</p>\n\n<p>If the number is negative, you return <code>null</code>. While in theory negative numbers have divisors (and positive numbers have negative divisors), I understand why this you chose this approach, as well as why you only return positive divisors. I would suggest you either document this behavior, or enforce it by using the <code>uint</code> datatype. I would chose the former approach, as <code>int</code>is much more prevalent, and using <code>uint</code> would most likely imply a lot of casting down the line.</p>\n\n<h1>Optimizing the algorithm</h1>\n\n<p>You check if the number is prime before looking for divisors. First of all, your algorithm for primality checking is rather naive and can be optimized in various ways. More importantly, this is an optimization only if the argument is prime, but is counterproductive in the vast majority of cases when it isn't prime. I suggest to simply get rid of that check.</p>\n\n<p>Furthermore, you check if every number between <code>2</code> and <code>n</code> is a divisor of <code>n</code>; however, you know that if <code>i</code> is a divisor, so is <code>n / i</code>. Therefore, you can loop only on values between <code>1</code> and <code>sqrt(n)</code> and add two divisors for every match.</p>\n\n<h1>My attempt</h1>\n\n<pre><code> public static class Divisors\n {\n /// &lt;summary&gt;\n /// Finds all the divisors of any positive integer passed as argument. \n /// Returns an array of int with all the divisors of the argument.\n /// Returns null if the argument is zero or negative.\n /// &lt;/summary&gt;\n public static int[] GetDivisorsMe(int n)\n {\n if (n &lt;= 0)\n {\n return null;\n }\n List&lt;int&gt; divisors = new List&lt;int&gt;();\n for (int i = 1; i &lt;= Math.Sqrt(n); i++)\n {\n if (n % i == 0)\n {\n divisors.Add(i);\n if (i != n / i)\n {\n divisors.Add(n / i);\n }\n }\n }\n divisors.Sort();\n return divisors.ToArray();\n }\n }\n</code></pre>\n\n<p>As for performance, finding all divisors for every integer between 0 and 10,000 takes around 130ms with your solution on my machine vs 12ms with mine, so a performance gain of around 10x.<br>\nFinding divisors for <code>int.MaxValue</code> takes around 9s your solution vs 5ms with mine, a performance gain greater than 1000x!<br>\nFinally, finding divisors for <code>2095133040</code> &ndash; the largest highly composite number that fits in the <code>int</code> datatype, with a total of 1600 divisors &ndash; takes around 5s with your solution, vs 13ms with my solution, again a performance gain of around 400x.</p>\n\n<p>Performance can probably be improved further by estimating how many divisors has a given input and passing that estimate to the <code>List&lt;int&gt;</code> constructor, and thus limiting how much memory reallocating is done as the list grows. In fact, the upper bound of the number divisors is known: 1600. You could simply allocate the list as:</p>\n\n<pre><code>List&lt;int&gt; divisors = new List&lt;int&gt;(1600);\n</code></pre>\n\n<p>This brings the execution time down to 5ms for the highest composite number, but feels like a waste of memory in most cases.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T15:23:19.140", "Id": "465577", "Score": "0", "body": "Dont compute square root of n again in every iteration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T15:27:59.817", "Id": "465578", "Score": "0", "body": "Good catch. I implicitly rely on compiler optimization: I think any modern compiler would memoize that value. Performance testing show no measurable difference between my approach and explicitly allocating a variable with that value. I'm not so sure about the `x*x < n` in the original code however, so I decided not to reuse that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T15:36:04.653", "Id": "465583", "Score": "0", "body": "ok, i wasnt sure how c# handles this. Anyway did you try with int.MaxValue?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T15:53:15.900", "Id": "465589", "Score": "0", "body": "@slepic I tried with `int.MaxValue`, and initially had a typo in my performance benchmark, it turns out the performance improvement is great (I was initially running the initial code against itself...). Also, it turns out that `int.MaxValue` is 2^31-1, which is a Mersenne Prime, so list preallocation isn't an issue for this particular value (only 2 factors)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T15:59:51.150", "Id": "465590", "Score": "0", "body": "If you can find the largest integer that Is a product of consecutive primes starting at 2, you may want to test on that number as it should have the most divisors. Just for criosity :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T16:28:27.443", "Id": "465594", "Score": "0", "body": "@slepic Good idea, I edited my answer to include something like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T22:31:36.833", "Id": "465634", "Score": "0", "body": "That refactor with some changes to my code is what got me to finally speed this. I still had to add back the *isPrime* so I can return a null which did slow this down again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T22:38:23.020", "Id": "465635", "Score": "0", "body": "Thank you @gazoh for your help. That refactor was what I needed along with the advice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T04:40:04.950", "Id": "465653", "Score": "0", "body": "@gazoh if you move `Math.Sqrt(n)` to `int iterator = (int)Math.Sqrt(n);` it would boost up the performance maybe around %10, that's a micro-boost ;).. you can also convert the return to `IEnumerable<int>` and just exclude `Sort()` and `ToArray()` and use `yield return` instead of the local list. this would make a huge performance boost. As `ToArray` and `Sort` are expensive operations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T08:20:43.333", "Id": "465678", "Score": "0", "body": "@iSR5 You're right, assigning `(int)Math.Sqrt(n)` to a variable before the loop increases performance by 33%, I'll update my answer (8s vs 12s on 100000 iterations on random data on my machine), I was overly confident in the compiler. I'll update my answer accordingly. However, excluding `Sort()` and `ToArray()` yield no further significant performance gain. Yes, they are quite slow, but operate on a maximum of 1600 values, which is rather small. Also, getting rid of `Sort()` means the output would be in an unexpected order." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T08:30:26.500", "Id": "465679", "Score": "0", "body": "@Milliorn If you really don't want the first and last divisor, you can just start the loop at `i = 2`, which would return an empty list for primes, or check for an empty list and return null. You wouldn't take the performance hit from you sub-optimal prime checking method, or the performance hit on all non-prime values even if you optimize your prime checking algorithm. If you otherwise need an `IsPrime` method, there are plenty of resources on the internet on how to make an efficient prime checking function, using a sieves of Eratosthenes, for example" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:05:03.273", "Id": "465743", "Score": "0", "body": "All these comments about caching the value of the square root are missing the point. **Do not calculate the square root at all, ever, if you can avoid it**. Square root computation is extremely expensive! `x * x < y` is much faster than `x < sqrt(y)`, provided that you know that `x * x` does not overflow. You say above that you were \"not sure about it\". What was the cause of your uncertainty?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T10:49:08.263", "Id": "465859", "Score": "0", "body": "@EricLippert Why shouldn't I calculate the square root? I ran some more tests using `x * x < y`. It turns out it does overflow on large inputs (larger than `int.MaxValue - 6`, not sure why though), so it requires using `long` and a bunch of casting to `int`, which makes the code harder to read and slower, and performs worse than caching the value of the square root. 100,000 iterations on random (seeded) values take 8.8s with explicitly caching the square root result, 9.17s with `x * x` (with overflow risk) and 27s with `x * x` and casting from `long`." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T15:07:58.910", "Id": "237442", "ParentId": "237416", "Score": "4" } }, { "body": "<p>I saw it would be better if I post an answer instead of using comments. </p>\n\n<p>For your <code>IsPrime</code> method, I see that you've covered most conditions, but you forgot to cover 0, 1, and -n cases, which you can just do with a small change on this line :</p>\n\n<p><code>if (n % 2 == 0) return false;</code> </p>\n\n<p>to </p>\n\n<p><code>if (n &lt; 2 || n % 2 == 0) return false;</code></p>\n\n<p>suggested : </p>\n\n<pre><code>public static bool IsPrime(int n)\n{\n if(n == 2) { return true; }\n\n if (n &lt; 2 || (n % 2 == 0)) { return false; }\n\n for (int x = 3; x * x &lt;= n; x += 2)\n {\n if (n % x == 0) { return false; }\n }\n\n return true;\n}\n</code></pre>\n\n<p>For <code>GetDivisors</code>. I assume that you excluded <code>1</code> and <code>n</code> from the results, since it's already known that every natural number is divisible by 1 and itself, which is fine if you intended to use this code personally, but it is uncommon to do that, and it might even conflict with other developers code, as you don't want to assume everybody knows that! so it must be included to make the code more usable for others, and you must always consider what is common use, and what is not.</p>\n\n<p>The technique in @gazoh answer is a really good one, and I would take it to the next level, but I have to note out that <code>Sort</code> and <code>ToArray</code> are expensive operations as I've mentioned in the comments. And I would avoid using them directly. </p>\n\n<p>I've updated this method to : </p>\n\n<pre><code>private static IEnumerable&lt;int&gt; GetDivisors(int n)\n{\n if (n &lt;= 0) { yield return default; }\n\n int iterator = (int)Math.Sqrt(n);\n\n for (int i = 1; i &lt;= iterator; i++)\n {\n if (n % i == 0)\n {\n yield return i; \n\n if (i != n / i) { yield return n / i; }\n }\n }\n}\n\npublic static IEnumerable&lt;int&gt; GetDivisors(int n, bool AscendingOrder = false)\n{\n return !AscendingOrder ? GetDivisors(n) : GetDivisors(n).OrderBy(x =&gt; x);\n}\n</code></pre>\n\n<p>I've used <code>IEnumerable&lt;int&gt;</code> to open more acceptable collections types rather than just sticking with an array. The overload is just to have an option to order the data, while the default is <code>unordered</code> data. This would make it optional, which would depend on usage, if you prefer performance over order, or order over performance. Then you can convert it to list or array or any collection. </p>\n\n<p>For performance differences, I've used <code>BenchmarkDotNet</code> to test and compare this method performance and here is the results. </p>\n\n<p><strong>Test 1 using <code>GetDivisors(2095133040)</code></strong></p>\n\n<pre><code>| Method | Mean | Error | StdDev |\n|------------------- |---------------------:|--------------------:|--------------------:|\n| Original | 5,907,229,864.000 ns | 116,153,274.6298 ns | 155,061,285.3568 ns |\n| ByGazoh | 169,411.783 ns | 2,805.6563 ns | 2,487.1413 ns |\n| IEnumerable&lt;int&gt; | 6.637 ns | 0.1896 ns | 0.2107 ns |\n| OrderBy | 17.514 ns | 0.3013 ns | 0.2516 ns |\n| ToArray | 151,408.141 ns | 2,906.1875 ns | 2,854.2648 ns |\n| ToList | 363,424.079 ns | 5,318.8335 ns | 4,975.2401 ns |\n| ToArray + OrderBy | 154,249.309 ns | 2,370.8673 ns | 2,101.7121 ns |\n| ToList + OrderBy | 356,705.127 ns | 6,002.7773 ns | 5,321.3057 ns |\n</code></pre>\n\n<p><strong>Test 2 using <code>GetDivisors(1600)</code></strong></p>\n\n<pre><code>| Method | Mean | Error | StdDev |\n|------------------- |-------------:|-----------:|-----------:|\n| Original | 4,804.474 ns | 93.0708 ns | 91.4080 ns | \n| ByGazoh | 515.822 ns | 7.6545 ns | 7.1601 ns | \n| IEnumerable&lt;int&gt; | 6.391 ns | 0.0966 ns | 0.0904 ns | \n| OrderBy | 16.783 ns | 0.2839 ns | 0.2517 ns | \n| ToArray | 422.570 ns | 6.3368 ns | 5.9274 ns | \n| ToList | 463.575 ns | 8.0975 ns | 7.5744 ns |\n| ToArray + OrderBy | 1,662.728 ns | 26.8204 ns | 25.0878 ns |\n| ToList + OrderBy | 1,634.595 ns | 30.9492 ns | 28.9499 ns |\n</code></pre>\n\n<p><strong>ns = nano-second;</strong></p>\n\n<p>Where </p>\n\n<ul>\n<li><code>OrderBy</code> = <code>Divisors.GetDivisors(n).OrderBy(x=&gt;x);</code></li>\n<li><code>ToArray</code> = <code>Divisors.GetDivisors(n).ToArray();</code></li>\n<li><code>ToList</code> = <code>Divisors.GetDivisors(n).ToList();</code></li>\n<li><code>ToArray + OrderBy</code> = <code>Divisors.GetDivisors(n).OrderBy(x=&gt;x).ToArray();</code></li>\n<li><code>ToList + OrderBy</code> =<code>Divisors.GetDivisors(n).OrderBy(x=&gt;x).ToList();</code></li>\n</ul>\n\n<p>Lastly, regarding your tests, I suggest you test each scenario separately.</p>\n\n<p>Example : </p>\n\n<pre><code>[TestMethod]\npublic void GetDivisors_15_IsEqual()\n{\n Assert.AreEqual(new int[] { 3, 5 }, Divisors.Divisors(15));\n}\n\n[TestMethod]\npublic void GetDivisors_16_IsEqual()\n{\n Assert.AreEqual(new int[] { 2, 4, 8 }, Divisors.Divisors(16));\n}\n\n[TestMethod]\npublic void GetDivisors_253_IsEqual()\n{\n Assert.AreEqual(new int[] { 11, 23 }, Divisors.Divisors(253));\n}\n\n[TestMethod]\npublic void GetDivisors_24_IsEqual()\n{\n Assert.AreEqual(new int[] { 2, 3, 4, 6, 8, 12 }, Divisors.Divisors(24));\n}\n</code></pre>\n\n<p> the reason is simple, if you create a separate test for each scenario you have, it'll be easy to determine which part of your code needs adjustments, and it would make things easier for improving your code (say you want to simplify it without breaking the code). Also, it would be more easier to read and follow, and could give you a better view on the requirements, and the validation process of it. </p>\n\n<p>If you don't detailed your tests, in smaller projects you might not have any issues, but in big projects, it'll be a pain in the neck.</p>\n\n<p>I hope this would be useful. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:11:23.747", "Id": "465797", "Score": "0", "body": "**For your IsPrime method, I see that you've covered most conditions, but you forgot to cover 0, 1, and -n cases, which you can just do with a small change on this line :**\n\nReason for that is due to this.\n\n**Take an integer n > 1 and returns an array with all of the integer's divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return null**\n\n**public static IEnumerable<int>**\n\nI completely agree that this would be optimal. I am however bound to returning an int[] for this. Very interesting stats you posted. Gives me a great perspective." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T01:18:37.233", "Id": "465809", "Score": "0", "body": "@Milliorn but still is not covered, test your original `IsPrime` with 0 and -1, it would return true, which are false results. So, the adjustment would solve that. because your method is exposed, so you need to consider to implement its own validations and don't depend on `GetDivisors` validations only. For the `int[]` you can use the `IEnumerable<int> ` as private method, and create an overload to call it back and use `ToArray()` this would return `int[]` and it would be much faster." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T11:42:15.230", "Id": "237490", "ParentId": "237416", "Score": "1" } }, { "body": "<p>You can get a vast improvement in speed: If x is divisible by y, then x is also divisible by (x / y) with the result y. </p>\n\n<p>So if you try to get the divisors of 1,000,000,000,000 you only need to divide by the numbers 1 to 1,000,000 and add two divisors to your list at a time instead of 1. The exception is when x is a square and x/y = y since you don’t want to add the same divisor twice. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T16:10:23.953", "Id": "237500", "ParentId": "237416", "Score": "1" } }, { "body": "<blockquote>\n <p>What I need is to optimize this code to be as fast as possible.</p>\n</blockquote>\n\n<p>That's premature. Start by making the code correct. For example, you do a multiplication of <code>x*x</code> in your primality check, but that can overflow. </p>\n\n<p>Once you have the code correct, then <strong>run the code through a profiler to find out where the slow parts are</strong> and attack those one at a time.</p>\n\n<p>What you will discover is that you are spending a huge amount of time checking to see if numbers are primes. </p>\n\n<p>Let's think about this a bit. You want the divisors of a positive 32 bit integer, so it is between 1 and around two billion. If the number is composite then its largest prime factor will be less than 45000. <strong>But there are only about 5000 primes less than 45000</strong>. Calculate them all <em>once</em> and put them in a sorted list. You can then binary search that list very quickly, or build a more optimized lookup.</p>\n\n<p>The algorithm now becomes:</p>\n\n<ul>\n<li>If the number is less than 45000, just check to see if it is on the list; that's binary-searchable.</li>\n<li>If the number is greater than 45000, check to see if it is divisible by any prime. That does a maximum of about 5000 checks and you don't waste any time checking non-primes.</li>\n</ul>\n\n<p>Now let's think about it harder. </p>\n\n<p>What is your algorithm for finding divisors? </p>\n\n<ul>\n<li>Do an expensive test to see if a number is prime; if it is, it only has two divisors.</li>\n<li>Otherwise, check every possible divisor up to its square root.</li>\n</ul>\n\n<p>This algorithm is incredibly expensive. We've seen that we can make the first part cheaper. Can we make the second part cheaper?</p>\n\n<p>Yes. A far better algorithm is:</p>\n\n<ul>\n<li>Determine the prime factorization of the number</li>\n<li>The divisors are all possible products of prime factors</li>\n</ul>\n\n<p>The trick here is that <em>for composite numbers, determining prime factors can be sped up</em>.</p>\n\n<p>Let's see how. Suppose you want the prime factors of 36.</p>\n\n<p>We start by noting that 36 is divisible by 2. Now comes the trick. <strong>The prime factors of 36 are 2, followed by the prime factors of 18</strong>. We just made the problem <em>smaller</em>. </p>\n\n<p>18 is divisible by 2 as well, so the prime factors of 36 are 2, 2, and the prime factors of 9. Again, we've made the problem smaller.</p>\n\n<p>What are the prime factors of 9? 2 doesn't work, so we bump up to 3. 3 works. So the prime factors of 36 are 2, 2, 3 and the prime factors of 3. </p>\n\n<p>What are the prime factors of 3? <strong>We do not start again at 2, because we know that we've already taken out all possible 2s</strong>. We start at 3, and get down to 1, and we're done. The prime factors of 36 are 2, 2, 3, 3.</p>\n\n<p>That solves the first problem. The second problem is then <strong>generate all possible products</strong>. The way to do this is to generate all possible combinations of 0, 1 and 2 as follows:</p>\n\n<pre><code>0 0 is 1 * 1 = 1\n0 1 is 1 * 3 = 3\n0 2 is 1 * 3 * 3 = 9\n1 0 is 2 * 1 = 2\n1 1 is 2 * 3 = 6\n1 2 is 2 * 3 * 3 = 18\n</code></pre>\n\n<p>and so on. Generate all possible combinations of products, put their results in an array, and sort that ascending.</p>\n\n<p>This algorithm is more complicated but it is typically much faster when the numbers get big.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:02:31.880", "Id": "465793", "Score": "0", "body": "**That's premature. Start by making the code correct. For example, you do a multiplication of x*x in your primality check, but that can overflow.**\n\nDid not consider that because in this specific case that would not happen, but this is indeed necessary otherwise.\n\n**What you will discover is that you are spending a huge amount of time checking to see if numbers are primes.**\n\nCorrect. Another comment suggested sieves of Eratosthenes which I was not aware of (I'm not math savvy at all).\n\nYou suggestion to use a list is very interesting. Was not aware of this approach to this problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:05:22.543", "Id": "465796", "Score": "0", "body": "@Milliorn: If you're going to be spending time working on these sorts of problems, getting even a small amount of \"math savviness\" will help you immensely. You might consider doing the first hundred or so Project Euler problems. They increase in difficulty slowly and do a pretty good job of building harder problems out of the solutions to simpler problems. Or get a good book on elementary number theory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:14:16.007", "Id": "465798", "Score": "0", "body": "I recently found that site. I am trying to get comfortable with this because its a weakness of mine. I'm not sure if I will spend considerable time in this in the future, but I don't want to be uncomfortable or unprepared either." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:20:17.230", "Id": "465799", "Score": "0", "body": "@Milliorn: This is a great opportunity for skill growth! You can learn a lot about math this way, and a stronger theoretical and practical grasp of foundational finite mathematics, particularly combinatorics, is a big help in solving programming problems. Particularly optimization problems. You've learned today a little bit about two of the fundamental principles of optimization: **you can often trade more space for less time**, and **compute stuff that does not change ahead of time**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:27:41.127", "Id": "465800", "Score": "0", "body": "Indeed, I have spent my time trying to type concise, readable code when **trade more space for less time, and compute stuff that does not change ahead of time** would of been ideal here in solving my issue." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:25:44.153", "Id": "237505", "ParentId": "237416", "Score": "1" } } ]
{ "AcceptedAnswerId": "237442", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T05:20:31.407", "Id": "237416", "Score": "3", "Tags": [ "c#", "performance", "mathematics" ], "Title": "C# Code to Find all Divisors of an Integer" }
237416
<p>I have this jQuery handled buttons. But I think I overdid it with the <code>if else</code> statements.</p> <p>I am wondering if the code can be more efficient in some way than what I have. It's mainly voting up and down. So what is does is toggle buttons and inserts HTML.</p> <pre><code>function handleVote(commentid, voted, type){ $.ajax({ url: endpoint + commentid + "/update/", method: "PATCH", data: { commentid: commentid, voted: voted, type: type}, success: function(data){ console.log(data) if(type === 'down' &amp;&amp; voted === 'True'){ $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('active-color'); $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('opacity-initial'); $('.comment-item .down-vote .i-down-'+commentid+'').css('opacity', '0.2') } else if(type === 'down' &amp;&amp; voted === 'False'){ $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('active-color'); $('.comment-item .down-vote .i-down-'+commentid+'').toggleClass('opacity-initial'); } else if(type === 'up' &amp;&amp; voted === 'True'){ $('.comment-item .up-vote .i-up-'+commentid+'').toggleClass('primary-color'); $('.comment-item .up-vote .i-up-'+commentid+'').toggleClass('opacity-initial'); $('.comment-item .up-vote .i-up-'+commentid+'').css('opacity', '0.2') } else if(type === 'up' &amp;&amp; voted === 'False'){ $('.comment-item .down-vote .i-up-'+commentid+'').toggleClass('primary-color'); $('.comment-item .down-vote .i-up-'+commentid+'').toggleClass('opacity-initial'); } $(".comment-vote-down .vote-count-down-" + commentid +"").html(`-${data.num_vote_down}`); $(".comment-vote-up .vote-count-up-" + commentid +"").html(`+${data.num_vote_up}`); }, error: function(data){ var msg = formatErrorMsg(data.responseJSON) $("[data-id='" + commentid + "']").closest('div .comment-wrapper').after(msg); } }) } </code></pre>
[]
[ { "body": "<p>Use variable for element, toggle can take multiple classes, use minimal selector.</p>\n\n<pre><code>var voteButton;\nif(type === 'down'){\n voteButton = $('.i-down-' + commentid);\n voteButton.toggleClass('active-color opacity-initial');\n} else {\n voteButton = $('.i-up-'+commentid);\n voteButton.toggleClass('primary-color opacity-initial'); \n}\nif(voted === 'True'){\n voteButton.css('opacity', '0.2')\n}\n</code></pre>\n\n<p>or you could stack functions</p>\n\n<pre><code>$('.comment-item .down-vote .i-down-'+commentid+'')\n .toggleClass('active-color opacity-initial')\n .css('opacity', '0.2')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:53:13.110", "Id": "465804", "Score": "0", "body": "If you're able to use ES6 syntax, or transpile with Babel, you can also use string literals to make the selector dynamic, e.g. `\\`.comment-item .${type}-vote .i-${type}-${commentid}\\``" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T09:00:25.843", "Id": "237425", "ParentId": "237423", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T07:53:24.353", "Id": "237423", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Toggle CSS class on vote" }
237423
<p>I am writing code to write a C template file; the executable takes two arguments (main) <code>&lt;file name&gt;</code> and <code>&lt;no of questions&gt;</code> and outputs a file with a file named <code>argv[1]</code> and inside which there are <code>n</code> no of functions with <code>n+1</code> switch cases in <code>main()</code> calling those functions; where <code>n = argv[2]</code>.</p> <h3>Problem</h3> <ul> <li>My problem is with the allocation of memory to the <code>char*</code>'s, it feels so messy and roundabout.</li> <li><p>The formatting of strings some times gives no seg faults other times it is not possible. For example, <code>ass = fopen(("./%s",fname),"w");</code> works fine; but <code>strncat(swic,(" case %d : q%d();break;\n",i,i),s/n);</code> does not work. For it to work I have to use <code>format()</code> a user function defined as follows:</p> <pre><code>char* format(char* s,...){ va_list args; size_t siz=strlen(s)+sizeof(size_t); char* res=(char*)malloc(siz); va_start(args,s); vsnprintf(res, siz, s, args); va_end(args); return(res); } </code></pre></li> <li><p>Another problem in above function is that I am unable to get the size or no. of passed arguments which I need to correctly allocate <code>char *res</code> which contains the resultant formatted string.</p></li> <li>Also, during debugging I found that during <code>fclose(ass)</code> in <code>main()</code>; vscode gives two faults <code>received SIGTRAP, Trace/breakpoint trap. in ntdll!RtlpNtMakeTemporaryKey</code><br><code>received signal ?, Unknown signal.</code>, then exits.</li> </ul> <p><a href="https://pastebin.pl/view/7190a823" rel="nofollow noreferrer">Click to view the complete code</a></p> <pre class="lang-c prettyprint-override"><code> char* tail(n) { char *main="\nint main(){\nint choi;\nprintf(\"\\n*note: enter 0 to diplay all Q\\n\\n Display Q no. \");\nscanf(\" %%d\",&amp;choi);\nswitch(choi){\n"; char *naim=" default: printf(\"! invalid choice !\");\n}\nreturn 0;\n}"; size_t f=strlen(format("void q%d(){printf(\"\\n ---- Q %d -----\\n\");\n}\n",n,n))*n, s=strlen(format(" case %d : q%d();break;\n",n,n))*n, s0=strlen(format("q%d();",n))*n,c0=strlen(" case 0 : break;\n"); char *func=(char*)malloc(f); // strcpy(func,""); char *swic0=(char*)malloc(s0); char *swic=(char*)malloc(s); // strcpy(swic,""); for(int i=1;i&lt;=n;i++){ if(i==1){ strcpy(func,format("void q%d(){printf(\"\\n ---- Q %d -----\\n\");\n}\n",i,i)); strcpy(swic,format(" case %d : q%d();break;\n",i,i)); strcpy(swic0,format("q%d();",i)); } else{ strncat(func,format("void q%d(){printf(\"\\n ---- Q %d -----\\n\");\n}\n",i,i),f/n); strncat(swic,format(" case %d : q%d();break;\n",i,i),s/n); strncat(swic0,format("q%d();",i),s0/n); } } // return strcat(strcat(strcat(func,main),swic),naim); char *case0=(char*)malloc(c0+s0); sprintf(case0," case 0 : %sbreak;\n",swic0); char *res=(char*)malloc(strlen(format("%s%s",main,naim))+f+s+c0+s0); sprintf(res,"%s%s%s%s%s",func,main,case0,swic,naim); return res; } </code></pre> <p>Example: output file if <code>argv[2]=="2"</code></p> <pre class="lang-c prettyprint-override"><code> //########## Loops assigment #include&lt;stdio.h&gt; int abs(int n){ if(n&lt;0) return n*-1; else return n; } // answer functions -- void q1(){printf("\n ---- Q 1 -----\n"); } void q2(){printf("\n ---- Q 2 -----\n"); } int main(){ int choi; printf("\n*note: enter 0 to diplay all Q\n\n Display Q no. "); scanf(" %d",&amp;choi); switch(choi){ case 0 : q1();q2();break; case 1 : q1();break; case 2 : q2();break; default: printf("! invalid choice !"); } return 0; } </code></pre>
[]
[ { "body": "<p>We need to be more defensive in these areas:</p>\n\n<ul>\n<li><code>malloc()</code> and family can return a null pointer.</li>\n<li><code>scanf()</code> and family can return fewer than requested conversions.</li>\n</ul>\n\n<p>Additionally, there's no need to cast the result of <code>malloc()</code> - if you've correctly included <code>&lt;stdlib.h&gt;</code>, then it returns a <code>void*</code>, which is assignable to any pointer type.</p>\n\n<p>Writing the unnecessary cast makes the code harder to review, because all casts indicate areas that need close attention by the reviewer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T11:13:28.967", "Id": "237431", "ParentId": "237426", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T09:51:39.550", "Id": "237426", "Score": "0", "Tags": [ "beginner", "c", "strings", "memory-management", "pointers" ], "Title": "Code to write a C template file" }
237426
<p>Please take a review of my simple .ini config loader / saver:</p> <pre><code>// // value wrapper // class IniEntry { public: // // default ctor IniEntry() { } // // copy ctor IniEntry(const IniEntry&amp; rhs) : _Data(rhs._Data) { } // // move ctor IniEntry(IniEntry&amp;&amp; rhs) noexcept : _Data(std::move(rhs._Data)) { } // // dtor ~IniEntry() { } public: // // copy assignment IniEntry&amp; operator=(const IniEntry&amp; rhs) { _Data = rhs._Data; return *this; } // // move assignment IniEntry&amp; operator=(IniEntry&amp;&amp; rhs) noexcept { _Data = std::move(rhs._Data); return *this; } // // string assignment IniEntry&amp; operator=(const char* value) { SetAsString(value); return *this; } // // integer assignment IniEntry&amp; operator=(int value) { SetAsInteger(value); return *this; } // // float assignment IniEntry&amp; operator=(float value) { SetAsFloat(value); return *this; } public: // // string explicit cast explicit operator const char*() const { return GetAsString(); } // // integer explicit cast explicit operator int() const { return GetAsInteger(); } // // float explicit cast explicit operator float() const { return GetAsFloat(); } public: // // set data from string inline void SetAsString(const char* value) { _Data.assign(value); } // // get data as string inline const char* GetAsString(const char* default_return = "") const { return _Data.empty() ? default_return : _Data.c_str(); } // // set data from integer inline void SetAsInteger(int value) { _Data.assign(std::to_string(value)); } // // get data as integer inline int GetAsInteger(int default_return = 0) const { try { return std::stoi(_Data); } catch (...) { return default_return; } } // // set data from float inline void SetAsFloat(float value) { _Data.assign(std::to_string(value)); } // // get data as float inline float GetAsFloat(float default_return = 0.f) const { try { return std::stof(_Data); } catch (...) { return default_return; } } public: // // check if data empty bool Empty() const { return _Data.empty(); } private: std::string _Data; }; // // util object to restrict copy (and move if not declared move information) // class IniNonCopyable { public: IniNonCopyable(const IniNonCopyable&amp;) = delete; IniNonCopyable&amp; operator=(const IniNonCopyable&amp;) = delete; }; // // container controller base // template&lt;class Element_t&gt; class IniContainer : public IniNonCopyable { typedef std::shared_ptr&lt;Element_t&gt; ContainerElement_t; typedef std::string ContainerKey_t; typedef std::unordered_map&lt;ContainerKey_t, ContainerElement_t&gt; Container_t; public: // // default ctor IniContainer() { } // // dtor virtual ~IniContainer() { } public: // // access to container element // if key does not exist - will be created new one Element_t&amp; operator[](const std::string&amp; key) { auto it = _Container.find(key); if (it != _Container.end()) { return *it-&gt;second.get(); } auto instance = new Element_t; _Container.insert(std::make_pair(key, instance)); return *instance; } // // check if container empty bool operator!() const { return Empty(); } public: // // create new element // if key already exist will be returned empty element virtual Element_t&amp; Create(const std::string&amp; key) { if (Has(key)) { static Element_t empty; return empty; } auto instance = new Element_t; _Container.insert(std::make_pair(key, instance)); return *instance; } // // delete existed element virtual bool Delete(const std::string&amp; key) { auto it = _Container.find(key); if (it == _Container.end()) { return false; } _Container.erase(key); return true; } // // access to container element // if key does not exist - will be returned empty element virtual Element_t&amp; At(const std::string&amp; key) const { auto it = _Container.find(key); if (it == _Container.end()) { static Element_t empty; return empty; } return *it-&gt;second.get(); } // // check if element at key exist virtual bool Has(const std::string&amp; key) const { return _Container.find(key) != _Container.end(); } // // container clear virtual void Clear() { _Container.clear(); } // // check if container empty virtual bool Empty() const { return _Container.empty(); } public: // // return ref to container data virtual const Container_t&amp; GetContainer() const { return _Container; } protected: Container_t _Container; }; // // section handler (IniEntry container) // class IniSection : public IniContainer&lt;IniEntry&gt; { public: // // default ctor IniSection() { } // // dtor virtual ~IniSection() { } }; // // file handler (IniSection container) // class IniFile : public IniContainer&lt;IniSection&gt; { public: // // default ctor // if path not empty then loading will be started automatically explicit IniFile(const std::string&amp; path = "") : _Path(path) { if (!_Path.empty()) { Load(); } } // // dtor virtual ~IniFile() { } public: // // file parsing // if path empty, then will be used ctor initialized path bool Load(const std::string&amp; path = "") { const std::string file_path(path.empty() ? _Path : path); if (file_path.empty()) { return false; } std::ifstream file_stream(file_path); if (!file_stream) { return false; } const std::regex comment_regex(R"x(\s*[;#])x"); const std::regex section_regex(R"x(\s*\[([^\]]+)\])x"); const std::regex value_regex(R"x(\s*(\S[^ \t=]*)\s*=\s*((\s?\S+)+)\s*$)x"); std::string file_line; std::smatch result; std::string section; while (std::getline(file_stream, file_line)) { if (file_line.empty() || std::regex_match(file_line, result, comment_regex)) { } else if (std::regex_match(file_line, result, section_regex) &amp;&amp; result.size() == 2) { section.assign(result[1]); Create(section); } else if (std::regex_match(file_line, result, value_regex) &amp;&amp; result.size() == 4) { At(section)[result[1]] = result[2].str().c_str(); } } return true; } // // file saving // if path empty, then will be used ctor initialized path bool Save(const std::string&amp; path = "") { const std::string file_path(path.empty() ? _Path : path); if (file_path.empty()) { return false; } std::ofstream file_stream(file_path); if (!file_stream) { return false; } for (auto&amp; section : GetContainer()) { file_stream &lt;&lt; "[" &lt;&lt; section.first &lt;&lt; "]" &lt;&lt; std::endl; for (auto&amp; entry : section.second-&gt;GetContainer()) { file_stream &lt;&lt; entry.first &lt;&lt; " = " &lt;&lt; (const char*)*entry.second &lt;&lt; std::endl; } file_stream &lt;&lt; std::endl; } return true; } private: std::string _Path; }; </code></pre> <p>The code has declaration / implementation in the same file, just because it's not finished yet. In the future, of course, those will be separated.</p> <p>Example of usage:</p> <pre><code>int main() { IniFile file("Test.ini"); if (!file) { std::cout &lt;&lt; "failed to load" &lt;&lt; std::endl; return 0; } auto&amp; general = file["General"]; if (!general) { std::cout &lt;&lt; "failed to pick section" &lt;&lt; std::endl; return 0; } auto title = general["Title"].GetAsString("Example"); auto rate = general["Rate"].GetAsInteger(100); auto scale = general["Scale"].GetAsFloat(200.f); // update and save example general["Rate"] = (int)general["Rate"] + 1; if (!file.Save()) { std::cout &lt;&lt; "failed to save" &lt;&lt; std::endl; return 0; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T17:31:00.047", "Id": "465604", "Score": "1", "body": "Welcome to Code Review! Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T17:38:16.390", "Id": "465607", "Score": "1", "body": "Hah, and again thank you, will keep in mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T17:40:55.593", "Id": "465608", "Score": "1", "body": "No problem - we were all new once. :-)" } ]
[ { "body": "<p>We're missing some required header includes:</p>\n\n<pre><code>#include &lt;fstream&gt;\n#include &lt;memory&gt;\n#include &lt;regex&gt;\n#include &lt;string&gt;\n#include &lt;unordered_map&gt;\n#include &lt;utility&gt;\n</code></pre>\n\n<hr>\n\n<p>The code doesn't compile until we give <code>IniNonCopyable</code> an accessible default constructor:</p>\n\n<pre><code>protected:\n IniNonCopyable() = default;\n</code></pre>\n\n<p>Classes that inherit from <code>IniNonCopyable</code> should inherit it privately.</p>\n\n<hr>\n\n<p>Names that begin with underscore followed by an uppercase letter are <em>reserved for any purpose</em>, which means that they may be pre-defined as macros, leading to very obscure bugs; avoid that naming convention.</p>\n\n<hr>\n\n<p>It seems strange that <code>IniEntry</code> can store <code>float</code> but not <code>double</code>; similarly, <code>char*</code> but not <code>std::string</code>.</p>\n\n<p>Its move and copy constructors and assignment, and destructor, all add no value and should be omitted.</p>\n\n<hr>\n\n<p>Modern C++ style prefers <code>using</code> to <code>typedef</code>:</p>\n\n<pre><code>using ContainerElement_t = std::shared_ptr&lt;Element_t&gt;;\nusing ContainerKey_t = std::string;\nusing Container_t = std::unordered_map&lt;ContainerKey_t, ContainerElement_t&gt;;\n</code></pre>\n\n<p>This puts the type being defined on the left-hand side, consistently with other C++ definitions.</p>\n\n<p>Be careful defining types that end with <code>_t</code>; double-check that these names are not reserved as they are in C.</p>\n\n<hr>\n\n<p>We have made the code much harder to test by not providing load/save methods that work on an already opened stream - we could use those to write and read an in-memory <code>std::strstream</code> object. Keep the filename interface as a slim wrapper.</p>\n\n<hr>\n\n<p>When we load and save, we check the state of the stream immediately after opening, but we should also check at the end, after closing. Note that we'll require an explicit <code>close()</code> call if we want to be sure that we've fully checked the stream state.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T11:59:37.393", "Id": "237434", "ParentId": "237432", "Score": "6" } }, { "body": "<p>Honestly, .ini is an outdated format that is considered deprecated by Microsoft.</p>\n\n<p>Anyways, you don't actually need to write anything - you can use <code>boost::ptree</code> - property tree which can parse (read and write) ini, json, and xml formats. And it is fairly simple to use. The only reason I don't use it in my code is because I learned of it only recently.</p>\n\n<p>At any rate I happen to also use ini format but I found the whole idea of using section+key to access data to be a poor choise. Instead I simply store all data in <code>map&lt;string,string&gt;</code> in format <code>cfg[\"section/key\"] = \"value\";</code>. It deviates to some degree from classical ini format as one can effectively create subsections (e.g., <code>cfg[\"section/subsection/key\"] = \"value\";</code>) as well as address values directly without sections. This way ini format becomes as powerful as xml and json - and there are major advantages to usage of such formats over classical ini. Why else do you think .ini is deprecated by Microsoft?</p>\n\n<p><strong>Alright, about your code</strong>:\nI don't see why you need to make the <code>IniSection</code> and <code>IniFile</code> to have virtual destructors and virtual functions. Do you really intend to make derived classes that are gonna override these?</p>\n\n<p>Furthermore, it is better to write <code>IniFile() = default;</code> and <code>virtual ~IniFile() = default;</code> instead of <code>IniFile(){};</code> and <code>virtual ~IniFile(){};</code>; usually it is unimportant (as well as in the current case) but for trivial classes it can ruin performance on allocation/deallocation operations - as long as they have such class as a member or derive from it.</p>\n\n<p>It is generally troublesome in C++, but initializing file loading from <code>std::string</code> is not a really good idea. It is fine for development code but generally you need support for non-english text. In C++20 you could simply use <code>std::u8string</code> while in current versions consider a path class as input - like one from <code>boost::filesystem</code> or one from C++17 std filesystem library.</p>\n\n<p>Furthermore, your input/output format shouldn't be <code>int/float</code> but rather <code>long long/double</code> (or even <code>long double</code>) as otherwise you might lose data. And this isn't a class where you need performance - rather compatability is of greater value here.</p>\n\n<p>Since compatability > performance here and likely several classes in multi-threaded environment might use the same ini file class instance, you'd better make it thread-safe via <code>std::mutex</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T19:24:02.663", "Id": "237509", "ParentId": "237432", "Score": "2" } } ]
{ "AcceptedAnswerId": "237434", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T11:25:48.260", "Id": "237432", "Score": "4", "Tags": [ "c++", "parsing" ], "Title": "INI config loader / saver" }
237432
<p>I was recently in a situation where I had to use vanilla js (no es6 and no http libraries, so I came up with this simple wrapper for get calls :</p> <pre><code>var Http = (function() { function Http() { this.xhr = new XMLHttpRequest(); } Http.prototype.get = function(url, onload) { this.xhr.onreadystatechange = function() { if (this.readyState === 4 &amp;&amp; this.status == 200) { onload(this.responseText); } } this.xhr.open("GET", url); this.xhr.send(); } return Http; })() </code></pre> <p>And I would use it like this :</p> <pre><code>var http = new Http(); http.get('endpoint', function() {}); </code></pre> <p>Can you see any potential problems with this approach like memory leaks insecurities etc. and would you and if possible, how, add something to improve it, like ability to handle multiple get() in row from the same http object?</p>
[]
[ { "body": "<p>I am concerned that you have added a layer of false generalization around a very specific, usually one-time use, request object. I would think the class would be better named Request or similar to better clarify what this wrapper represents as currently stands. </p>\n\n<p>If your intent is to truly define a class that provides generalized request functionality ( get, post, put, etc.) then you should think more closely about how (and if) the class holds state for individual request objects. You probably would not store a common request object for every request on ‘this’, but rather would create a new request object for every method call. If you find yourself no longer holding request state in your class, then you then would probably consider whether and instantiable class is really what you want. </p>\n\n<p>On a different front, your current code really does nothing to handle errors in the request. If you are spending the time to build a common request abstraction like this, you should add appropriate error handling. </p>\n\n<p>Finally, if you are in the business of building a new request abstraction, then I would strongly consider building of the much more modern and now widely supported Fetch API. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T03:19:50.803", "Id": "237473", "ParentId": "237437", "Score": "0" } } ]
{ "AcceptedAnswerId": "237473", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T14:05:08.070", "Id": "237437", "Score": "2", "Tags": [ "javascript" ], "Title": "Simple JS XMLHttp wrapper class" }
237437
<p>I have the following table in a PostgreSQL DB (simplified for the question), where I want to select only the rows marked with *:</p> <pre><code>uuid | status | info1 | info2 ------------------------------- 1234 | CONF | - | 10 1234 | START | abc | 10 1234 | FIN | abc | 10 * ------------------------------- 7890 | CONF | - | 20 * ------------------------------- 1111 | CONF | - | 30 1111 | START | zzz | 30 1111 | FIN | zzz | 30 1111 | REM | zzz | 30 ------------------------------- 2222 | CONF | - | 100 2222 | START | ijk | 100 * </code></pre> <p>The separating lines between different values of <strong>uuid</strong> are only for clarity, as I will explain now.</p> <p>The logic for selection is the following: </p> <ul> <li>Partition the table by the column <em>uuid</em> in order to create <em>groups</em> of all the different values.</li> <li>Discard all the groups where there is at least one row with status <strong>REM</strong>.</li> <li>For all the remaining groups, select only the one with the last <em>status</em>. The values of this column define a custom order like this: CONF &lt; START &lt; FIN. The value <em>REM</em> is only used to <em>remove</em> this group of the selection.</li> </ul> <p>I wrote this query that does the job, but I think there might be a better solution, and I have the sensation of abusing the subtable structures:</p> <pre><code>SELECT * FROM ( SELECT MAX(numericphase.phase) OVER (PARTITION BY numericphase.uuid) AS s , * FROM( SELECT CASE WHEN status = 'FIN' THEN 3 WHEN status = 'START' THEN 2 WHEN status = 'CONF' THEN 1 ELSE -1 END AS phase , * FROM ( SELECT * , BOOL_OR(status = 'REM') OVER (PARTITION BY uuid) AS removed FROM mytable ) nonremoved WHERE NOT removed ) numericphase ) lastphase WHERE s = phase AND s &gt; 0 </code></pre> <p>Here I'm doing the following operations (from inner to outer):</p> <ul> <li>First, select all rows where status is not <code>REM</code> (using <code>BOOL_OR</code>).</li> <li>Then, map each status value to a numeric one so they can be sorted.</li> <li>Compute the maximum value of each uuid group (corresponding to the last status following the custom sorting).</li> <li>Finally, select only rows where <code>status = max(status)</code>. This way, only the rows corresponding to the maximum status for each group are selected. </li> </ul> <p>Any possible status that does not correspond to any value in this question is not suitable, so they are mapped to <code>-1</code> and discarded.</p> <p>I think is easier to understand the problem by looking at the table than trying to redact it, so feel free to correct me if something is not clear.</p>
[]
[ { "body": "<p>As I wrote in my edit of the question, I came to the following solution, which I think could be better optimized, but does the job:</p>\n\n<pre><code>SELECT *\nFROM (\n SELECT *\n , MAX(numericphase.phase) OVER (PARTITION BY numericphase.uuid) AS s\n FROM (\n SELECT *\n , CASE\n WHEN status = 'REM' THEN 4\n WHEN status = 'FIN' THEN 3\n WHEN status = 'START' THEN 2\n WHEN status = 'CONF' THEN 1\n ELSE -1\n END AS phase\n FROM mytable\n ) numericphase\n) lastphase\nWHERE phase != 4\nAND s = phase\nAND s &gt; 0\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T09:58:34.003", "Id": "466125", "Score": "0", "body": "Thanks for posting this (and it can now be removed from the question, where it doesn't really fit). You could improve the value of this answer by actually reviewing the code and showing *how* this replacement improves on it. We value self-answers; it does help if they reach the same standards of explanation as other answers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T08:39:39.443", "Id": "237688", "ParentId": "237439", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T14:06:02.903", "Id": "237439", "Score": "4", "Tags": [ "sql", "postgresql" ], "Title": "Select latest phase of objects not marked \"remove\"" }
237439
<p>The following method is used to add objects to a polymorphic <code>ArrayList</code> from a file.</p> <p>It reads lines from the file, and based on a specific line which denotes the category of the product object, it uses the loadFromFile() method of the specific class, before moving onto the next. We are taught to build programs in such a way to allow for future functionality, so I would like to find a way to modify this so if a new child class was created, it would be able to detect that and call the method of that class. instead of the developer needing to add to the switch case every time.</p> <p>Each child class has slightly different attributes hence why this is needed. I am looking for a more sophisticated and future proof method.</p> <pre><code>public void loadFromFile(String fileName) throws FileNotFoundException, IOException, ParseException{ Filename = fileName; String record; FileReader reader; reader = new FileReader(Filename); BufferedReader bin = new BufferedReader(reader); record = new String(); while ((record = bin.readLine())!=null) { switch(bin.readLine()){ case "Electronic": ElectronicProduct eProduct = new ElectronicProduct(); Products.add(eProduct.loadFromFile(eProduct,bin)); break; case "Kitchen": KitchenProduct kProduct = new KitchenProduct(); Products.add(kProduct.loadFromFile(kProduct,bin)); break; case "Food": FoodProduct fProduct = new FoodProduct(); Products.add(fProduct.loadFromFile(fProduct,bin)); break; case "Book": BookProduct bProduct = new BookProduct(); Products.add(bProduct.loadFromFile(bProduct,bin)); break; } bin.close(); bin =null; } } </code></pre> <p><strong>EDIT</strong></p> <p>Below shows entire class, some methods not fully functional as currently upgrading from iteration 1 to iteration 2.</p> <pre><code>package mysupermarket; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JLabel; /** * * @author x */ public class ProductList { private ArrayList&lt;Product&gt;Products; private String Filename; public ProductList(){ Filename = "ProductList.txt"; } public void add(Product src) throws IOException{ Products.add (src); } public void remove(Product src){ Products.remove (src); } public Optional&lt;Product&gt; find(String nameInput){ Optional&lt;Product&gt; aProduct= this.Products.stream() .filter(p-&gt;p.getName().equalsIgnoreCase(nameInput)) .findFirst(); return aProduct; } public void display (javax.swing.JTextArea src){ this.Products.forEach((product) -&gt; { product.display(true, src); }); } public void displayReorders(javax.swing.JTextArea src){ src.setText(null); for(Product product: this.Products){ if(scanForLowStock(product)){ src.append("Product: " + product.getName()+"\n"); src.append("Quantity: " + product.getQuantity()+"\n"); src.append("Min Restock amount: " + (product.getMinimumStockLevel()-product.getQuantity())+"\n"); } } } public void displayImage(JLabel imageArea, String image) throws IOException{ String noImageFound = "no-image-available.jpg"; BufferedImage img = null; try { img = (BufferedImage)ImageIO.read(new File(image)); Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0); imageArea.setIcon(new ImageIcon(actualimage)); } catch (IOException e) { img = (BufferedImage)ImageIO.read(new File(noImageFound)); Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0); imageArea.setIcon(new ImageIcon(actualimage)); System.out.println(e.getMessage()); } } public void loadFromFile(String fileName) throws FileNotFoundException, IOException, ParseException{ Filename = fileName; String record; FileReader reader; reader = new FileReader(Filename); BufferedReader bin = new BufferedReader(reader); record = new String(); while ((record = bin.readLine())!=null) { switch(bin.readLine()){ case "Electronic": ElectronicProduct eProduct = new ElectronicProduct(); Products.add(eProduct.loadFromFile(eProduct,bin)); break; case "Kitchen": KitchenProduct kProduct = new KitchenProduct(); Products.add(kProduct.loadFromFile(kProduct,bin)); break; case "Food": FoodProduct fProduct = new FoodProduct(); Products.add(fProduct.loadFromFile(fProduct,bin)); break; case "Book": BookProduct bProduct = new BookProduct(); Products.add(bProduct.loadFromFile(bProduct,bin)); break; } bin.close(); bin =null; } } public void saveToFile(boolean append, String fileName) throws IOException, ParseException{ Filename = fileName+".txt"; try{//This simply overwrites the file with a blank file FileWriter aWriter = new FileWriter(Filename,false); } catch(IOException ioe){ System.out.println("Failed to wipe file"); } //Now file writing begins FileWriter aWriter = new FileWriter(Filename,true); aWriter.write(System.getProperty("line.separator")); this.Products.forEach((product) -&gt; { try { product.saveToFile(aWriter); } catch (IOException ex) { Logger.getLogger(ProductList.class.getName()).log(Level.SEVERE, null, ex); } catch (ParseException ex) { Logger.getLogger(ProductList.class.getName()).log(Level.SEVERE, null, ex); } }); try{ aWriter.close(); } catch(IOException ioe){ System.out.println("Failed to save product list"); } } public int generateProductID(){ //This is superior to using ArrayList index as it, as that is dynamic and this is static once set. Boolean NewIDFound = false; Boolean inUse = false; int potentialID; for(potentialID=0;NewIDFound==false;potentialID++){ inUse=false; for(Product productToCompare: this.Products){ if (potentialID==productToCompare.getID()){ inUse=true; } } if(inUse!=true){ NewIDFound=true; return potentialID; } } return potentialID; } public int calculateSuggestedQuantity(Product chosenProduct){ int suggestedQuantity = chosenProduct.getMaximumStockLevel()-chosenProduct.getQuantity(); return suggestedQuantity; } public String calculateAdvisedOrderDate(Product chosenProduct,int deliveryTime) throws ParseException{ String date = ""; date = chosenProduct.getExpiryDate(); SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy"); Calendar cal = Calendar.getInstance(); cal.setTime(formatter.parse(date)); cal.add(Calendar.DATE,-deliveryTime); date = formatter.format(cal.getTime()); return date; } public double calculateOrderCost(Product chosenProduct, int orderQuantity){ Double orderCost = 0.0; orderCost= orderQuantity * chosenProduct.getUnitCost(); return orderCost; } public boolean checkIfNameInUse(String input){ boolean alreadyInStock =false; for(Product product : this.Products){ if(input.equals(product.getName())){ alreadyInStock =true; break; } } return alreadyInStock; } public void updateLastOrderDate(Product input){ String date = new SimpleDateFormat("dd/MM/yy").format(new Date()); input.setDateOfLastOrderPlacement(date); } public int setStockDefaultValue(String userInput){ int output = 0; if(!userInput.equalsIgnoreCase("")){ output=Integer.valueOf(userInput); } return output; } public boolean confirmStockLevelsSet(Product chosenProduct){ boolean reOrderPossible =true; if(chosenProduct.getMaximumStockLevel()==0||chosenProduct.getMinimumStockLevel()==0){ reOrderPossible=false; } return reOrderPossible; } public boolean scanForLowStock(Product chosenProduct){ boolean warningRequired = false; if(chosenProduct.getQuantity()&lt;chosenProduct.getMinimumStockLevel()){ warningRequired=true; } return warningRequired; } public String getFilename() { return Filename; } public void setFilename(String Filename) { this.Filename = Filename; } public boolean checkIfFileExists(String fileName){ String filename = fileName; File tempFile = new File(filename); boolean exists = tempFile.exists(); return exists; } } </code></pre> <p><strong>EDIT 2</strong></p> <p>An extract of a child class is as follows, all child classes are similar with one or two unique attributes</p> <pre><code>public KitchenProduct loadFromFile(KitchenProduct kProduct, BufferedReader bin) throws IOException, ParseException{ super.loadFromFile(kProduct,bin); kProduct.setFragile(super.convertTextToBoolean(bin.readLine())); return kProduct; } </code></pre> <p>below is an extract of the parent class</p> <pre><code>public Product loadFromFile(Product aProduct, BufferedReader bin) throws IOException, ParseException{ aProduct.edit( /*int ID*/Integer.valueOf(bin.readLine()), /*String name*/bin.readLine(), /*String Supplier*/bin.readLine(), /*String deliverycomapyn*/bin.readLine(), /*String caTEGORY*/bin.readLine(), /*double price*/Double.valueOf(bin.readLine()), /*double unit cosre*/Double.valueOf(bin.readLine()), /*int quantity*/Integer.valueOf(bin.readLine()), /*int wiehgt*/Integer.valueOf(bin.readLine()), /*int shelf life*/Integer.valueOf(bin.readLine()), /*string date of last order*/bin.readLine(), /*string image name*/bin.readLine(), /*String min stock*/Integer.valueOf(bin.readLine()), /*string max stock */Integer.valueOf(bin.readLine())); return aProduct; } </code></pre> <p>product list is as follows, different child classes have different amount of attributes which is reflected in file and detected when reading. </p> <pre><code>6 Potatoes Farm Wholesale UPS veg 5.0 0.5 100 50 14 18/01/20 food 30 300 1 spatula amazon UPS Farm 2.0 0.3 10 1 4 20/01/20 kitchen 4 15 true </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T14:45:36.860", "Id": "465571", "Score": "4", "body": "It would be better if the whole class was provided." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T16:21:53.310", "Id": "465592", "Score": "1", "body": "Thank you for your suggestion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T16:27:40.543", "Id": "465593", "Score": "0", "body": "It would be useful to have the `Product` class, and at least 1 derived product class. (Is `eProduct.loadFromFile` a virtual method or a static method? We can’t tell yet.). Also, a sample `ProductList.txt` file. After pasting your properly formatted code from your editor into the post, select the entire code and press Ctrl-K or Cmd-K to properly format it here, with the correct indentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T16:33:36.453", "Id": "465595", "Score": "0", "body": "please check edit" } ]
[ { "body": "<p>I think there are two choices with little or no in-betweens:</p>\n\n<ol>\n<li>formally specify the products and use a parser</li>\n<li>keep the current behavior, which means determining the product and switching.</li>\n</ol>\n\n<p>so in the end, you have to either take a big step and create a formal description and a parser (parser generation is a university course, mind you). Or you'll have to perform some smart but elaborate branching.</p>\n\n<hr>\n\n<p>A possible enhancement is to first load into memory and then switch. This would decouple the file handling from the parsing of the products. That way you can also test the parsing of the products without relying on files (!).</p>\n\n<hr>\n\n<p>Another possible enhancement is to use factory methods / classes. In that case a factory is used to aggregate the various data of a product performing validation on the input. Then it can be used to create the actual (<code>Potatoes</code>) object after making sure that all necessary components are present and not in conflict.</p>\n\n<p>This could also make it easier to use one factory for multiple products, so you can group together the handling of similar products. Of course, you may need to create a product -> factory mapping - but that should not be hard. In Java you can also use reflection to then instantiate the right factory.</p>\n\n<hr>\n\n<p>Let me end by: never trust your input! I see too little input checking and no clear strategy (such as throwing a checked exception) in case the input is invalid.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T16:52:43.223", "Id": "237445", "ParentId": "237441", "Score": "3" } }, { "body": "<h1>First, a Code Review</h1>\n\n<h2>Anti-pattern</h2>\n\n<p>Please don't do this:</p>\n\n<pre><code>record = new String();\n</code></pre>\n\n<p>This is (barring compiler heroics), creating a brand new empty string literal, when a perfectly good interned string literal is available:</p>\n\n<pre><code>record = \"\";\n</code></pre>\n\n<p>Using this interned literal <code>\"\"</code> prevents the creation of a number of identical tiny objects, and will improve the performance of the JVM. This is the same reason for preferring <code>Integer.valueOf(some_string)</code> over <code>new Integer(some_string)</code>.</p>\n\n<h2>Primitives -vs- Objects</h2>\n\n<p>In Java, a primitive value is a light-weight - uh - value thing. It can stored in a register, or in a couple of bytes of memory. It has no \"identity\"; there is no difference between <code>5678</code> and <code>5678</code> ... they are simply equal values. In contrast, an <code>Object</code> is a heavy weight thing. It is always stored in the heap, requires dozens of bytes of memory, access via indirection, and has identity. Identity means <code>new Integer(5678)</code> and <code>new Integer(5678)</code> are <strong>different</strong> objects which contain the same numerical value; they exist in different areas of memory.</p>\n\n<p><code>boolean</code> is a value; <code>Boolean</code> is an object which holds a <code>boolean</code> value.</p>\n\n<pre><code>Boolean inUse = false;\n</code></pre>\n\n<p>Here, you are declaring a <code>Boolean</code> object, and attempting to storing a <code>boolean</code> value in that variable. The compiler autoboxes the <code>false</code> value into the singleton <code>Boolean.FALSE</code> for you, and stores a reference to that object in <code>inUse</code>. Additionally, it may increases a reference count of <code>Boolean.FALSE</code>, in order to properly manage the object heap, find unreferenced objects, and perform garbage collection.</p>\n\n<p>If instead, you used:</p>\n\n<pre><code>boolean inUse = false;\n</code></pre>\n\n<p>the compiler would move a false value into a temporary register.</p>\n\n<p>Compare the amount of behind the scenes work described in those paragraphs. Your code will run much faster when you use values instead of objects.</p>\n\n<p>Reading further into your code, I see lines like these:</p>\n\n<pre><code> /*int ID*/Integer.valueOf(bin.readLine())\n /*double price*/Double.valueOf(bin.readLine()),\n</code></pre>\n\n<p>The comments suggested these values are being passed to an <code>int</code> and a <code>double</code> parameter. However <code>Integer.valueOf(...)</code> returns an <code>Integer</code> object and <code>Double.valueOf(...)</code> returns a <code>Double</code> object. This means you've again asked the JVM to do more work than necessary. After reading the line, <code>Integer.valueOf(...)</code> converts the string into a <code>int</code>. (It internally uses <code>int</code> in the conversion process for efficiency.) After the conversion is complete, it boxes the <code>int</code> value into an <code>Integer</code> (allocated on the heap, if it cannot intern the value), and returns this object. Then, since the returned value is being passed to an <code>int</code> parameter, the <code>Integer</code> object is unboxed back into an <code>int</code>. </p>\n\n<p>If instead you used:</p>\n\n<pre><code> /*int ID*/Integer.parseInt(bin.readLine())\n /*double price*/Double.parseDouble(bin.readLine()),\n</code></pre>\n\n<p>these function would return an <code>int</code> and a <code>double</code> respectively. No boxing and subsequent unboxing is required. Again, less work means faster, more efficient code.</p>\n\n<h2>AutoCloseable</h2>\n\n<p>Most reader and writer objects are <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/AutoCloseable.html\" rel=\"noreferrer\"><code>AutoCloseable</code></a>, which means they can be used with Java's try-with-resources statement. This ensures the operating system resources are properly closed at the end of normal and exceptional execution paths. It also means you don't have to call <code>bin.close()</code>, if you write your code correctly.</p>\n\n<p>Instead of:</p>\n\n<pre><code>FileReader reader;\n\nreader = new FileReader(Filename);\nBufferedReader bin = new BufferedReader(reader);\n\n/* ... read code omitted for brevity ... */\n\nbin.close();\nbin =null;\n</code></pre>\n\n<p>You should write:</p>\n\n<pre><code>try (FileReader reader = new FileReader(Filename);\n BufferedReader bin = new BufferedReader(reader))\n {\n /* ... read code omitted for brevity ... */\n }\n</code></pre>\n\n<p>Notice the absence of <code>bin.close()</code>. Resources declared and opened inside <code>try ( ... )</code> are closed for you at the end of the try block. If an exception is thrown inside the try, the resources are still properly closed for you; something which your code currently does not handle.</p>\n\n<h2>Coding Conventions</h2>\n\n<p>Variable and member names should not start with an upper case letter; class names start with upper case letters. In <code>reader = new FileReader(Filename);</code>, it looks like a <code>Filename</code> is a class.</p>\n\n<p>Use spaces liberally, including after commas, around operators, after <code>if</code>, <code>for</code>, <code>while</code>, and before <code>{</code>. Compare:</p>\n\n<pre><code>if(chosenProduct.getMaximumStockLevel()==0||chosenProduct.getMinimumStockLevel()==0){\n reOrderPossible=false; \n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if (chosenProduct.getMaximumStockLevel() == 0 || chosenProduct.getMinimumStockLevel() == 0) {\n reOrderPossible = false; \n}\n</code></pre>\n\n<p>Notice the double space around the <code>||</code> which helps suggest the order of precedence of the operations.</p>\n\n<h2>@Override</h2>\n\n<p>You have:</p>\n\n<pre><code>class Product {\n public Product loadFromFile(Product aProduct, BufferedReader bin) throws IOException, ParseException { ... }\n ...\n}\n</code></pre>\n\n<p>and </p>\n\n<pre><code>class KitchenProduct : public Product {\n public Product loadFromFile(KitchenProduct kProduct, BufferedReader bin) throws IOException, ParseException { ... }\n ...\n}\n</code></pre>\n\n<p>First thing to note is neither of these is a <code>static</code> method. This means they must be called with a receiver, the <code>this</code> object.</p>\n\n<p>In your code, you call:</p>\n\n<pre><code> KitchenProduct kProduct = new KitchenProduct(); \n ...( kProduct.loadFromFile(kProduct, bin) ); \n</code></pre>\n\n<p>So when <code>kProduct.loadFromFile(...)</code> is invoked, <code>this</code> will be the value of <code>kProduct</code> from the caller, and the first argument will be the value of <code>kProduct</code> from the caller.</p>\n\n<p>In <code>KitchenProduct::loadFromFile(KitchenProduct kProduct, ...)</code>, you call <code>kProduct.setFragile(...)</code>. You could have just as easily written <code>this.setFragile(...)</code> because <code>this</code> has the same value as the first argument to the function. Or less verbosely, you could simply write <code>setFragile(...)</code> because <code>this.</code> is implicit.</p>\n\n<p>Improved code (step 1):</p>\n\n<pre><code>public KitchenProduct loadFromFile(KitchenProduct kProduct, BufferedReader bin) throws IOException, ParseException{\n super.loadFromFile(this, bin);\n\n setFragile(super.convertTextToBoolean(bin.readLine()));\n\n return this;\n}\n</code></pre>\n\n<p>Similarly, <code>Produce::loadFromFile(Product aProduct, ...)</code> is being called with the receiver (<code>this</code>) the same as the first argument (<code>aProduct</code>), so it can be rewritten:</p>\n\n<pre><code>public Product loadFromFile(Product aProduct, BufferedReader bin) throws IOException, ParseException{\n\n edit(\n /* ... omitted for brevity ... */\n );\n\n return this;\n}\n</code></pre>\n\n<p>Note that neither <code>Product::loadFromFile(...)</code> nor <code>KitchenProduct::loadFromFile(...)</code> are using their first argument anymore. These can be removed, leaving just the <code>BufferedReader bin</code> argument. At this point, the function arguments become identical, which allows us to use the annotation <code>@Override</code>.</p>\n\n<pre><code>class Product {\n\n public Product loadFromFile(BufferedReader bin) throws IOException, ParseException {\n edit( /* ... omitted for brevity ... */ );\n return this;\n }\n\n ...\n}\n\nclass KitchenProduct {\n\n @Override\n public KitchenProduct loadFromFile(BufferedReader bin) throws IOException, ParseException {\n super.loadFromFile(bin)\n setFragile(convertTextToBoolean(bin.readLine()));\n return this;\n }\n\n ...\n}\n\n\n...\n\n case \"Kitchen\":\n KitchenProduct kProduct = new KitchenProduct(); \n Products.add(kProduct.loadFromFile(bin)); \n break;\n</code></pre>\n\n<hr>\n\n<h1>Improving the Load</h1>\n\n<p>We're now ready to start improving the dynamic loading code.</p>\n\n<p>First of all, all <code>Product</code> classes now <code>@Override</code> a common base class <code>loadFromFile</code> method. This means we can call the method on any derived class from the base class, without knowing what kind of base class we have.</p>\n\n<p>So this code:</p>\n\n<pre><code>switch(bin.readLine()){\n\n case \"Electronic\":\n ElectronicProduct eProduct = new ElectronicProduct(); \n Products.add(eProduct.loadFromFile(eProduct,bin)); \n break;\n\n case \"Kitchen\":\n KitchenProduct kProduct = new KitchenProduct(); \n Products.add(kProduct.loadFromFile(kProduct,bin)); \n break;\n\n case \"Food\":\n FoodProduct fProduct = new FoodProduct(); \n Products.add(fProduct.loadFromFile(fProduct,bin)); \n break;\n\n case \"Book\":\n BookProduct bProduct = new BookProduct(); \n Products.add(bProduct.loadFromFile(bProduct,bin)); \n break;\n}\n</code></pre>\n\n<p>can now be written as:</p>\n\n<pre><code>Product product = null;\n\nswitch (bin.readLine()) {\n case \"Electronic\":\n product = new ElectronicProduct(); \n break;\n\n case \"Kitchen\":\n product = new KitchenProduct(); \n break;\n\n case \"Food\":\n product = new FoodProduct(); \n break;\n\n case \"Book\":\n product = new BookProduct(); \n break;\n}\n\nif (product != null) {\n Products.add(product.loadFromFile(bin));\n}\n</code></pre>\n\n<p>As a further improvement, I'd make all of the <code>loadFromFile(...)</code> methods return <code>void</code>, and write:</p>\n\n<pre><code>if (product != null) {\n product.loadFromFile(bin);\n Products.add(product);\n}\n</code></pre>\n\n<p>Now, you can create a factory method which turns a string into the correct product class, and write the code as:</p>\n\n<pre><code>String product_name = bin.readLine();\nProduct product = create_product(product_name);\nproduct.loadFromFile(bin);\nProducts.add(product);\n</code></pre>\n\n<p>And your factory method might look like:</p>\n\n<pre><code>private static Product create_product(String product_name) {\n switch (product_name) {\n case \"Electronic\": return new ElectronicProduct();\n case \"Kitchen\": return new KitchenProduct();\n case \"Food\": return new FoodProduct();\n case \"Book\": return new BookProduct();\n default: throw new UnknownProductException(product_name);\n }\n}\n</code></pre>\n\n<h1>Dynamic Construction</h1>\n\n<p>It has been a long road, but to finish, this is one way to implement dynamic construction (untested):</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\nprivate static Product create_product(String product_name) {\n try {\n Class&lt;?&gt; product_class = Class.forName(product_name + \"Product\");\n return (Product) product_class.getDeclaredConstructor().newInstance();\n } except (ReflectiveOperationException e) {\n throw new UnknownProductException(product_name);\n }\n}\n</code></pre>\n\n<p>You will need <code>\"your.package.\" + product_name + \"Product\"</code> if your derived <code>Product</code> classes exist in a package.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T15:40:24.193", "Id": "465727", "Score": "0", "body": "Thank you so much for your detailed response to this. I am currently working towards a tight deadline so once I have completed vital tasks I will read through this in depth and apply to my code (and replace this comment)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T19:21:43.940", "Id": "237450", "ParentId": "237441", "Score": "13" } }, { "body": "<p><strong>Is inheritance really the answer?</strong></p>\n\n<p>I think it's been covered that you <em>could</em> dynamically build your product instances, but it's not really clear to me why you'd need to. The object model feels a bit wrong to me. From what I can see you're reading all of the objects in, then storing them in an <code>ArrayList&lt;Product&gt;</code>. There doesn't appear to be a lot of processing (although that could be in the code you've not shared), so I can't help but wonder if you're really getting much more from having these classes than you would get with a simple map of field types to values. So, you'd have a <code>ProductDefinition</code> something like:</p>\n\n<pre><code>ProductDefinition\n ProductType productType\n OrderedList&lt;Field&gt; fields\n\nFieldDefinition\n String fieldName // Name used to retrieve field\n FieldType fieldType // String/Boolean/Integer etc\n</code></pre>\n\n<p>You could then simply maintain a <code>Map</code> of <code>ProductIdentificationStrings</code>, so given a \"Kitchen\" product identifier, the Matching product definition is used to determine which fields to read... these would then be stored in a Product which has it's own map of field/values... This lends itself quite readily to a table driven approach whereby adding support for a new type of product is really just about creating the new product definition entries...</p>\n\n<p><strong>Other Stuff</strong></p>\n\n<ul>\n<li>Seperation of concerns seems a bit skewed. Your <code>ProductList</code> knows about swing and also about reading/writing products out to files. This seems like too much responsibility. You really want to try to separate the front end from the back a bit more.</li>\n<li><p>Quite a lot of your functions define variables that really aren't needed. They don't add extra clarity. If a function can be one line, simply make it one line... Instead of </p>\n\n<blockquote>\n<pre><code>public double calculateOrderCost(Product chosenProduct, int orderQuantity){\n Double orderCost = 0.0;\n orderCost= orderQuantity * chosenProduct.getUnitCost();\n return orderCost;\n}\n</code></pre>\n</blockquote>\n\n<p>Just do:</p>\n\n<pre><code>public double calculateOrderCost(Product chosenProduct, int orderQuantity){\n return orderQuantity * chosenProduct.getUnitCost();\n}\n</code></pre>\n\n<p>Similarly, consider simplifying your <code>if</code>s, rather than <code>if (x || y) return true;return false;</code> just do <code>return x || y</code>. The function name <em>should</em> indicate what the returned value represents.</p></li>\n<li><p>Consider making your product file more self describing. Files like this can be a pain. If you're writing them out in text anyway, then using something like YAML can make it easier to understand the file if things go wrong and you need to fix it in a text editor. In the example you've posted (which may have been redacted), it looks like the product type is actually the 2nd/3rd from last field depending on the product type... making it the first line would seem more natural.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T22:07:22.447", "Id": "237459", "ParentId": "237441", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T14:34:58.020", "Id": "237441", "Score": "6", "Tags": [ "java", "array", "polymorphism" ], "Title": "Supermarket Product Inventory Management with Polymorphic Product Types" }
237441
<p>I'm trying to create a sorted array based on the below input data:</p> <p><strong>Input:</strong></p> <p><code>[{&quot;title&quot;: &quot;100_baz&quot;}, {&quot;title&quot;: &quot;01_foo&quot;}, {&quot;title&quot;: &quot;05_bar&quot;}]</code></p> <pre><code>function indexSort (input) { let output = []; input.forEach(value =&gt; { if (value.title &amp;&amp; value.title.indexOf('_') !== -1) { let targetIndex = parseInt (value.title.split('_')[0]); let title = value.title.substring(value.title.indexOf('_') + 1, value.title.length); // extract the string next to '_' output[targetIndex] = title; } }) console.log(output) } </code></pre> <p><strong>Desired Output:</strong></p> <p><a href="https://i.stack.imgur.com/WAAOz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WAAOz.png" alt="enter image description here" /></a></p> <p>I'm able to get the desired output using the above code snippet, however, I'm looking for a better way to achieve this in terms of good practice, or a concise and clear method in ES5 or ES6.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T19:29:57.087", "Id": "465614", "Score": "1", "body": "There is a slight issue with your desired output. It looks like you want a dictionary because you have key value pairs, but you have it surrounded with brackets like an array. Can you clarify the structure of your desired output? Are you looking for an array or a dictionary?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T12:59:27.987", "Id": "465707", "Score": "0", "body": "@SamG Strictly looking for an array in order to retain the order/index. I have updated the desired output now." } ]
[ { "body": "<p>Your code is pretty sound. I can't see any improvements that specifically use ES5/ES6 tricks - the spread operator for example will set all of the other keys to <code>undefined</code> instead of leaving them empty, which I think is undesired. Further loops would iterate over those <code>undefined</code> keys as well.</p>\n\n<p>That said, here are some improvements:</p>\n\n<ul>\n<li>Use <code>reduce</code> to remove the need for a new array and replace the <code>forEach</code></li>\n<li>Store the return value from <code>split</code> and use that to replace the <code>indexOf</code> (if the delimiter doesn't exist <code>split</code> returns an array of length 1) and <code>substring</code> calls</li>\n<li>At the moment, the <code>indexSort</code> function isn't as <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single-purpose</a> as it could be. It has to know that the <code>input</code> array contains a <code>title</code> key. This can be moved outside to where the function is called making <code>indexSort</code> reusable</li>\n<li>The name <code>indexSort</code> is a little misleading - I assumed it was going to sort a preexisting array. Perhaps use something like <code>arrayFromTitles</code> instead?</li>\n</ul>\n\n<p>Quick snippet showing these changes:</p>\n\n<pre><code>function indexSort (input) {\n return input.reduce((accumulator, current) =&gt; {\n let split = current.split('_');\n if ( split.length &gt; 1 ) {\n accumulator[parseInt(split[0])] = split[1];\n }\n return accumulator;\n }, []);\n}\n\nlet titles = [{\"title\": \"100_baz\"}, {\"title\": \"01_foo\"}, {\"title\": \"05_bar\"}];\nindexSort(titles.map(x =&gt; x.title));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:36:53.923", "Id": "237517", "ParentId": "237446", "Score": "2" } }, { "body": "<p>Updating my comments on current implementation, Thanks @Mast for pointing out.</p>\n\n<ol>\n<li>You have used <code>let</code> for <code>output</code>, <code>targetIndex</code> and <code>title</code>. None of\nthem never updated. <code>const</code> is better suitable here. </li>\n<li>Usage of <code>value.title.indexOf('_')</code> is repeated. you can use variable.</li>\n<li>You can avoid <code>substring</code> usage because you are already did <code>value.title.split('_')</code> and you can use index 1 value from result\n array.</li>\n</ol>\n\n<p>Apart from these minor points, <code>code looks good to me</code>.</p>\n\n<p>As you asked, Here is alternative ES6 implementation.</p>\n\n<ol>\n<li>Use arrow function</li>\n<li>With <code>reduce</code> and using destructure in input function arguments and have the default value for <code>title</code>.</li>\n<li>In reduce function use destucture to get the values from <code>split</code> result.</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>const data = [{\"title\": \"100_baz\"}, {\"title\": \"01_foo\"}, {\"title\": \"05_bar\"}];\n\nconst indexSort = data =&gt; data.reduce((acc, {title = ''}) =&gt; {\n const [num, value] = title.split('_');\n acc[Number(num)] = value;\n return acc;\n}, []);\n\nconsole.log(indexSort(data));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T21:14:43.557", "Id": "465954", "Score": "0", "body": "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." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T04:32:43.263", "Id": "465982", "Score": "1", "body": "@Mast, Thanks for suggestion. I just updated my thoughts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T23:25:31.007", "Id": "466091", "Score": "0", "body": "It’s a matter of opinion, but I prefer only using `const` when the intention of the variable is to never change. In this case, it is a coincidence (caused by the chosen implementation) that the variable never got updated, so I would use `let` instead." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T17:52:09.933", "Id": "237571", "ParentId": "237446", "Score": "3" } } ]
{ "AcceptedAnswerId": "237571", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T17:15:50.007", "Id": "237446", "Score": "2", "Tags": [ "javascript", "array" ], "Title": "JavaScript: Better way to sort an array by setting custom index" }
237446
<p>I'm new to programming; I started about a week ago and started learning python. Currently, I only know some basic arithmetic operations in addition to some basic knowledge about lists, dictionaries, strings, etc.</p> <p>I tried testing what I learnt so far. I made this prime number checker, which works except when the numbers are really big. Please rate it and suggest improvements that I can understand at my current level.</p> <p>Here is the code:</p> <pre class="lang-py prettyprint-override"><code>''' pr means the number we'll be working on dl is a dictionary that contains our the dividend and the reaminder x is the dividend e is a list that contains all remainders and what the program does as you might have guessed already it makes a list of all remainders of the division of our number by every integer before it and checks for the number 0 if it finds it then the number is not prime and if it doesn't then it's prime ''' pr = int(input("Enter your number ")) print("\n") dl = {} x = pr - 1 while x &lt; pr and x &gt; 1 : r = pr % x dl[x]= r x -= 1 e = list(dl.values()) if any( z == 0 for z in e ) : print(pr," is not a prime number") else : print(pr," is a prime number") print("\n") input("Press Enter to close the program") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T20:03:48.913", "Id": "465775", "Score": "8", "body": "Can you say why you wrote `x < pr and x > 1`? Under what circumstances can the left side of the `and` be false? If it can, demonstrate such a test case. If it cannot, then why say it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T10:11:24.250", "Id": "465854", "Score": "1", "body": "oh i see i did it because initially i tried working with a for loop but it wasn't working so when i switched to the while loop i didn't change it, thank you for notifying me" } ]
[ { "body": "<p>First, thank you for including a docstring that explained how the script works; it saved me a good couple of minutes in puzzling it out. :) It turned out to be a lot simpler than I initially thought it was, which suggests an easy path to optimizing it for space.</p>\n\n<p>The error that your program hits with large numbers is a <code>MemoryError</code>, which is a result of the dictionary that you build which includes every number prior to your number (or, potentially, the roughly-equally-massive list that you then unnecessarily convert that dictionary into).</p>\n\n<p>Since you're only interested in one piece of data (is any of these numbers zero?), and since the computation of the numbers doesn't depend on any of the numbers before them, there's no need to store them all in memory. As soon as one of the values of <code>r</code> (aka <code>pr % x</code>; there's not really any reason to name or store it since you only look at it once) is 0, you know that the number isn't prime; that's all there is to it.</p>\n\n<p>The core of your program stays the same. Just skip the part where you build the giant dictionary and the giant list, and have the program finish immediately once it knows what the answer is:</p>\n\n<pre><code>pr = int(input(\"Enter your number: \"))\n\nx = pr - 1\nwhile x &gt; 1 :\n if pr % x == 0:\n print(pr, \"is not a prime number\")\n exit()\n x -= 1\nprint(pr, \"is a prime number\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T22:40:46.590", "Id": "465636", "Score": "14", "body": "`exit()` should be avoided in Python programs, as it immediately exits the Python interpreter, which makes writing Unit Test code not possible in pure Python. Instead, use a `break` statement and a `while : ... else:` construct." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T22:22:45.697", "Id": "237461", "ParentId": "237455", "Score": "13" } }, { "body": "<p>I'd have to rate your program a \"D-Minus\".</p>\n\n<ul>\n<li>incorrectly labels 1, 0, and all negative numbers as prime!</li>\n<li>runs in <span class=\"math-container\">\\$O(n)\\$</span> time, instead of <span class=\"math-container\">\\$O(\\sqrt n)\\$</span> time</li>\n<li>runs in <span class=\"math-container\">\\$O(n)\\$</span> space, instead of <span class=\"math-container\">\\$O(1)\\$</span> space</li>\n</ul>\n\n<p>Other deficiencies:</p>\n\n<ul>\n<li><code>'''docstrings'''</code> should be used for describing \"how\" to use the module/class/method; comments should be used to explain how the code works</li>\n<li>variable names are cryptic; too short to be descriptive</li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8 guidelines</a> are not consistently followed. Operators like <code>=</code> should have 1 space on each side. No space should be used after <code>(</code>, or before <code>)</code>, as well as not before <code>:</code></li>\n<li>a dictionary is being used to store a list of values; a simple list would suffice</li>\n<li><code>dl.values()</code> is an iterable; there is no need to convert it into a <code>list</code> in order to use in the <code>for z in ...</code></li>\n</ul>\n\n<p>As suggested by <a href=\"https://codereview.stackexchange.com/users/175890/aaaaa-says-reinstate-monica\">aaaaa says reinstate Monica</a>,\nplease work on your solution and then submit it as a new question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T09:35:22.117", "Id": "465849", "Score": "5", "body": "a good indication that variables names are cryptic: the OP explained them in the beginning..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T23:06:50.137", "Id": "237462", "ParentId": "237455", "Score": "31" } }, { "body": "<p>Code showing some of the points AJNeufeld mentioned.</p>\n\n<p>Further points:</p>\n\n<ul>\n<li>You can check most false states in one condition</li>\n<li>Because of this, you only need to check factors from a minimum of 3</li>\n<li>Working through the possible factors in ascending order will produce a quicker result. E.g. 1200 is not divisible by 1199, but is by 3. </li>\n<li>You only need to check factors up to the square root of the passed number, since any numbers after that will start repeating previously checked calculations. E.g. 3 * 400 == 400 * 3</li>\n<li>Any even factor will produce an even number, so we can skip checking even factors in the for loop using a step size of 2</li>\n</ul>\n\n<pre><code>import math\n\nnum = int(input(\"Enter your number: \"))\n\n# check all negative numbers, 0, 1 and even numbers\nif num &lt;= 1 or (num % 2 == 0 and num &gt; 2):\n print(num, \"is not a prime number\")\nelse:\n # calculate square root as maximum factor to check\n # any numbers past this point will start repeating\n # previously checked values since a * b == b * a\n sqrt = math.sqrt(num)\n # start from 3, checking odd numbers only\n # even factors will result in an even num\n # + 1 on end ensures loop runs for x == 3\n for x in range(3, int(math.floor(sqrt)) + 1, 2):\n if num % x == 0:\n print(num, \"is not a prime number\")\n break\n # no factor found, loop falls through\n else:\n print(num, \"is a prime number\")\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T16:03:54.327", "Id": "465732", "Score": "4", "body": "Prints the wrong result when num = 2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T16:17:05.740", "Id": "465735", "Score": "0", "body": "Welcome to Code Review! I've removed the salutation from this post, since this site is trying to focus only on the contents of a given post. Upon reading around, you might notice that little to no other posts have salutations in them :) In addition to that I reformulated the way you refer to AJNeufeld's answer, (notably removing the word \"example\"), mostly to make it \"scan\" easier without the salutation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T20:36:01.723", "Id": "465783", "Score": "1", "body": "Your code also shows an optimization with sqrt; it would improve your answer to [edit] and call out this optimization since no one else has suggested it and it will substantially reduce the search space." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T21:00:56.793", "Id": "465784", "Score": "0", "body": "Thanks all for the comments! Thanks gnasher729 for spotting the bug - it's fixed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T21:13:49.297", "Id": "465785", "Score": "3", "body": "Python 3.8 include [`math.isqrt(num)`](https://docs.python.org/3/library/math.html?highlight=isqrt#math.isqrt) which avoids the need for things like `int(math.floor(math.sqrt(num)))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T21:24:04.020", "Id": "465786", "Score": "0", "body": "You should use a step-size of two in your loop, since you've already tested even numbers with the first if statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T21:25:40.217", "Id": "465787", "Score": "0", "body": "Your `for ... if ... break` could easily be turned into an `if any` statement, with the same short-circuit behaviour. Eg, something like: `if any(num % x == 0 for x in range(3, math.isqrt(num) + 1), 2):` `print(\"Not prime\")` `else:` `print(\"Prime\")`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T21:29:55.257", "Id": "465788", "Score": "0", "body": "Nice optimisations AJNeufeld! I'll make sure to remember those for future :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:33:55.090", "Id": "465947", "Score": "0", "body": "FYI `int(math.sqrt(num))` and `int(math.floor(math.sqrt(num)))` are both inaccurate. For example, the floor of the square root of 81129638414606699710187514626049 is 9007199254740993, but these formulas return 1 less than that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T21:23:34.953", "Id": "465960", "Score": "0", "body": "@pts Yes, that's true. You would get more consistently accurate results by importing the `Decimal` class from the `decimal` module and using `int(math.floor(Decimal(num).sqrt()))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T22:00:46.223", "Id": "465962", "Score": "0", "body": "@oobug: Actually, `int(math.floor(Decimal(num).sqrt()))` also returns 1 less. To get the correct result, drop the `math.floor`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T22:08:10.830", "Id": "465963", "Score": "0", "body": "@oobug: `int(Decimal(num).sqrt())` is also incorrect, e.g. it's 1 less than the correct result 10000000000000000000000000001 for num 100000000000000000000000000020000000000000000000000000001." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T22:14:33.727", "Id": "465964", "Score": "0", "body": "This is how to get square root without loss of precision: `import decimal; c = decimal.Context(); c.prec = len(str(num)); print(int(c.sqrt(num)))`. Anything using `math.sqrt` or `math.floor` or `Decimal` without `Context` is inaccurate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T07:27:42.820", "Id": "465994", "Score": "2", "body": "Remember comments are not a replacement for good variable names. Naming things like \"num\", \"sqrt\", \"x\" doesn't help much. Consider changing them to variable names that accurately represent what they are; eg \"num\" to \"prime_candidate\", \"sqrt\" to \"maximum_factor\", \"x\" to \"i\". Remove gratuitous comments like \"# no factor found, loop falls through\" - good code comments itself, when that fails rely on comments. If the naming and logic is improved then it becomes obvious that when all factors are checked, the loop will end and the number must be a prime." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T15:31:01.273", "Id": "237497", "ParentId": "237455", "Score": "16" } }, { "body": "<p>In addition, I'd recommend using a for loop instead of a while loop here just so that it's more clear what's going on. And I'd put the entire for loop in a function so you could do something like</p>\n\n<pre><code>if isPrime(pr):\n print(pr, \" is a prime number.\")\nelse:\n print(pr, \" is not a prime number.\")\n</code></pre>\n\n<p>This will also make it so you can use return() instead of exit() as specified in the other answer:</p>\n\n<pre><code>def isPrime(pr):\n for i in range(2, pr):\n if pr % i == 0:\n return(True)\n return(False)\n</code></pre>\n\n<p>Also as already stated name your variables properly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:45:07.617", "Id": "465757", "Score": "7", "body": "`return` is not a function, don't use parentheses on it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T15:49:44.400", "Id": "237499", "ParentId": "237455", "Score": "4" } }, { "body": "<blockquote>\n <p><code>pr</code> means the number we'll be working on<br>\n <code>dl</code> is a dictionary that contains our the dividend and the reaminder<br>\n <code>x</code> is the dividend<br>\n <code>e</code> is a list that contains all remainders</p>\n</blockquote>\n\n<p>These variable names are very short and don't have a lot of meaning.\nYou can save a lot of comments by naming your variables: <code>number_to_check</code>, <code>remainders</code>, <code>dividend</code>, <code>remainder_list</code>.</p>\n\n<p>Not all variable names need to be that explicit, but if you feel the need to explain them in a comment, there is probably room for improvement.</p>\n\n<blockquote>\n <p>and what the program does as you might have guessed already\n it makes a list of all remainders of the division of our number by every integer before it\n and checks for the number 0\n if it finds it then the number is not prime\n and if it doesn't then it's prime</p>\n</blockquote>\n\n<p>This part of the comment you can also make redundant by using method names:</p>\n\n<pre><code>def isPrime(our_number):\n remainders = make_list_of_all_remainders(our_number)\n if any( item == 0 for item in remainders ):\n return False\n else:\n return True\n</code></pre>\n\n<p>If you read the method names, it basically narrates the same as your description of the algorithm does.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T23:01:11.667", "Id": "237520", "ParentId": "237455", "Score": "6" } }, { "body": "<p><strong>Input validation</strong>: the term \"prime\" is often used to refer to integers greater than 1. You might want to check whether it qualifies. It's up to you whether to reject negative integers outright or multiply them by negative 1.</p>\n\n<p><strong>Reverse order doesn't make sense</strong>: you're starting from the largest numbers, but if something isn't prime, then you'll see that earlier if you start will small numbers. For instance, for 26, you'll have to go down 12 numbers if you're starting at 25 to get to 13, but you'll immediately get to 2 if you're starting with small numbers.</p>\n\n<p><strong>Smaller range</strong>: you only have to check numbers less than the square root.</p>\n\n<p><strong>Reduced possible factors</strong>: Once you check whether a prime number is a factor, you don't have to check any multiples of the prime factor. So if you have a list of prime factors up to the square root of the number you're checking, you only have to use those. Otherwise, you can check only numbers relatively prime to the product of the primes you do have. For instance, for primes <code>[2, 3, 5]</code>, you only have to check numbers that are, modulus 30, in <code>[1, 7, 11, 13, 17, 19, 23, 29]</code>.</p>\n\n<pre><code>import math\ndef prime_checker(pr, modulus = 30):\n residues = [residue for residue in range(modulus) \n if math.gcd(residue, modulus) == 1]\n try:\n our_int = int(pr)\n except:\n print(\"Not a valid number\")\n return\n if our_int != float(pr):\n print(\"Not an integer\")\n return\n if our_int &lt; 2:\n print(\"Number greater than 1 expected.\")\n return\n if our_int in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]:\n return True\n for candidate in range(2, modulus):\n if candidate * candidate &gt; our_int:\n return True\n if (our_int % candidate) == 0:\n print(str(candidate)+ \" is a factor\")\n return False \n multiple = 1\n while True:\n product = multiple*modulus\n if product*product &gt; our_int:\n return True\n for residue in residues: \n if ((our_int % (residue + product)) == 0):\n print(str(residue + product)+ \" is a factor\")\n return False \n multiple += 1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T07:02:13.813", "Id": "237540", "ParentId": "237455", "Score": "2" } }, { "body": "<h1>functions</h1>\n\n<p>Separate your program into functions</p>\n\n<ul>\n<li>getting the input number</li>\n<li>calculate the result </li>\n<li>present the result (print)</li>\n</ul>\n\n<h1>get the number</h1>\n\n<p>When you do <code>int(input(\"&lt;message&gt;\"))</code>, and the user types in text that is not convertable to an integer, your program will fail with a strange error message. Better is to validate the user input</p>\n\n<pre><code>def get_number() -&gt; int:\n \"\"\"\n Asks the user for a number\n\n Asks again if the user input is no valid integer\n Returns None when the user returns 'q'\n \"\"\"\n while True:\n input_str = input(\"Enter your number\")\n try:\n return int(input_str)\n except ValueError:\n if input_str.lower() == \"q\":\n return None\n print(\n f\"{input_str} is not a valid integer. \"\n \"Try again or enter `q` to quit\"\n )\n</code></pre>\n\n<p>If you want, you can add more tests to this function, like testing that the result is larger than 1,...</p>\n\n<h1>calculate</h1>\n\n<p>Your algorithm works like this:\n- iterate from the number itself down\n- store the remainder of the division in a dict\n- make a list of the values\n- check whether any of the values of the dict is 0</p>\n\n<p>This can be simplified in a number of steps:\n- why the list. You can immediately iterate over the values\n- why the dict? You only use the values, so you can use another container like a <code>list</code> or <code>set</code> to only store the values\n- why iterate over all the values, if you use a <code>set</code>, you can check <code>if 0 in remainders</code>\n- why iterate over all the values. You can stop once a remainder is 0\n- why start at the number with the iteration. You will not find any divisors between <code>number</code> and <code>number//2</code>. You can even stop at the square root of the number, because either the divisor or the quotient will be smaller if there is any.\n- why iterate descending. Odds are, you'll find a remainder in the lower numbers sooner\n- why iterate over all numbers. If 2 is no divisor, 4, 6, 8, ... will not be a divisor either</p>\n\n<p>So this would be a lot more efficient:</p>\n\n<pre><code>def is_prime(number: int) -&gt; bool:\n \"\"\"Checks whether `number` is prime\"\"\"\n if number &lt; 2:\n return False\n if number == 2: \n return True\n i = 3\n while i**2 &lt;= number:\n if number % i == 0: # or of `not number % i:`\n return False\n i += 2\n return True\n</code></pre>\n\n<p>There are more efficient prime checkers out there, but this will already be a lot more performant than your version</p>\n\n<h1>present the result</h1>\n\n<p>Now you have nice, clear functions to get a number from the user, and calculate whether the number is prime, you can make a function to present this to the user:</p>\n\n<pre><code>def main() -&gt; None:\n number = get_number()\n if number is None:\n return\n result = is_prime(number)\n if result:\n message = f\"{number} is prime\"\n else:\n message = f\"{number} is not prime\"\n\n print(message)\n print(\"Press Enter to close the program\")\n input()\n</code></pre>\n\n<h1><code>if __name__ == \"__main__\"</code></h1>\n\n<p>The code you really want executed when you call this as a script, but not when you import it in a different program should go behind an <code>if __name__ == \"__main__\":</code> guard. Here you can do the presentation:</p>\n\n<pre><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n\n<h1>type hints</h1>\n\n<p>I've added type hints, so users of the function (other programmers, not the end users) know what kind of type the function expects and returns</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T09:32:29.150", "Id": "237552", "ParentId": "237455", "Score": "4" } }, { "body": "<p>Great start! People have already given good advice in terms of improving the solution, but I'd like to comment on some things that could be improved on even though they aren't relevant in the \"cleaned up\" versions people have posted.</p>\n\n<ul>\n<li>you can iterate over a dictionary, so there's no need to turn it into a list first. Iterating over like this: <code>for i in dl:</code> will give you the keys, and like this: <code>for i in dl.values():</code> will of course give you the values. <code>dl.items()</code> gives both as a tuple (which can be unpacked if you'd like: <code>for (key, value) in dl.items():</code>.</li>\n<li>With that in mind, the <code>any</code> check could be written as <code>if any( z == 0 for z in dl.values()</code> This is fine, but we can invert the logic (something that takes a bit of experience to recognize). <code>if any values equal 0</code> is the same as <code>if all values are not 0</code>. Realizing that python treats <code>0</code> as <code>false</code> and all other integers as <code>true</code> gives the slightly cleaner final form: <code>if all(dl.values()): # the number is prime</code></li>\n<li>All that being said, since you aren't using the 'divisor list' <code>dl</code> except for checking if it contains a <code>0</code>, you can instead just break the loop when you find a <code>0</code> without storing the result and checking it later. Other answers cover that in better detail. That will be much more memory efficient and also more efficient in terms of runtime, since you can stop as soon as you find a divisor.</li>\n<li>Your first while condition is unnecessary. Since you've set <code>x = pr - 1</code>, <code>x &lt; pr</code> will always be true (provided you don't increment or set <code>x</code> to a value higher than <code>pr</code>, which of course you aren't doing)</li>\n</ul>\n\n<p>Happy Coding!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T17:40:20.703", "Id": "237650", "ParentId": "237455", "Score": "3" } } ]
{ "AcceptedAnswerId": "237497", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T20:48:13.107", "Id": "237455", "Score": "13", "Tags": [ "python", "primes" ], "Title": "Rate my first python prime checker" }
237455
<p>I've been writing code to get the frequencies of elements of an array. The code works, but it uses a lot of "old style" C constructs, some of which I feel should be changed to more C++-like features, but I don't know exactly which way would be best. In general, I feel that a lot of the code could be improved to be more elegant.</p> <p>The first two functions, <code>remdups</code> and <code>freq</code>, are helper functions for <code>getFrequencies</code>, which is "facade" of the API.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;vector&gt; template &lt;class T&gt; void remdups(T *arr, size_t *n) { for (size_t i = 1; i &lt; *n; ) { if (arr[i] == arr[i-1]) { memmove(arr + i - 1, arr + i, (*n-i) * sizeof (T)); --*n; } else ++i; } } int *freq(const int *arr, size_t n, size_t *outN) { int *freq = new int[n], cnt; for (size_t i = *outN = 0; i &lt; n; ++i) { freq[i] = -1; cnt = 1; for (size_t j = i + 1; j &lt; n; ++j) { if (arr[i] == arr[j]) { ++cnt; freq[j] = 0; } } if (freq[i] != 0) { freq[i] = cnt; ++*outN; } } // remove duplicate frequency entries remdups&lt;int&gt;(freq, outN); return freq; } std::vector&lt;std::pair&lt;int, size_t&gt;&gt; getFrequencies(std::vector&lt;int&gt; arr) { size_t n = arr.size(), newSize; int *freqs = freq(&amp;arr[0], n, &amp;newSize); // remove duplicate values from the array remdups(&amp;arr[0], &amp;newSize); std::vector&lt;std::pair&lt;int, size_t&gt;&gt; ret; for (size_t i = 0; i &lt; newSize; ++i) ret.push_back(std::pair&lt;int, size_t&gt; { arr[i], freqs[i] }); delete []freqs; return ret; } </code></pre> <p>Example driver code:</p> <pre><code>int main() { std::vector&lt;int&gt; v = { 5, -3, -3, -3, -2, 0, 0 }; auto freqs = getFrequencies(v); printf("%8s %8s\n", "Elem.", "Freq."); for (auto it = freqs.cbegin(); it != freqs.cend(); ++it) printf("%8d %8zu\n", it-&gt;first, it-&gt;second); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T22:13:26.637", "Id": "465632", "Score": "0", "body": "templates and std::vector are not part of C and will not compile in a strict C compiler. You might want to loose the old C I/O and use std::cin and std::cout." } ]
[ { "body": "<p>This seems over-complicated. A simpler solution would use a <code>std::map</code> or <code>std::unordered_map</code> for the counting:</p>\n\n<pre><code>std::unordered_map&lt;int, std::size_t&gt; counts;\nfor (auto const &amp;element: container) {\n ++counts[element];\n}\n</code></pre>\n\n<hr>\n\n<p>Instead of being tied to <code>std::vector&lt;int&gt;</code>, we could make the code much more flexible as a template, taking a pair of iterators (or, from C++20, a <code>std::range</code>) with any appropriate element type. The signature might look something like:</p>\n\n<pre><code>template&lt;typename Iter&gt;\nauto getFrequencies(Iter begin, Iter end)\n -&gt; std::unordered_map&lt;decltype(*Iter), std::size_t&gt;;\n</code></pre>\n\n<p>We might use constraints or SFINAE to choose whether to return an ordered or unordered map, based on whether <code>*Iter</code> is ordered and/or hashable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T10:18:09.887", "Id": "465694", "Score": "1", "body": "`typename std::iterator_traits<Iter>::difference_type`? That's what `std::count` returns. Also, should we give the user to specify the template arguments to `std::unordered_map` to enable usage with types for which something other than `std::equal_to` or `std::hash` has to be used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T11:37:03.783", "Id": "465702", "Score": "1", "body": "Yep @L.F. makes sense. Perhaps easiest if the user just specifies the entire type of the map. Anyway, this answer was just a loose sketch to suggest a simpler approach, rather than a full worked example (more learning value that way, plus I'm busy IRL ATM)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T09:04:49.680", "Id": "237483", "ParentId": "237457", "Score": "5" } } ]
{ "AcceptedAnswerId": "237483", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-17T21:15:54.853", "Id": "237457", "Score": "4", "Tags": [ "c++" ], "Title": "Count frequencies of elements in array" }
237457
<p>I have implemented Visitor and Decorator Pattern in python. I am much used to java design pattern style and hence thought would try in python as well. Could anyone tell me if this is the correct way to do in Python. </p> <p>Is there any better way to do this?</p> <p>I have made coffee class and decorating it with Sugar and Milk. I have a visitor that will calculate the tax or the cost. The values are random in TaxVisitor and CostVisitor</p> <pre><code>from abc import ABC, abstractmethod class Visitable(ABC): @abstractmethod def accept(self, visitor): pass class CostVisitor(ABC): @abstractmethod def cost(self, node): pass class TaxVisitor(CostVisitor): def cost(self,node): if isinstance(node, Milk): return 150 if isinstance(node, Sugar): return 100 if isinstance(node, Plain_Coffee): return 10 class CostVisitor(CostVisitor): def cost(self,node): if isinstance(node, Milk): return 15 if isinstance(node, Sugar): return 10 if isinstance(node, Plain_Coffee): return 1 class Coffee(Visitable): @abstractmethod def cost(self): raise ValueError('Implement') @abstractmethod def display(self): raise ValueError('Implement') class Plain_Coffee(Coffee): def cost(self): return 2 def display(self): return 'Coffee' def accept(self, visitor): return visitor.cost(self) class CoffeeDecorator(Coffee): def __init__(self, m_base): self.m_base = m_base def accept(self, visitor): return visitor.cost(self) + self.m_base.accept(visitor) class Milk(CoffeeDecorator): def __init__(self, m_base): CoffeeDecorator.__init__(self, m_base) def cost(self): return self.m_base.cost() + 1 def display(self): return self.m_base.display() + ' milk' class Sugar(CoffeeDecorator): def __init__(self, m_base): CoffeeDecorator.__init__(self, m_base) def cost(self): return self.m_base.cost() + .5 def display(self): return self.m_base.display() + ' sugar' coffee = Plain_Coffee() coffee = Milk(coffee) coffee = Sugar(coffee) print(coffee.accept(CostVisitor())) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T04:17:05.507", "Id": "465652", "Score": "1", "body": "You've got some mixed-up code. `coffee.accept(CostVisitor())` returns `26`, and `coffee.cost()` returns `3.5`. Why the difference?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T17:59:14.470", "Id": "465741", "Score": "0", "body": "@AJNeufeld Yes I get your point. I will fix it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:17:55.233", "Id": "465746", "Score": "0", "body": "@AJNeufeld I fixed the code by removing cost() since cost is being calculated by CostVisitor so we do not need cost()" } ]
[ { "body": "<p>In general visitor patterns in other languages are manage with tables, maps or any other struct/object type, here is the improvement that you can make on your code</p>\n\n<pre><code>class TaxVisitor(CostVisitor):\n\n def cost(self,node):\n if isinstance(node, Milk):\n return 150\n if isinstance(node, Sugar):\n return 100\n if isinstance(node, Plain_Coffee):\n return 10\n</code></pre>\n\n<p>Can be changed to</p>\n\n<pre><code>class TaxVisitor(CostVisitor):\n self.__table = { \"Milk\" : 150, \"Sugar\" : 100, ...}\n\n def cost(self,node):\n if node.__class__.__name__ in self.__table:\n return self.__table[node.__class__.__name__]\n</code></pre>\n\n<p>This will make it easy to extender the number of instances by just update the table variable, hope is clear.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T11:27:19.643", "Id": "465701", "Score": "1", "body": "why not just the classes as dict keys? Then you don't need the `.__class__.__name__`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T12:11:18.497", "Id": "465704", "Score": "0", "body": "Yes that's another valid approach, the idea basically is to use a dict() for handling the visitor lookups instead of if statements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:19:41.230", "Id": "465747", "Score": "0", "body": "@camp0 I am new to python what is self.__table suppose to mean? Is that instance variable or class variable? How would python recognize self if is not mentioned inside method or __init__()" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T08:27:47.323", "Id": "237480", "ParentId": "237467", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T00:12:16.463", "Id": "237467", "Score": "2", "Tags": [ "python", "python-3.x", "design-patterns" ], "Title": "Decorator & Visitor Pattern in Python" }
237467
<p>The challenge is to find the maximum product of a subset of a given array. Here's the problem:</p> <blockquote> <p>Write a function solution(xs) that takes a list of integers representing the power output levels of each panel in an array, and returns the maximum product of some non-empty subset of those numbers. So for example, if an array contained panels with power output levels of [2, -3, 1, 0, -5], then the maximum product would be found by taking the subset: xs[0] = 2, xs[1] = -3, xs[4] = -5, giving the product 2*(-3)*(-5) = 30. So solution([2,-3,1,0,-5]) will be "30".</p> <p>Each array of solar panels contains at least 1 and no more than 50 panels, and each panel will have a power output level whose absolute value is no greater than 1000 (some panels are malfunctioning so badly that they're draining energy, but you know a trick with the panels' wave stabilizer that lets you combine two negative-output panels to produce the positive output of the multiple of their power values).</p> </blockquote> <p>My code basically removes all 0's inside the list, then I iterate over all the remaining integers in the array and put each one in their respective array (positive or negative numbers). I sort my array with negative numbers then check its length; if it's odd, then I remove the last element (which will always be the one closest to 0 since I sorted it). Finally, I multiply each number inside these two arrays and return the result (we need to return it as string).</p> <pre class="lang-py prettyprint-override"><code>def solution(xs): negatives = [] positives = [] product = 1 xs = filter(lambda a: a != 0, xs) if not xs: return '0' for num in xs: if num &gt; 0: positives.append(num) elif num &lt; 0: negatives.append(num) if not positives and len(negatives) == 1: return '0' negatives.sort() if negatives: if len(negatives) % 2 != 0: negatives.pop() for x in positives + negatives: product *= x return str(product) </code></pre> <p>I've already search the internet as to why my logic is failing the fourth test case, I've read that if there's only one negative number in the array, you should return 0, but I also read that you should return the negative value. However, previously to writing the part of my code that checks this possibility, the fifth test case was also failing. So you need to return 0 in this case.</p> <p><a href="https://repl.it/@DanielSouzaBert/PrimarySlateblueVolume" rel="nofollow noreferrer">Here's the repl with my code</a>, open test cases and some test cases that I've added.</p> <p>Clearly there's an edge case that my code is failing but I can't figure out at all. Help, please?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T15:23:28.977", "Id": "465723", "Score": "0", "body": "What is the exact message you get back? Is it merely a time-limit-exceeded problem or a wrong answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T15:28:38.223", "Id": "465726", "Score": "0", "body": "@Mast just \"Test 4 [Hidden] Failed\", but I managed to pass all test cases now, thanks to the answer below :)" } ]
[ { "body": "<p>You've got too much code.</p>\n\n<p>First you filter out the zeros:</p>\n\n<pre><code>xs = filter(lambda a: a != 0, xs)\n</code></pre>\n\n<p>Then you filter the positives to one list and the negatives to another:</p>\n\n<pre><code>for num in xs:\n if num &gt; 0:\n positives.append(num)\n elif num &lt; 0:\n negatives.append(num)\n</code></pre>\n\n<p>So why bother with the first filtering? Zeros would go into neither list in this loop; they're naturally filtered out.</p>\n\n<p>You sort the <code>negatives</code> array unnecessarily. You only need to do so if it contains an odd number of elements. And you don't need to protect the test of whether it contains an odd number of elements with a check if it contains any elements at all.</p>\n\n<p>No positive values and 1 negative value seems an odd special case. If you let the code progress past that point, the single odd value would be pop'd out of the negative array, leaving no positive values and no negative values, which seems a less \"special\" special case.</p>\n\n<p>Simplified code:</p>\n\n<pre><code>def solution(xs):\n negatives = [num for num in xs if num &lt; 0]\n positives = [num for num in xs if num &gt; 0]\n\n if len(negatives) % 2 != 0:\n negatives.sort()\n negatives.pop()\n\n if positives or negatives:\n product = 1\n for x in positives + negatives:\n product *= x\n\n return str(product)\n\n return '0'\n</code></pre>\n\n<p>This should behave the same as your original code (complete with not passing some edge cases), but should be slightly faster.</p>\n\n<hr>\n\n<p>Do you really need to sort the <code>negatives</code> array? That is an <span class=\"math-container\">\\$O(N \\log N)\\$</span> operation. You just need to remove the smallest magnitude number from the array, and finding and removing that can be done in <span class=\"math-container\">\\$O(N)\\$</span> time.</p>\n\n<hr>\n\n<h1>Edge Cases</h1>\n\n<p>What is the maximum product of a non-empty subset of <code>[-4]</code>?</p>\n\n<blockquote>\n <p>I've read that if there's only one negative number in the array, you should return 0, but I also read that you should return the negative value.</p>\n</blockquote>\n\n<p>Seems unreasonable to return zero in this case, because the only non empty subset is <code>[-4]</code>, and the maximum product is <code>-4</code>.</p>\n\n<p>But what about <code>[-4, 0]</code>? Both <code>0 &gt; -4</code> and <code>-4 * 0 &gt; -4</code>, so the maximum product is no longer <code>-4</code>.</p>\n\n<p>Modification of the code left to student.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T13:30:17.283", "Id": "465712", "Score": "0", "body": "Wow... How could I be so dumb, that's exatcly the edge case that was missing. I know this is a space for clarification but thank you so much for helping me out and giving a great feedback about my code. It passed all test cases!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T03:13:19.427", "Id": "237472", "ParentId": "237468", "Score": "1" } } ]
{ "AcceptedAnswerId": "237472", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T00:15:48.110", "Id": "237468", "Score": "0", "Tags": [ "python", "python-2.x" ], "Title": "Foo Bar - Power Hungry challenge test case failing on unknown edge cases" }
237468
<p>I have this specific scenario where I'm going to get a JSON that could have multiple Objects. From the Multiple Objects I will create a new Json that can have nested arrays growing by n amount depending on some json object values.</p> <p>I hoping there is a better way to do this. Maybe my example below is the best way? I took a look at <a href="https://realpython.com/python-data-classes/" rel="nofollow noreferrer">https://realpython.com/python-data-classes/</a> but I don't think that will help since it seems complicated to turn the dataclass object into another json. </p> <p>Update: I think I will ingest the original json object into a dataclass. Then iterate over the objects. </p> <p>Example Input: Note that 3 and 4 are break start and end times. Which is why you will see the start and end times show up in the break array.</p> <pre><code>[{ "name": "Jay", "clock_type": 1, "start": "4am" }, { "name": "Jay", "clock_type": 4, "start": "5am" }, { "name": "Jay", "clock_type": 3, "end": "6am" }, { "name": "Jay", "clock_type": 4, "start": "7am" }, { "name": "Jay", "clock_type": 3, "end": "8am" }] </code></pre> <p>Example output:</p> <pre><code>{ "name": "Jay", "start": "4am", "break": [{ "start": "5am", "end": "6am" }, { "start": "7am", "end": "8am" }] } </code></pre> <p>What i'm doing right now is looping through the array, and building the punch dynamically based on the "clock_type". </p> <pre><code>import json def write_new_json(data): request = {} break_count = 0 for i in data: # 1 = New Object. First Clock In if i['clock_type'] in [1]: request.update({"name": i["name"], "start": i["start"]}) # 3 = Break End if i['clock_type'] in [3]: request["break"][break_count].update({"end": i["end"]}) break_count += 1 # 4 = Break start. If there is already a breaks object, then we do not create a breaks array, # we just append to the existing one. if i['clock_type'] in [4]: if break_count == 0: request.update({"break": []}) request["break"].append({"start": i["start"]}) # 2 = Not in the example, but a punch of 2 would reset break_count to 0. return request with open('example.json') as f: api_request = write_new_json(json.load(f)) print(json.dumps(api_request)) </code></pre>
[]
[ { "body": "<p>There are a few points in the existing code that I think could be improved.</p>\n<h3>Confusing function name <code>write_new_json</code></h3>\n<p>Naming is important. Good names make your code more readable, and easier to understand. Bad names make it less readable. Names are bad when they don't describe what the thing is/does, or conversely, if they <em>seem</em> to describe something that the thing <em>isn't/doesn't do</em>.</p>\n<p>Usually, the verbs &quot;read&quot; and &quot;write&quot; in programming refer to fetching data from, and sending data to, some external/system resource. Especially a file. So the name <code>write_new_json()</code> sounds like you're writing some JSON to a file. But that's not what the function is doing at all. It's actually transforming some JSON into some other kind of JSON. Therefore <code>write_new_json()</code> is a misleading name.</p>\n<p>I would pick a new name that avoids <code>write</code> and probably even avoids <code>json</code>; describing the input and output formats of a function as &quot;JSON&quot; does nothing to capture the <em>purpose</em> of the function. How about <code>build_clock_punches</code>? <code>build_time_logs</code>?</p>\n<h3>Confusing variable name <code>i</code></h3>\n<pre><code> for i in data:\n</code></pre>\n<p>Another naming nitpick. In most programming languages, it is conventional to name your loop counter variable <code>i</code>. In Python, this would be something like <code>for i in range(0, 1000):</code>.<sup>1</sup> But in your case, <code>i</code> is not a loop counter; it is not even a number. Therefore the name is confusing. Try using a more descriptive name, e.g. <code>for clock_punch in data:</code> or <code>for clock_event in data:</code>.</p>\n<h3>Unnecessary use of <code>in</code> operator</h3>\n<pre><code> if i['clock_type'] in [3]:\n</code></pre>\n<p>You're using <code>in</code> because <code>[3]</code> is a list, but there doesn't seem to be any reason that <code>[3]</code> needs to be a list. You can just compare the value directly using the equality operator, e.g. <code>if clock_event['clock_type'] == 3:</code>.</p>\n<h3>Unnecessary variable <code>break_count</code></h3>\n<p>As far as I can tell, you only use <code>break_count</code> to keep track of the length of <code>request[&quot;break&quot;]</code>. Persistently tracking the length of a list in a separate variable is a <strong>bad idea</strong>: it is unnecessary, and it opens you up to bugs. Suppose you go in later and add a new line of code that changes the length of <code>request[&quot;break&quot;]</code>, but forget to add that second line of code that updates <code>break_count</code>? Or vice versa?</p>\n<p>To find the length of a list directly, use <code>len()</code>.</p>\n<pre><code> if clock_event['clock_type'] == 3:\n last_break_index = len(request[&quot;break&quot;]) - 1\n request[&quot;break&quot;][last_break_index].update({&quot;end&quot;: clock_event[&quot;end&quot;]})\n</code></pre>\n<p>But wait! There's an even better approach here. Python offers a handy syntax for getting the last item in a list: <code>my_list[-1]</code>.</p>\n<pre><code> if clock_event['clock_type'] == 3:\n request[&quot;break&quot;][-1].update({&quot;end&quot;: clock_event[&quot;end&quot;]})\n</code></pre>\n<p>And for the <code>if break_count == 0:</code> line, it is better to check for the non-existence of <code>request[&quot;break&quot;]</code> directly.</p>\n<pre><code> if clock_event['clock_type'] == 4:\n if &quot;break&quot; not in request:\n request.update({&quot;break&quot;: []})\n</code></pre>\n<h3>Too trusting</h3>\n<p>Your program assumes the input data will always be well-formed. What happens if it's not? Suppose the system that produces your input goes haywire, and you receive a break-start, and then <em>two</em> break-ends? Or receive a break-end without receiving any break-starts first? Or data with a mix of two or more names?<sup>2</sup> Depending on the nature of the nonsense input, your program would either crash entirely, or produce a nonsense output of its own.</p>\n<p>What your program <em>should</em> do in these cases is detect that something is wrong, and then throw some kind of <a href=\"https://docs.python.org/3/tutorial/errors.html#exceptions\" rel=\"nofollow noreferrer\">exception</a> that explains what the problem was. Unfortunately I don't have time to elaborate on every possible case you might encounter, so I'll have to leave that as an exercise for you.</p>\n<p>Of course, if this is a school assignment or other non-real-world project where you have a <em>guarantee</em> that the data will be well-formed, you may not want to go through all the extra trouble. But it's something you should keep in mind for future projects.</p>\n<hr />\n<h3>Thoughts on using a data class</h3>\n<p>You mentioned wanting to use a data class to ingest the input data. If all you are planning to do is replace all the dicts in the list <code>data</code> with equivalent data class objects, and then run those objects through the same logic you have now...then you don't gain that much. You do get the type annotations, and there's nothing wrong with having those, but it's not a <em>huge</em> benefit.</p>\n<hr />\n<p><sup><sup>1</sup>Technically, Python doesn't even have &quot;loop counters&quot; like some other languages do. All Python for-loops are <a href=\"https://en.wikipedia.org/wiki/Foreach_loop\" rel=\"nofollow noreferrer\"><em>foreach</em> loops</a> rather than &quot;traditional&quot; for-loops. But it's close enough that the conventions around <code>i</code> still apply.</sup></p>\n<p><sup><sup>2</sup>Actually, it seems perfectly reasonable for the upstream system to send you data for two or more names at once. You may want to enhance your code to support that (or not, I don't know your circumstances).</sup></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:07:24.667", "Id": "466171", "Score": "0", "body": "Thanks! I really appreciate the input, especially the part about break counters!\n\nThe data i'm getting is from some other code that I wrote. If it does not come in the format i'm expecting there was a pretty big issue since there is a lot in place to make sure it does. However, I've seen stranger things so I will definitely add some logic for what to do when the file is not as I expect it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T18:12:50.320", "Id": "466191", "Score": "0", "body": "@PhilipJayFry Well, if it's all one big program, then it's easier to trust that you're getting the right stuff. The best thing to do is ask \"how much control do I have over what data the module receives?\" and then work from there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T18:36:53.913", "Id": "466194", "Score": "0", "body": "@PhilipJayFry ...keeping in mind that code tends to get re-written, refactored, reused, and generally moved around. So even if you control the source of your data _today_, that doesn't guarantee that you will control it _tomorrow_." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T06:08:34.570", "Id": "237682", "ParentId": "237470", "Score": "2" } }, { "body": "<p>Three things to add to MJ713's answer:</p>\n\n<p>For mutually exclusive options, use <code>if ... elif ...</code>. When a match is found, the rest of the conditions are skipped. It may also help to put the order the tests so that the most common case is first and the least common case is last.</p>\n\n<p><code>dict.setdefault(key, default_value)</code> returns dict[key] if it is in the dict. Otherwise, it sets dict[key] to default_value and returns that.</p>\n\n<p>Avoid so called \"magic numbers\". If someone else looks at your code, they won't know what <code>3</code> means. Indeed, you put a note in the problem description to say that <code>3</code> and <code>4</code> indicate break start/stop times. The numbers also make it more difficult to change the code (e.g., are you sure the 3 you are about to change is a break start and not just a 3?). It would be better to use a global constant or an enum.</p>\n\n<p>Put together:</p>\n\n<pre><code>DAY_START = 1\nBREAK_RESET = 2\nBREAK_END = 3\nBREAK_START = 4\nDAY_END = 5\n\ndef collect_data(data):\n\n request = {}\n\n for clock_event in data:\n clock_type = clock_event['clock_type']\n\n if clock_type == BREAK_START:\n breaks = request.setdefault(\"break\", [])\n breaks.append({\"start\": clock_event[\"start\"]})\n\n elif clock_type == BREAK_END:\n request[\"break\"][-1][\"end\"] = clock_event[\"end\"]\n\n elif clock_type == DAY_START:\n request.update({\"name\": clock_event[\"name\"],\n \"start\": clock_event[\"start\"]})\n\n # handle other clock types\n\n else:\n raise ValueError(f\"Invalid 'clock_type': {clock_type}\") \n\n return request\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T15:09:42.887", "Id": "466172", "Score": "0", "body": "Thanks! You make a very good point about my use of numbers in the logic flow. An Enum seems like a great alternative." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T18:38:02.313", "Id": "466195", "Score": "0", "body": "All very good points." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T06:51:20.630", "Id": "237684", "ParentId": "237470", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T01:05:05.390", "Id": "237470", "Score": "4", "Tags": [ "python", "python-3.x", "json", "hash-map" ], "Title": "Takes json input and builds dynamic json output based on values in input: Looking for a better way to accomplish this" }
237470
<p>So I want to create a very basic constantly changing text bvariable with a counter function. I created it, and it is working well, but once I press the "countdown" button, the GUI freezes, and the only way to close the window is from PyCharm.</p> <p>Any suggestons about what causes the freeze and how to fix it?</p> <p>The program unfreezes when the countdown is finished, so it's just a hanging interface, not a crash. Written for Python 3.8.</p> <pre><code>from tkinter import * class MyFirstGUI: def __init__(self, master): self.master = master master.title("A simple GUI") self.label = Label(master, textvariable=time) self.label.pack() self.greet_button = Button(master, text="Greet", command=self.greet) self.greet_button.pack() self.close_button = Button(master, text="Countdown", command=self.countdown) self.close_button.pack() def greet(self): print("Greetings!") def countdown(self): remaining = 100 for i in range(100): time.set(remaining) remaining -= 1 self.master.after(1000) self.master.update_idletasks() root = Tk() time = StringVar() my_gui = MyFirstGUI(root) root.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:38:40.457", "Id": "466162", "Score": "0", "body": "The `after()` method acts exactly liked `sleep()` if all you provide is the milliseconds. This effectively blocks the mainloop. Also this question is more of SO question. I do not think it is well suited for CR." } ]
[ { "body": "<p>Tkinter is already in a loop. The window handler gets all messed up because of your own loop, which is called synchronously. Effectively you're running a loop in a loop and wonder why the outer loop takes so long to get to the next step. That's because of the inner loop taking so much time.</p>\n\n<p>Long story short, your next window update will only commence once the <code>countdown</code> loop is finished.</p>\n\n<p>There's mainly 2 ways of fixing that.</p>\n\n<ol>\n<li>Don't loop.</li>\n<li>Use asynchronous (or threaded) loops instead.</li>\n</ol>\n\n<p>Basically, you'll need a function <code>start_countdown</code> which starts a threaded version of <code>countdown</code>. That would probably look something like this:</p>\n\n<pre><code>import threading\n\n\nclass MyFirstGUI:\n # Init and rest of methods snipped for brevity\n def refresh(self):\n self.root.update()\n self.root.after(1000,self.refresh)\n\n def start_countdown(self):\n self.refresh()\n threading.Thread(target=countdown).start()\n</code></pre>\n\n<p>Now, the countdown will be calculated in a thread that doesn't halt the current loop (the Tkinter main window). With that as basis, see if you can rebuild your <code>countdown</code> method. You'll see it becomes more focussed on the actual calculations and less on the screen.</p>\n\n<p>Please see <a href=\"https://stackoverflow.com/a/29158947/1014587\">this answer on Stack Overflow</a> for the complete story on how to work with Tkinter and calls that would ordinarily block.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T07:52:34.357", "Id": "465669", "Score": "0", "body": "Thank you very much Mast! Exactly what I was looking for. As a newbie, I had no idea about this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T07:55:48.777", "Id": "465670", "Score": "0", "body": "@RMWIXX No problem, glad I could help out. And, next time, please be complete in both your code and question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:41:20.680", "Id": "466164", "Score": "0", "body": "Threading is overkill here. `after()` is perfectly suited for timers in tkinter. It just needs to be used correctly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T20:15:57.573", "Id": "466207", "Score": "1", "body": "@Mike feel free to point out better solutions in your own answer, should it be posted on SO." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T07:48:35.680", "Id": "237478", "ParentId": "237476", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T06:56:52.980", "Id": "237476", "Score": "0", "Tags": [ "python", "python-3.x", "tkinter" ], "Title": "Python Tkinter countdown app with a freezing GUI" }
237476
<p>I have the following function which has the required functionality. Is there any way that I can reduce the code but have the same functionality?</p> <pre><code>addClickEventListeners = () =&gt; { let multipleChoiceQuestionButtons = document.querySelectorAll('[name="multiple_choice"]'); let trueFalseQuestionButtons = document.querySelectorAll('[name="true_false"]'); let multipleChoiceMultiAnswersQuestionButtons = document.querySelectorAll('[name="multi_answers"]'); if (multipleChoiceQuestionButtons.length &gt; 0) { multipleChoiceQuestionButtons.forEach((button) =&gt; { button.addEventListener('click', someFunction, false); }); } else if (trueFalseQuestionButtons.length &gt; 0) { trueFalseQuestionButtons.forEach((button) =&gt; { button.addEventListener('click', someFunction, false); }); } else if (multipleChoiceMultiAnswersQuestionButtons.length &gt; 0) { multipleChoiceMultiAnswersQuestionButtons.forEach((button) =&gt; { button.addEventListener('click', someFunction, false); }); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T15:22:51.770", "Id": "465722", "Score": "0", "body": "To be clear, you call the same `someFunction` in all three cases?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T15:25:12.733", "Id": "465725", "Score": "0", "body": "Yes. It's the same function." } ]
[ { "body": "<p>Interesting question;</p>\n\n<p>You can make this code slightly less efficient (however, the user will never notice), and so we can just attach listeners to everything.</p>\n\n<pre><code>const addClickEventListeners = () =&gt; {\n\n const addListener = (button) =&gt; button.addEventListener('click', someFunction, false);\n\n document.querySelectorAll('[name=\"multiple_choice\"]').forEach(addListener);\n document.querySelectorAll('[name=\"true_false\"]').forEach(addListener); \n document.querySelectorAll('[name=\"multi_answers\"]').forEach(addListener); \n\n};\n</code></pre>\n\n<p>This should behave the same way as far as I can tell.</p>\n\n<p>You could also create your buttons that require <code>someFunction</code> with a css class dedicated for that selection or even better with a data attribute for that purpose. Then you just query on that and attach the listener.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:08:28.363", "Id": "465744", "Score": "0", "body": "Can you please tell why is the above code less efficient?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:21:24.003", "Id": "465749", "Score": "0", "body": "Because it will try a `forEach()`, even if nothing was found" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T21:54:06.773", "Id": "465792", "Score": "0", "body": "Since they all attach to the same handler could you comma separate the selectors in one `querySelectorAll`?\nOf course keeping it separate can help with readability" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T12:19:10.520", "Id": "465864", "Score": "0", "body": "@AdamTaylor totally, you could and I did consider it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T15:42:14.157", "Id": "237498", "ParentId": "237477", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T07:33:21.020", "Id": "237477", "Score": "1", "Tags": [ "javascript" ], "Title": "Better way to query and pass the elements to conditional operator in Javascript" }
237477
<p>I was assigned an university project where I had to parse directed graph files coming from <a href="http://snap.stanford.edu/" rel="nofollow noreferrer">SNAP</a> and then convert them into CSR (Compressed Sparse Row) format. Then the client must have the ability to perform connection queries between any 2 vertices by using Bidirectional BFS.</p> <p>Here is my implementation:</p> <p><strong>Main.java</strong></p> <pre><code>public class Main { public static void main(String[] args) { InputInterface input = null; switch (args.length) { case 1: input = new KeyboardHandler(); break; case 3: if(args[1].equalsIgnoreCase("-f")) input = new QueryFileHandler(args[2]); else { System.out.println("Usage: program &lt;graphPath&gt; [-f &lt;queriesFile&gt; ] "); System.exit(1); } break; default: System.out.println("Usage: program &lt;graphPath&gt; [-f &lt;queriesFile&gt; ] "); System.exit(1); break; } try { AdjacencyListGraph s = new AdjacencyListGraph(args[0]); CSRGraph normalCSR = new CSRGraph(s,GraphType.NORMAL); CSRGraph invertedCSR = new CSRGraph(s,GraphType.INVERTED); BidirectionalBFS bfs = new BidirectionalBFS(normalCSR,invertedCSR); input.processQueries(bfs); } catch(AdjacencyListGraphNotCompletedException ex) { System.out.println(ex.getMessage() + "\nTerminating application..."); System.exit(2); } catch(CSRGraphNotCompletedException ex) { System.out.println(ex.getMessage() + "\nTerminating application..."); System.exit(3); } } } </code></pre> <p><strong>AdjacencyListGraph.java</strong></p> <pre><code>import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.HashMap; import java.util.LinkedList; import java.util.regex.Pattern; public class AdjacencyListGraph { private final HashMap&lt;Long, LinkedList&lt;Long&gt;&gt; normalGraph = new HashMap&lt;&gt;(); private final HashMap&lt;Long, LinkedList&lt;Long&gt;&gt; invertedGraph = new HashMap&lt;&gt;(); private int totalEdges; //Constructor public AdjacencyListGraph(String path) throws AdjacencyListGraphNotCompletedException { System.out.println("Parsing file " + path); long tStart = System.nanoTime(); try { File file = new File(path); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.US_ASCII); BufferedReader br = new BufferedReader(isr); Pattern pattern = Pattern.compile("\\s"); int lineCounter = 0; String line; while ((line = br.readLine()) != null) { lineCounter++; if (line.charAt(0) != '#') //Discarding any comments { try { //Tokenize the line final String[] tokens = pattern.split(line); final long source = Long.parseLong(tokens[0]); final long target = Long.parseLong(tokens[1]); //Add the edge to the 2 Maps addTargetToSource(normalGraph,source,target); addTargetToSource(invertedGraph,target,source); this.totalEdges++; } catch(NumberFormatException ex) { System.out.println("Error at line " + lineCounter + " : Could not parse. String was: " + line + ". Skipping line "); } } } br.close(); long tEnd = System.nanoTime(); System.out.println("Loaded " + totalEdges + " edges in " + Duration.ofNanos(tEnd - tStart).toMillis() + "ms"); } catch (FileNotFoundException ex) { throw new AdjacencyListGraphNotCompletedException("Invalid file path given."); } catch (IOException ex) { throw new AdjacencyListGraphNotCompletedException("I/0 error occurred."); } } //Getters public HashMap&lt;Long, LinkedList&lt;Long&gt;&gt; getNormalGraph() { return this.normalGraph; } public HashMap&lt;Long, LinkedList&lt;Long&gt;&gt; getInvertedGraph() { return invertedGraph; } public int getTotalEdges() { return this.totalEdges; } private void addTargetToSource(HashMap&lt;Long, LinkedList&lt;Long&gt;&gt; map, Long source, Long target) { map.putIfAbsent(source, new LinkedList&lt;&gt;()); map.get(source).add(target); } } </code></pre> <p><strong>AdjacencyListGraphNotCompletedException.java</strong></p> <pre><code>public class AdjacencyListGraphNotCompletedException extends Exception { public AdjacencyListGraphNotCompletedException(String message) { super(message); } } </code></pre> <p><strong>CSRGraph.java</strong></p> <pre><code>import java.time.Duration; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; enum GraphType { NORMAL("Normal"), INVERTED("Inverted"); final String name; GraphType(String name) { this.name = name; } } public class CSRGraph { private HashMap&lt;Long, Integer&gt; idMap ; private int[] IA; private long[] JA; public CSRGraph(AdjacencyListGraph graph, GraphType type) throws CSRGraphNotCompletedException { long tStart = System.nanoTime(); HashMap&lt;Long, LinkedList&lt;Long&gt;&gt; graphMap; switch (type) { case NORMAL: graphMap = graph.getNormalGraph(); break; case INVERTED: graphMap = graph.getInvertedGraph(); break; default: throw new CSRGraphNotCompletedException("Implementation error."); } if(graphMap.isEmpty()) throw new CSRGraphNotCompletedException("Error in the creation of CSR: No edges exist."); this.idMap = new HashMap&lt;&gt;(graphMap.size()); this.IA = new int[graphMap.size()+1]; this.IA[0] = 0; this.JA = new long[graph.getTotalEdges()]; int IA_Index = 0; int JA_Index = 0; //Iterate through every HashMap entry for(Map.Entry&lt;Long, LinkedList&lt;Long&gt;&gt; entry : graphMap.entrySet()) { long key = entry.getKey(); LinkedList&lt;Long&gt; values = entry.getValue(); for (long target : values) this.JA[JA_Index++] = target; this.idMap.put(key, IA_Index); this.IA[IA_Index + 1] = IA[IA_Index] + values.size(); IA_Index++; } long tEnd = System.nanoTime(); System.out.println(type.name + " graph conversion to CSR took " + Duration.ofNanos(tEnd - tStart).toMillis() + "ms"); } public LinkedList&lt;Long&gt; getNeighbors(long id) { LinkedList&lt;Long&gt; children = new LinkedList&lt;&gt;(); if(!idMap.containsKey(id)) return children; int id_Index = idMap.get(id); long [] children_arr = Arrays.copyOfRange(JA,IA[id_Index],IA[id_Index+1]); for(long target : children_arr) children.add(target); return children; } public boolean vertexExists(long id) { return idMap.containsKey(id); } } </code></pre> <p><strong>CSRGraphNotCompletedException.java</strong></p> <pre><code>public class CSRGraphNotCompletedException extends Exception { public CSRGraphNotCompletedException(String message) { super(message); } } </code></pre> <p><strong>BidirectionalBFS.java</strong></p> <pre><code>import java.time.Duration; import java.util.HashMap; import java.util.LinkedList; public class BidirectionalBFS { private final CSRGraph normalGraph; private final CSRGraph invertedGraph; public BidirectionalBFS(CSRGraph normalGraph, CSRGraph invertedGraph) { this.normalGraph = normalGraph; this.invertedGraph = invertedGraph; } public BFSResult connectionQuery(VertexPair query) { long tStart = System.nanoTime(); long source = query.getSourceNode(); long target = query.getTargetNode(); /*We then check if the source and target nodes even exist in the graph. We earn a lot of time if we skip doomed BFS queries. */ boolean source_exists = normalGraph.vertexExists(source); boolean target_exists = invertedGraph.vertexExists(target); if(!source_exists || !target_exists) return new BFSResult(source,source_exists,target,target_exists,false,null,Duration.ofNanos(System.nanoTime() - tStart)); else if(source == target) return new BFSResult(source, true, target, true,true, 0, Duration.ofNanos(System.nanoTime() - tStart)); LinkedList&lt;Long&gt; queueNormal = new LinkedList&lt;&gt;(); LinkedList&lt;Long&gt; queueInverted = new LinkedList&lt;&gt;(); HashMap&lt;Long,Integer&gt; nodeInfoNormal = new HashMap&lt;&gt;(); HashMap&lt;Long,Integer&gt; nodeInfoInverted = new HashMap&lt;&gt;(); nodeInfoNormal.put(source,0); nodeInfoInverted.put(target,0); queueNormal.add(source); queueInverted.add(target); while (!queueNormal.isEmpty() || !queueInverted.isEmpty()) { Intersection intersection; if ((intersection = graphBFS(normalGraph,queueNormal, nodeInfoNormal, nodeInfoInverted)).intersectionExists() || (intersection = graphBFS(invertedGraph,queueInverted, nodeInfoInverted, nodeInfoNormal)).intersectionExists()) { int normalDistance = nodeInfoNormal.get(intersection.getIntersectNode()); int invertedDistance = nodeInfoInverted.get(intersection.getIntersectNode()); int totalDistance = normalDistance + invertedDistance; return new BFSResult(source, true, target, true, true, totalDistance, Duration.ofNanos(System.nanoTime() - tStart)); } } return new BFSResult(source,true,target,true,false,null,Duration.ofNanos(System.nanoTime() - tStart)); } private Intersection graphBFS(CSRGraph graph, LinkedList&lt;Long&gt; queue, HashMap&lt;Long,Integer&gt; nodeInfoThisGraph, HashMap&lt;Long,Integer&gt; nodeInfoOtherGraph) { if (!queue.isEmpty()) { long current_node = queue.remove(); LinkedList&lt;Long&gt; adjacentNodes = graph.getNeighbors(current_node); while (!adjacentNodes.isEmpty()) { long adjacent = adjacentNodes.poll(); if (nodeInfoOtherGraph.containsKey(adjacent)) { nodeInfoThisGraph.put(adjacent,nodeInfoThisGraph.get(current_node)+1); return new Intersection(true,adjacent); } else if(!nodeInfoThisGraph.containsKey(adjacent)) { nodeInfoThisGraph.put(adjacent,nodeInfoThisGraph.get(current_node)+1); queue.add(adjacent); } } } return new Intersection(false,null); } public void areConnected(VertexPair query) { BFSResult res = connectionQuery(query); System.out.println(res.toString()); } } final class BFSResult { private final long source_id; private final boolean source_exists; private final long target_id; private final boolean target_exists; private final boolean areConnected; private final Integer distance; private final Duration timeElapsed; public BFSResult(long source_id, boolean source_exists, long target_id, boolean target_exists, boolean areConnected, Integer distance, Duration timeElapsed) { this.source_id = source_id; this.source_exists = source_exists; this.target_id = target_id; this.target_exists = target_exists; this.areConnected = areConnected; this.distance = distance; this.timeElapsed = timeElapsed; } public long getSource_id() { return source_id; } public boolean isSource_exists() { return source_exists; } public long getTarget_id() { return target_id; } public boolean isTarget_exists() { return target_exists; } public boolean isAreConnected() { return areConnected; } public Integer getDistance() { return distance; } public Duration getTimeElapsed() { return timeElapsed; } @Override public String toString() { return "BFSResult{" + "source_id=" + source_id + ", source_exists=" + source_exists + ", target_id=" + target_id + ", target_exists=" + target_exists + ", areConnected=" + areConnected + ", distance=" + distance + ", timeElapsed=" + timeElapsed.toMillis() + "ms" + '}'; } } final class Intersection { private final boolean intersectionExists; private final Long intersectNode; public Intersection(boolean intersectionExists,Long intersectNode) { this.intersectionExists = intersectionExists; this.intersectNode = intersectNode; } public boolean intersectionExists() { return intersectionExists; } public Long getIntersectNode() { return intersectNode; } } </code></pre> <p><strong>InputInterface.java</strong></p> <pre><code>public interface InputInterface { void processQueries(BidirectionalBFS bfs); } </code></pre> <p><strong>KeyboardHandler.java</strong></p> <pre><code>import java.util.Scanner; public class KeyboardHandler implements InputInterface { private Scanner scan = new Scanner(System.in); public void processQueries(BidirectionalBFS bfs) { System.out.println("Using keyboard input."); while(true) { System.out.println("Give a node pair (source,target)"); VertexPair query = new VertexPair(longPositiveZero(),longPositiveZero()); bfs.areConnected(query); System.out.println("Would you like an another query? (Yes/No)"); String answer = stringEqualsIgnoreCase(new String[]{"Yes","No"}); if(answer.equalsIgnoreCase("No")) { System.out.println("Thank you for using our software!"); System.exit(0); } } } public long longPositiveZero() { long value; while(true) { while (!scan.hasNextLong()) { System.out.println("Expected an Integer. Please type again."); scan.next(); } value = scan.nextLong(); if(value &gt;= 0) return value; else System.out.println("Field cannot be negative. Please type again."); } } public String stringEqualsIgnoreCase(String[] args) { while(true) { String value = scan.next(); for(String i : args) { if(value.equalsIgnoreCase(i)) return i; } System.out.println("Invalid value. Please type again."); } } } </code></pre> <p><strong>QueryFileHandler.java</strong></p> <pre><code>import java.io.*; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.LinkedList; import java.util.regex.Pattern; public class QueryFileHandler implements InputInterface { private String path; public QueryFileHandler(String path) { this.path = path; } public void processQueries(BidirectionalBFS bfs) { System.out.println("Using file input mode."); LinkedList&lt;VertexPair&gt; queries = null; try { queries = parseQueries(); } catch (QueryFileHandlerException ex) { System.out.println(ex.getMessage() + "\nTerminating application..."); System.exit(3); } while(queries.size() != 0) { VertexPair query = queries.poll(); bfs.areConnected(query); } System.out.println("Thank you for using our software!"); } private LinkedList&lt;VertexPair&gt; parseQueries() throws QueryFileHandlerException { long totalQueries = 0; LinkedList&lt;VertexPair&gt; queries = new LinkedList&lt;&gt;(); System.out.println("Parsing query file " + path); long tStart = System.nanoTime(); try { File file = new File(path); FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.US_ASCII); BufferedReader br = new BufferedReader(isr); Pattern pattern = Pattern.compile("\\s"); int lineCounter = 0; String line; while ((line = br.readLine()) != null) { lineCounter++; if (line.charAt(0) != '#') //Discarding any comments { try { //Tokenize the line final String[] tokens = pattern.split(line); final long source = Long.parseLong(tokens[0]); final long target = Long.parseLong(tokens[1]); queries.add(new VertexPair(source,target)); totalQueries++; } catch(NumberFormatException ex) { System.out.println("Error at line " + lineCounter + " : Could not parse. String was: " + line + ". Skipping line "); } } } br.close(); long tEnd = System.nanoTime(); System.out.println("Loaded " + totalQueries + " queries in " + Duration.ofNanos(tEnd - tStart).toMillis() + "ms"); if(totalQueries == 0) throw new QueryFileHandlerException("File does not contain any pair of nodes."); return queries; } catch (FileNotFoundException ex) { throw new QueryFileHandlerException("Invalid file path given."); } catch (IOException ex) { throw new QueryFileHandlerException("I/0 error occurred."); } } </code></pre> <p><strong>QueryFileHandlerException.java</strong></p> <pre><code>public class QueryFileHandlerException extends Exception { public QueryFileHandlerException(String message) { super(message); } } </code></pre> <p><strong>VertexPair.java</strong></p> <pre><code>public class VertexPair { private long sourceNode; private long targetNode; public VertexPair(long sourceNode, long targetNode) { this.sourceNode = sourceNode; this.targetNode = targetNode; } public long getSourceNode() { return sourceNode; } public long getTargetNode() { return targetNode; } } </code></pre> <p><strong>Part from a sample file <a href="http://snap.stanford.edu/data/soc-Epinions1.html" rel="nofollow noreferrer">soc-epinions1.txt</a></strong></p> <pre><code># Directed graph (each unordered pair of nodes is saved once): soc-Epinions1.txt # Directed Epinions social network # Nodes: 75879 Edges: 508837 # FromNodeId ToNodeId 0 4 0 5 0 7 0 8 0 9 0 10 0 11 0 12 0 13 0 14 0 15 0 16 0 17 </code></pre> <p>What is your opinion about this implementation ? Please suggest any enhancements that can be made.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:27:52.240", "Id": "465753", "Score": "0", "body": "A sample of the data in the file and what the expected return would be, will go a long way toward getting proper answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T19:08:38.873", "Id": "465760", "Score": "0", "body": "@tinstaafl edited." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T07:51:27.253", "Id": "237479", "Score": "2", "Tags": [ "java", "parsing", "graph", "breadth-first-search" ], "Title": "Parsing a Graph To Convert It Into Adjacency Lists And CSR And Then Make Connection Queries Using Bidirectional BFS" }
237479
<p>Suggestions to better understand when and how is convenient to use OPP.</p> <p><strong>This question is a follow-up question on <a href="https://codereview.stackexchange.com/questions/237322/oop-paradigm-in-python-extend-class-functionalities">this post</a>.</strong></p> <p>I have a script that reads an input file. In time, the script may be modified to account for new elements, that are directly added in the same input file. I would like to better understand how OOP paradigm can help to simplify this updating procedure.</p> <p>The code is written based on the suggestions from @Peilonrayz.</p> <p>Input file:</p> <pre><code>SIMPLY SUPPORTED BEAM NNODES&lt;NNnodes&gt;&lt;Node,X,Y&gt; 2 1,0,0 2,1,0 SECTIONS&lt;NSec&gt;&lt;Sec,Area,Inertia,Depth,ShearCF&gt; 1 1,100000,1,1,0 </code></pre> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations from dataclasses import dataclass @dataclass class Mesh: title: str nnode: NNode sections: Section @classmethod def load(cls, file): return cls( file.readline(), NNode.load(file), Section.load(file) ) _NNODE_KEYS = ['ID', 'x', 'y'] @dataclass class NNode: nodes: List[dict] @classmethod def load(cls, file): file.seek(0) while not file.readline().startswith('NNODES'): continue amount = int(file.readline()) values = [] for node in range(amount): values.append(dict(zip( _NNODE_KEYS, file.readline().split(',') ))) return cls(values) _SECTIONS_KEYS = ['Sec', 'Area', 'Inertia','Depth','ShearCF'] @dataclass class Section : sections: List[dict] @classmethod def load(cls, file): file.seek(0) while not file.readline().startswith('SECTIONS'): continue amount = int(file.readline()) values = [] for node in range(amount): values.append(dict(zip( _SECTIONS_KEYS, file.readline().split(',') ))) return cls(values) </code></pre> <p>Next, if the script is modified to handle more data, one can use inheritance.</p> <pre><code>SIMPLY SUPPORTED BEAM NNODES&lt;NNnodes&gt;&lt;Node,X,Y&gt; 2 1,0,0 2,1,0 SECTIONS&lt;NSec&gt;&lt;Sec,Area,Inertia,Depth,ShearCF&gt; 1 1,100000,1,1,0 MATERIALS&lt;NMat&gt;&lt;Mat,Young,Poisson,Thermal,Weight&gt; 1 1,30000000,0.3,0,0 </code></pre> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations from dataclasses import dataclass @dataclass class Mesh: title: str nnode: NNode sections: Section @classmethod def load(cls, file): return cls( file.readline(), NNode.load(file), Section.load(file) ) _NNODE_KEYS = ['ID', 'x', 'y'] @dataclass class NNode: nodes: List[dict] @classmethod def load(cls, file): file.seek(0) while not file.readline().startswith('NNODES'): continue amount = int(file.readline()) values = [] for node in range(amount): values.append(dict(zip( _NNODE_KEYS, file.readline().split(',') ))) return cls(values) _SECTIONS_KEYS = ['Sec', 'Area', 'Inertia','Depth','ShearCF'] @dataclass class Section : sections: List[dict] @classmethod def load(cls, file): file.seek(0) while not file.readline().startswith('SECTIONS'): continue amount = int(file.readline()) values = [] for node in range(amount): values.append(dict(zip( _SECTIONS_KEYS, file.readline().split(',') ))) return cls(values) @dataclass class Mesh_mat(Mesh): materials: Material @classmethod def load(cls, file): return cls( file.readline(), NNode.load(file), Section.load(file), Material.load(file) ) _MATERIAL_KEYS = ['Mat', 'Young', 'Poisson','Thermal','Weight'] @dataclass class Material : materials: List[dict] @classmethod def load(cls, file): file.seek(0) while not file.readline().startswith('MATERIALS'): continue amount = int(file.readline()) values = [] for node in range(amount): values.append(dict(zip( _MATERIAL_KEYS, file.readline().split(',') ))) return cls(values) </code></pre> <p>Anyway, I don't see any convenience in using this approach instead of simply modify the <code>Mesh</code> class.</p> <pre class="lang-py prettyprint-override"><code>from __future__ import annotations from dataclasses import dataclass @dataclass class Mesh: title: str nnode: NNode sections: Section materials: Material @classmethod def load(cls, file): return cls( file.readline(), NNode.load(file), Section.load(file), Material.load(file) ) _NNODE_KEYS = ['ID', 'x', 'y'] @dataclass class NNode: nodes: List[dict] @classmethod def load(cls, file): file.seek(0) while not file.readline().startswith('NNODES'): continue amount = int(file.readline()) values = [] for node in range(amount): values.append(dict(zip( _NNODE_KEYS, file.readline().split(',') ))) return cls(values) _SECTIONS_KEYS = ['Sec', 'Area', 'Inertia','Depth','ShearCF'] @dataclass class Section : sections: List[dict] @classmethod def load(cls, file): file.seek(0) while not file.readline().startswith('SECTIONS'): continue amount = int(file.readline()) values = [] for node in range(amount): values.append(dict(zip( _SECTIONS_KEYS, file.readline().split(',') ))) return cls(values) _MATERIAL_KEYS = ['Mat', 'Young', 'Poisson','Thermal','Weight'] @dataclass class Material : materials: List[dict] @classmethod def load(cls, file): file.seek(0) while not file.readline().startswith('MATERIALS'): continue amount = int(file.readline()) values = [] for node in range(amount): values.append(dict(zip( _MATERIAL_KEYS, file.readline().split(',') ))) return cls(values) </code></pre> <p>Since I don't have experience in OPP programming, which of these two approaches is better, if a different person who writes the code is asked to add modifications(like handles more data) ?</p> <p>The code can be further improved as @Peilonrayz said in the first question (while cycle and controls over the input data) but I would stay focused only on OOP improvements </p>
[]
[ { "body": "<p>Now that we have more classes we can start utilizing more OOP.\nAll the classe <code>NNode</code>, <code>Section</code> and <code>Material</code> have the <code>load</code> class method.\nThis means we can utilize inheritance to simplify the code using inheritance</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class LoadCSV:\n _FLAG: ClassVar[str] = ''\n _KEYS: ClassVar[Tuple[str, ...]] = ()\n\n @classmethod\n def load(cls, file):\n file.seek(0)\n while not file.readline().startswith(cls._FLAG):\n continue\n amount = int(file.readline())\n values = []\n for node in range(amount):\n values.append(dict(zip(\n cls._KEYS,\n file.readline().split(',')\n )))\n return cls(values)\n\n\n@dataclass\nclass NNode(LoadCSV):\n _FLAG = 'NNODES'\n _KEYS = ('ID', 'x', 'y')\n\n nodes: List[dict]\n\n\n@dataclass\nclass Section(LoadCSV):\n _FLAG = 'SECTION'\n _KEYS = ('Sec', 'Area', 'Inertia','Depth','ShearCF')\n\n sections: List[dict]\n\n\n@dataclass\nclass Material(LoadCSV):\n _FLAG = 'MATERIALS'\n _KEYS = ('Mat', 'Young', 'Poisson','Thermal','Weight')\n\n materials: List[dict]\n</code></pre>\n\n<blockquote>\n <p>Next, if the script is modified to handle more data, one can use inheritance.</p>\n</blockquote>\n\n\n\n<blockquote>\n <p>Anyway, I don't see any convenience in using this approach instead of simply modify the Mesh class.</p>\n</blockquote>\n\n\n\n<blockquote>\n <p>The code can be further improved as @Peilonrayz said in the first question (while cycle and controls over the input data) but I would stay focused only on OOP improvements</p>\n</blockquote>\n\n<p>No inheritance there sucks, much like the original <code>Mesh</code> class. Both of them are bad. You can see that they're bad, so you should give up on this OOP quest, and actually implement something of substance. Because OOP is a means to organize code not actually do something. \"Doing something in OOP\" may sound like OOPs doing all the work, but people should really say \"Doing something utilizing OOP\".</p>\n\n<p>You have gotten all the OOP improvements you can get. Since you only want OOP improvements, I can do no more.\nPlease further improve the code.</p>\n\n<ol>\n<li><p>Change <code>Mesh</code>, with the three loads, so that it can work on any of the provided files. If NNODES is there, or if it's not.</p>\n\n<p>If you make this change in <code>LoadCSV.load</code> then all of the other objects will automatically benifit from it.</p></li>\n<li>Remove <code>_KEYS</code> from the classes. Your file provides them, and what you're doing is unOOP like and just janky.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T10:19:41.813", "Id": "465695", "Score": "0", "body": "\"Because OOP is a means to organize code not actually do something\" is one of the key concept I was missing. The LoadCSV class is still a dataclass? P.S. I want only OOP improvements because I want to figure out the other problems by myself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T10:23:53.717", "Id": "465696", "Score": "1", "body": "@Stefano \"The LoadCSV class is stall a dataclass?\" No, because it doesn't have `@dataclass` before it. Also it doesn't make sense to make it a dataclass, as it has no attributes. It only has class variables, which probably wouldn't play ball if you make it a dataclass." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T10:00:51.773", "Id": "237484", "ParentId": "237481", "Score": "3" } } ]
{ "AcceptedAnswerId": "237484", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T08:58:27.907", "Id": "237481", "Score": "2", "Tags": [ "python", "object-oriented", "inheritance" ], "Title": "Read data from file: better approach using OOP" }
237481
<p>what is proper way to save all lines from text file to objects. I have .txt file something like this</p> <pre><code>0001Marcus Aurelius 20021122160 21311 0002William Shakespeare 19940822332 11092 0003Albert Camus 20010715180 01232 </code></pre> <p>From this file I know position of each data that is written in file, and all data are formatted.</p> <pre><code>Line number is from 0 to 3 Book author is from 4 to 30 Publish date is from 31 to 37 Page num. is from 38 to 43 Book code is from 44 to 49 </code></pre> <p>I made class Data which holds information about start, end position, value, error.</p> <p>Then I made class Line that holds list of type Data, and list that holds all error founded from some line. After load data from line to object Data I loop through lineError and add errors from all line to list, because I need to save errors from each line to database.</p> <p>My question is this proper way to save data from file to object and after processing same data saving to database, advice for some better approach? Is better approach to create custum attribute which holds position of every record? For this I can't use third party library.</p> <pre><code>public class Data { public int startPosition = 0; public int endPosition = 0; public object value = null; public string fieldName = ""; public Error error = null; public Data(int start, int end, string name) { this.startPosition = start; this.endPosition = end; this.fieldName = name; } public void SetValueFromLine(string line) { string valueFromLine = line.Substring(this.startPosition, this.endPosition - this.startPosition); // if else statment that checks validity of data (lenght, empty value) this.value = valueFromLine; } } public class Line { public List&lt;Data&gt; lineData = new List&lt;Data&gt;(); public List&lt;Error&gt; lineError = new List&lt;Error&gt;(); public Line() { AddObjectDataToList(); } public void AddObjectDataToList() { lineData.Add(new Data(0, 3, "lineNumber")); lineData.Add(new Data(4, 30, "bookAuthor")); lineData.Add(new Data(31, 37, "publishData")); lineData.Add(new Data(38, 43, "pageNumber")); lineData.Add(new Data(44, 49, "bookCode")); } public void LoadLineDataToObjects(string line) { foreach(Data s in lineData) { s.SetValueFromLine(line); } } public void GetAllErrorFromData() { foreach (Data s in lineData) { if(s.error != null) { lineError.Add(s.error); } } } } public class File { public string fileName; public List&lt;Line&gt; lines = new List&lt;Line&gt;(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T14:10:16.880", "Id": "465714", "Score": "0", "body": "`after processing same data saving to database` do you mean that currently you are processing the data to the database directly (from the file to the database), and now you need to adjust this process by adding extra layer to deserialize the data into objects and then you would adjust the old logic to let the database process from this object instead of the file, please clarify the current application cycle?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T14:33:56.860", "Id": "465716", "Score": "0", "body": "@iSR5 \"after processing same data saving to database\" under this I mean to validate data before saving them to database. For example I need to check if I have author data already inserted in database. If I don't have autor data in database I shouldn't save data to database until someone fill author data in database." } ]
[ { "body": "<p>from what I understood, you need a Model class, since you don't have one for the current data. I assume the file that holds the information is saved by other third-party application, and you're working on a middle-ware application in which would take that file and insert the data into the database. </p>\n\n<p>If possible, try to find another approach than reading the file and try parse each line of it to convert them into an object model. If the other end can process CVS, a table view from the database if any, or an API that would retrieve the information you need, these would be a much safer approaches. </p>\n\n<p>If there is no other way than reading the file and parsing each line. You can still do your idea, but hence, you must know that you need the replace both (the other end application, and this one) with an application that process the data better (combining both application processes into one). </p>\n\n<p>The class you need : </p>\n\n<pre><code>// Book Model\npublic class Book\n{\n // position start index: 0 \n // Length: 4\n public int LineNumber { get; set; }\n\n // position start index: 4 \n // Length: 25\n public string Author { get; set; }\n\n // position start index: 29\n // Length: 8 \n public DateTime Publish { get; set; }\n\n // position start index: 37\n // Length: 5\n public int PageNumber { get; set; }\n\n // position start index: 43\n // Length: 5\n public string Code { get; set; }\n\n public Book(string line)\n {\n // normal validation\n if (string.IsNullOrEmpty(line)) { throw new ArgumentNullException(nameof(line)); }\n\n // business validation \n if (line.Length != 48) { throw new InvalidOperationException(nameof(line)); }\n\n LineNumber = int.TryParse(ParseValue(line, 0, 4), out int lineResult) ? lineResult : -1;\n\n Author = ParseValue(line, 4, 25);\n\n Publish = DateTime.TryParse(ParseValue(line, 29, 8), out DateTime publishResult) ? publishResult : DateTime.MinValue;\n\n PageNumber = int.TryParse(ParseValue(line, 37, 5), out int pageResult) ? pageResult : -1;\n\n Code = ParseValue(line, 43, 5);\n }\n\n private string ParseValue(string line, int startIndex, int endIndex)\n {\n // get \n var value = line.Substring(startIndex, endIndex).Trim();\n\n // check if is it a white space return null \n // we need to discard whitespace initialization.\n // this could be a business requirment where all data should have real data \n // if this is a requirment, then throw an exception instead of null\n if (value.Length == 0) { return null; }\n\n return value;\n }\n}\n</code></pre>\n\n<p>Then, you stream the file and create a <code>Book</code> from each line or implement <code>GetBooks</code> method example : </p>\n\n<pre><code>public IEnumerable&lt;Book&gt; GetBooks(string filePath)\n{\n if(string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException(nameof(filePath)); }\n\n using (var fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n using (var bs = new BufferedStream(fs))\n using (var sr = new StreamReader(bs))\n {\n string line;\n while ((line = sr.ReadLine()) != null)\n {\n yield return new Book(line);\n }\n }\n}\n</code></pre>\n\n<p>then you could do this : </p>\n\n<pre><code>var books = GetBooks(@\"filepath\");\n\nforeach(var book in books)\n{\n // do something with each book object. \n}\n</code></pre>\n\n<p>or you can use <code>LINQ</code> if you need as well.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Since you're looking for using <code>Attribute</code> you need to keep in mind, using attributes would put more work on your hands, as you would define them, and use <code>Reflection</code> to access its values, which would add more processing time to your code performance.</p>\n\n<p>To create a new custom attribute you can do this : </p>\n\n<pre><code>/// &lt;summary&gt;\n/// Implement StringPosition custom attribute\n/// To define the start position and the length of the extracted string\n/// &lt;/summary&gt;\n[AttributeUsage(AttributeTargets.Property)]\npublic class StringPositionAttribute : Attribute\n{\n public int StartPosition { get; set; }\n\n public int Length { get; set; }\n\n public StringPositionAttribute(int startPosition, int endPosition)\n {\n StartPosition = startPosition;\n Length = endPosition;\n }\n}\n</code></pre>\n\n<p>Now, you can use <code>[StringPosition(startIndex, length)]</code> attribute on the class properties. </p>\n\n<p>Example :</p>\n\n<pre><code>// Book Model\npublic class Book\n{\n [StringPosition(0, 4)]\n public int LineNumber { get; set; }\n\n [StringPosition(4, 25)]\n public string Author { get; set; }\n\n [StringPosition(29, 8)]\n public DateTime Publish { get; set; }\n\n [StringPosition(37, 5)]\n public int PageNumber { get; set; }\n\n [StringPosition(43, 5)]\n public string Code { get; set; }\n}\n</code></pre>\n\n<p>now, by doing this, we can create a method where it loop over all of these properties and extract the targeted string based on the values of their attributes, then save the results for each. </p>\n\n<pre><code>private void ParseValues(string line)\n{\n foreach(var property in this.GetType().GetProperties())\n {\n // Get property attribute\n var attribute = (StringPositionAttribute)property.GetCustomAttribute(typeof(StringPositionAttribute));\n\n // Get the start index value from the attribute\n var startIndex = attribute.StartPosition;\n\n // Get the length value from the attribute\n var length = attribute.Length;\n\n // parse the values to get the string\n var value = ParseValue(line, startIndex, length);\n\n // set the value of the property for this instance\n property.SetValue(this, Convert.ChangeType(value, property.PropertyType), null);\n }\n}\n</code></pre>\n\n<p>now use this method in the constructor : </p>\n\n<pre><code>public Book(string line)\n{\n // normal validation\n if (string.IsNullOrEmpty(line)) { throw new ArgumentNullException(nameof(line)); }\n\n // business validation \n if (line.Length != 48) { throw new InvalidOperationException(nameof(line)); }\n\n // do the parsing\n ParseValues(line);\n}\n</code></pre>\n\n<p>this is a quick examples to give you a boost start, the attribute can be useful in many cases, such as validation, or messages ..etc. But I believe your work does not need that much of work.</p>\n\n<p>I hope this would give you the boost you need. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:36:27.800", "Id": "465754", "Score": "0", "body": "thank you for your explanation and approach, I don't have too much experience in c# but I would try to add custom attribute for specifying start and end position for specific data, I don't know if it is possible but I will try, your example are simple and good for me :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T19:33:42.673", "Id": "465766", "Score": "1", "body": "@Anve I have updated the answer with the attribute solution, I hope it would be useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T20:31:00.010", "Id": "465782", "Score": "0", "body": "thank you that is what I looking for, now I need to made some method for validating my data, because I need to validate if I have data about author in database, and other data. I will post my method tomorrow to see if there are possible enhancements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T21:34:20.423", "Id": "465789", "Score": "0", "body": "@Anve In `ParseValue` method the condition `if (value.Length == 0) ` would cover the whitespace part, so if any of these data returns whitespace it would or the whole line is null, then it would return null for that specific part or line, so in your validation method, you start by checking nulls for `string`, and for `-1` for `int` properties. then do the rest required validation on each non-null properties." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T17:25:09.863", "Id": "237501", "ParentId": "237485", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T10:03:19.383", "Id": "237485", "Score": "3", "Tags": [ "c#" ], "Title": "What would be proper way to store data from file and validate data from file" }
237485
<p>My goal was to create a portfolio site for my motion design work. The website should be modern and intuitive, yet pose a good gallery. Please also comment on the dark mode functionality and responsiveness.</p> <p>The full website is hosted under <a href="http://timlwsk.bplaced.net" rel="nofollow noreferrer">timlwsk.bplaced.net</a> (good domain coming soon). The contact form isn't working yet.</p> <p><strong>index.html</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en" dir="ltr"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name=”viewport” content=”width=device-width,initial-scale=1″&gt; &lt;script src="https://kit.fontawesome.com/43017aa80c.js" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha256-pasqAKBDmFT4eHoN2ndd6lN370kFiGUFyTiUHWhU7k8=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;link href="https://fonts.googleapis.com/css?family=Chivo&amp;display=swap" rel="stylesheet"&gt; &lt;link rel="stylesheet" href="./css/master.css"&gt; &lt;title&gt;timlwsk&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="item header" id="header-l"&gt; &lt;h1&gt;timlwsk&lt;/h1&gt; &lt;/div&gt; &lt;div class="item header" id="header-r"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#contact"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;span title="Twitter"&gt;&lt;a href="https://twitter.com/timlwsk" target="_blank"&gt;&lt;i class="fab fa-twitter"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;span title="Instagram"&gt;&lt;a href="https://instagram.com/lwskdesign" target="_blank"&gt;&lt;i class="fab fa-instagram"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;span title="Unsplash"&gt;&lt;a href="https://unsplash.com/@lwskphotography" target="_blank"&gt;&lt;i class="fa fa-camera"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;span title="Reddit"&gt;&lt;a href="https://reddit.com/u/timlwsk" target="_blank"&gt;&lt;i class="fab fa-reddit-alien"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;span title="Toggle Dark Mode"&gt;&lt;a href="#" onclick="darkMode()"&gt;&lt;i class="fas fa-moon"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="gallery"&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/15.jpg" title="everybody gets high" alt="gallery image 15"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/14.jpg" title="spilt blood" alt="gallery image 14"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/13.jpg" title="drippin' gold" alt="gallery image 13"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/12.jpg" title="suffocated (white)" alt="gallery image 12"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/11.jpg" title="suffocated (black)" alt="gallery image 11"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/10.jpg" title="hannover" alt="gallery image 10"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/09.jpg" title="head in the clouds" alt="gallery image 09"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/08.jpg" title="arm" alt="gallery image 08"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/07.jpg" title="wilted" alt="gallery image 07"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/06.jpg" title="Honey, I am drowning" alt="gallery image 06"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/05.jpg" title="discobolus" alt="gallery image 05"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/04.jpg" title="AF1" alt="gallery image 04"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/03.jpg" title="sadness" alt="gallery image 03"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/02.jpg" title="happiness" alt="gallery image 02"&gt;&lt;/div&gt; &lt;div class="img-wrapper"&gt;&lt;img src="./images/01.jpg" title="嗳 (Love)" alt="gallery image 01"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="contact" id="contact"&gt; &lt;form class="contact-form" action="email.php" method="post"&gt; &lt;label for="name"&gt;Your Name&lt;/label&gt; &lt;input type="text" name="name"&gt; &lt;label for="email"&gt;Your Email&lt;/label&gt; &lt;input type="text" name="email"&gt; &lt;label for="message"&gt;Your Messages&lt;/label&gt; &lt;textarea name="messahge"&gt;&lt;/textarea&gt; &lt;input type="submit"&gt;&lt;/input&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="footer"&gt; &lt;p&gt;Copyright 2020&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="./js/darkmode.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>master.css</strong></p> <pre class="lang-css prettyprint-override"><code>/* grid-area: &lt;name&gt; | &lt;row-start&gt; / &lt;column-start&gt; / &lt;row-end&gt; / &lt;column-end&gt;; */ :root, [data-theme="light"] { --bg-color: #ffffff; --bg-color-inv: #000000; --outline-color: #000000; --text-primary: #000000; --text-primary-inv: #ffffff; --text-secondary: #a4a4a4; --text-secondary-hover: #000000; --chivo: 'Chivo', sans-serif; } [data-theme="dark"] { --bg-color: #121212; --bg-color-inv: #dadada; --outline-color: #dadada; --text-primary: #dadada; --text-primary-inv: #000000; --text-secondary: #919191; --text-secondary-hover: #dadada; } html { margin: 0; padding: 0; font-family: 'Chivo', sans-serif; color: var(--text-primary); background-color: var(--bg-color); font-size: 100%; scroll-behavior: smooth; } /* Transitions */ html, #header-r ul li a:link, #header-r ul li a:visited, #header-r ul li a:hover, input[type=submit], input[type=submit]:hover, html { -webkit-transition: .5s; -moz-transition: .5s; -o-transition: .5s; transition: .5s; } .container { display: grid; grid-template-columns: 10% auto 10%; grid-template-rows: auto; } #header-l { grid-area: 1/2/1/2; justify-self: left; align-self: center; margin-top: 5%; margin-bottom: 5%; } #header-r { grid-area: 1/2/1/2; justify-self: right; align-self: center; } #header-r ul li { list-style: none; float: left; margin-left: 22px; } #header-r ul li a:link, #header-r ul li a:visited { color: var(--text-secondary); text-decoration: none; text-transform: uppercase; } #header-r ul li a:hover { color: var(--text-secondary-hover); } .gallery { font-size: 0; grid-column: 2/2; } .img-wrapper { width: calc(100%/1); display: inline-block; } .img-wrapper img { max-width: 100%; max-height: 100%; } .contact { grid-area: 3/2/3/2; justify-self: center; align-self: center; width: calc(2/3); margin-top: 10%; } label { font-size: 100%; display: inline-block; } input[type=text], textarea{ margin-bottom: 30px; } input[type=text], input[type=submit], select, textarea { font-size: 100%; font-family: var(--chivo); border: 1px solid var(--outline-color); width: 100%; background-color: var(--background-color); padding: 10px; border-radius: 2px; box-sizing: border-box; -moz-box-sizing: border-box; color: var(--text-primary); } input[type=submit]:hover { background-color: var(--bg-color-inv); color: var(--text-primary-inv); } textarea { height: 20vh; } .footer { grid-area: 4/2/4/2; justify-self: center; align-self: center; margin-top: 5%; margin-bottom: 5%; } @media (min-width: 1080px) /* Large Devices */ { html { font-size: 1rem; } .img-wrapper { width: calc(100%/3); } } @media (min-width: 2560px) /* Large Devices */ { html { font-size: 1.25rem; } .img-wrapper { width: calc(100%/5); } } </code></pre> <p><strong>darkmode.js</strong></p> <pre class="lang-js prettyprint-override"><code>var isOn = false; function darkMode () { document.documentElement.setAttribute('data-theme', ['dark', 'light'][+isOn]); isOn = !isOn; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T16:09:05.270", "Id": "465733", "Score": "1", "body": "Is the code posted in the question working? If so remove the comment about the contact form which makes the question off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T16:10:24.803", "Id": "465734", "Score": "0", "body": "Just an FYI, if you are first starting out with a new website, then a content management system such as WordPress or Drupal is a better way to go. There will be a lot less code required to implement it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T17:14:26.743", "Id": "465736", "Score": "0", "body": "@BCdotWEB done, I edited the title!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T17:14:29.723", "Id": "465737", "Score": "0", "body": "@pacmaninbw Sorry, but I am not quite sure why the question becomes off-topic, when I state that a part of the website isn't coded yet. Furthermore, I love to code but thanks for the tip!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T17:55:03.770", "Id": "465740", "Score": "1", "body": "To explain why a comment about the code not working would make the question off-topic please see our help center on how to ask a good question. https://codereview.stackexchange.com/help. Content management systems simply reduce the amount of code necessary, they don't remove the need for code unless the site doesn't do anything. I can code in HTML, CSS and JavaScript, but if I was starting a new website I would use a content management system to reduce the amount of work." } ]
[ { "body": "<p>First of all: good job! I like the simple layout and only-one-breakpoint-design. But like always there are some little things I would change.</p>\n\n<h1>1 <a href=\"https://www.w3schools.com/html/html5_semantic_elements.asp\" rel=\"nofollow noreferrer\">HTML5 Semantic Elements</a></h1>\n\n<p>Tell your browser what is a header, section, footer and so on.</p>\n\n<pre><code>&lt;header&gt;\n &lt;div class=\"container\"&gt;\n &lt;div class=\"center-vertically justify-space-between\"&gt;\n &lt;div&gt;Logo&lt;/div&gt;\n &lt;div&gt;Stuff&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/header&gt;\n&lt;section id=\"gallery\" class=\"panel\"&gt;\n &lt;div class=\"container\"&gt;\n &lt;div class=\"grid grid-3-3-3\"&gt;\n &lt;div class=\"grid-item\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/div&gt;\n &lt;div class=\"grid-item\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/div&gt;\n &lt;div class=\"grid-item\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/div&gt;\n &lt;div class=\"grid-item\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/div&gt;\n &lt;div class=\"grid-item\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/div&gt;\n &lt;div class=\"grid-item\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/div&gt;\n &lt;div class=\"grid-item\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/div&gt;\n &lt;div class=\"grid-item\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/div&gt;\n &lt;div class=\"grid-item\"&gt;&lt;img src=\"\" alt=\"\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/section&gt;\n&lt;section id=\"contact\"&gt;\n &lt;div class=\"container\"&gt;\n &lt;form action=\"\"&gt;&lt;/form&gt;\n &lt;/div&gt;\n&lt;/section&gt;\n&lt;footer id=\"footer\"&gt;\n &lt;div class=\"container\"&gt;\n &lt;/div&gt;\n&lt;/footer&gt;\n</code></pre>\n\n<h1>2 Grid</h1>\n\n<p>I think it isn't necessary to make your whole container a CSS grid. I think it makes it harder to build on top of it/less scalable. For example if, at some point, you would like to add a full width section you would need to work with negative margins. Of course this is possible, but I think it is kind of \"hacky\". I would suggest to use a container class in every section. That way there would be no problem to add a full width section without the container class in the future. These programmers... always trying to predict the future...</p>\n\n<p>Also, if you like to expand your knowledge, you could have a look at Sass. It helps you to keep your CSS modular. Here is an example how I use Sass. I know you didn't ask for that, but I hope it is interesting for you nonetheless\n.</p>\n\n<p><strong>variables.sass</strong></p>\n\n<pre><code>// TYPOGRAPHY\n$primaryFont: 'Public Sans', 'Helvetica', Arial, sans-serif\n$secondaryFont: 'Public Sans', 'Helvetica', Arial, sans-serif\n$baseTextSize: 1.6rem\n$textColor: #222\n\n// MARGINS\n$margin: 2rem\n$margin-2: 4rem\n\n// BREAKPOINTS\n$mobileS: \"max-width: 374px\"\n$mobileM: \"min-width: 375px\"\n$tablet: \"min-width: 768px\"\n</code></pre>\n\n<p><strong>layout.sass</strong></p>\n\n<pre><code>.container\n margin: 0 auto\n\n@media($mobileS)\n .container\n width: 100%\n\n@media($tablet)\n .container\n width: 700px\n</code></pre>\n\n<p><strong>helper-classes.sass</strong></p>\n\n<pre><code>.justify-space-between\n display: flex\n justify-content: space-between\n\n.center-vertically\n display: flex\n align-items: center\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-27T20:28:04.523", "Id": "466889", "Score": "0", "body": "Hi Dennis! Thank you for your feedback, I really appreciate it! I actually tried to have a look at Sass but was quickly turned down by the lack of good-looking apps for windows. Do you got any recommendations (using atom atm)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-27T22:46:21.217", "Id": "466913", "Score": "0", "body": "I'm not on Windows, so I don't really know what is popular there. But maybe this might help you: https://atom.io/packages/sass-autocompile" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-26T19:02:19.163", "Id": "237997", "ParentId": "237491", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T12:05:53.093", "Id": "237491", "Score": "3", "Tags": [ "javascript", "html", "css" ], "Title": "HTML/CSS Gallery Website | Feedback on design and code" }
237491
<p>I've found an explanation on Wikipedia on <a href="https://en.wikipedia.org/wiki/International_Bank_Account_Number#Algorithms" rel="noreferrer">how to validate an IBAN</a>. Since the number generated from the transformation can cause overflow with all data types available in VBA, I've worked with <code>String</code>.</p> <p>I'd like to have someone else review. Thanks in advance!</p> <p>From Wikipedia:</p> <ol> <li>Check that the total IBAN length is correct as per the country. If not, the IBAN is invalid .</li> <li>Move the four initial characters to the end of the string .</li> <li>Replace each letter in the string with two digits, thereby expanding the string, where A = 10, B = 11, ..., Z = 35.</li> <li>Interpret the string as a decimal integer and compute the remainder of that number modulo 97.</li> </ol> <pre><code>Public Function isValidIBAN(IBAN As String) As Boolean isValidIBAN = False Dim Country As String Dim CountryLenght As Integer Dim tempStr As String Dim c As String Dim o As Long Dim newStr As Variant Const Modder As Integer = 97 If IBAN = vbNullString Then Exit Function Country = Left(IBAN, 2) CountryLenght = 0 On Error Resume Next CountryLenght = Application.WorksheetFunction.VLookup(Country, Foglio3.Range("A:D"), 4, 0) 'This Search in a table --- Country|someVal|someVal|IBAN lenght On Error GoTo 0 If Len(IBAN) &lt;&gt; CountryLenght Then Exit Function 'move first 4 chars to right tempStr = Right(IBAN, Len(IBAN) - 4) &amp; Left(IBAN, 4) 'loop throught single char in tempStr and if not numeric return 10 based number from letter 'use string in place of number to store new-generated "IBAN" For o = 1 To Len(tempStr) c = Mid(tempStr, o, 1) If Not IsNumeric(c) Then newStr = newStr &amp; CStr(Range(c &amp; 1).Column + 9) Else newStr = newStr &amp; CStr(c) End If Next o c = vbNullString ' perform primary school' style division - digit by digit For o = 1 To Len(newStr) c = c &amp; Mid(newStr, o, 1) myStr = myStr &amp; CStr(Int(CLng(c) / Modder)) 'if is the last char in str check if mod is 1 - Only fired once If o = Len(str) Then isValidIBAN = ((CLng(c) Mod Modder) = 1) Exit Function End If c = IIf(CLng(c) &lt; Modder, c, CLng(c) Mod Modder) Next o End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T13:12:36.590", "Id": "465710", "Score": "0", "body": "Micro-review - misspelt `CountryLength`." } ]
[ { "body": "<p>On first sight, your code looks reasonably short. Nevertheless, no matter how short the code is, there's always something to improve.</p>\n\n<p>The function name and signature are perfect. I though about passing the string as <code>ByVal</code>, but that might be less efficient since the string might have to be copied then.</p>\n\n<p>Initializing the return value of the function to <code>False</code> at the very beginning is good style. For a function that validates something, any accidental return should say \"not valid\". This is a commonly found pattern, especially in security-related code.</p>\n\n<p>Some of the variable names start with an uppercase letter and some with a lowercase letter. I don't see any reason to mix these two styles. You should either start all variable names with an uppercase letter, or all with a lowercase letter.</p>\n\n<p>Typo: <code>Lenght</code> should be <code>Length</code> instead. It seems the Microsoft IDE lacks a spell checker. That should really be fixed on Microsoft's side.</p>\n\n<p>The variable name <code>tempStr</code> does not say much about the purpose of that variable. A better name would be <code>ReorderedIBAN</code>.</p>\n\n<p>The variable name <code>o</code> is strange as well. For cases like here, the variable name <code>i</code> is more common. This name is an abbreviation for <code>index</code>.</p>\n\n<p>The variable name <code>newStr</code> is confusing because its type is not <code>String</code> but <code>Variant</code>.</p>\n\n<p>After each line containing <code>Exit Function</code>, I would put an empty line, to start a new paragraph. This groups the code lines more logically.</p>\n\n<p>It's unfortunate that this simple function needs a whole spreadsheet just to look up the IBAN length by country name. I'd rather encode all the length requirements in a single string, like this:</p>\n\n<pre><code>' See https://en.wikipedia.org/wiki/International_Bank_Account_Number#IBAN_formats_by_country\nLengthByCountry = \"AL28 AN24 AT20 AZ28 BH22 ...\"\n</code></pre>\n\n<p>Given this string, you could search like this:</p>\n\n<pre><code>LengthIndex = Index(LengthByCountry, Left(IBAN, 2))\nIf LengthIndex Mod 5 &lt;&gt; 1 Then Exit Function\n\nCountryLength = Mid(LengthByCountry, LengthIndex + 2, 2)\nIf Len(IBAN) &lt;&gt; CountryLength Then Exit Function\n</code></pre>\n\n<p>And if you made it this far, you could also validate that the IBAN matches the BBAN Format that is given in the Wikipedia article.</p>\n\n<p>When you loop over the characters of the <code>ReorderedIBAN</code>, you use a spreadsheet lookup again. I'm sure VBA has a built-in function for getting the character code from the first character of a string, but I couldn't find it. Usually it is called <code>ASC</code>, <code>ORD</code>, <code>CODE</code>.</p>\n\n<p>Instead of creating new strings all the time, you could also do the <code>Mod 97</code> math directly on the digits as you convert them. The idea is:</p>\n\n<pre><code>Result = 0\nFor i = 1 To Len(ReorderedIBAN)\n ch = Mid(ReorderedIBAN, i, 1)\n\n If IsNumeric(ch) Then\n n = Asc(ch) - Asc(\"0\")\n Else\n n = Asc(ch) - Asc(\"A\") + 10\n If n &lt; 1 Or n &gt; 26 Then Exit Function\n End If\n\n If Result &lt; 10 Then\n Result = (10 * Result + n) Mod 97\n Else\n Result = (100 * Result + n) Mod 97\n End If\nNext i\n</code></pre>\n\n<p>The above code takes care not to use strings but rather only simple arithmetic operations, since the latter are usually faster than string operations.</p>\n\n<p>Your code currently may or may not handle lowercase letters correctly. That depends on the part of the Excel spreadsheet that you omitted from your question. If in doubt, just call <code>UCase</code> on the <code>ReorderedIBAN</code> before looping over it.</p>\n\n<p>To ensure your code works as intended, you should place a <code>Sub TestIsValidIban</code> next to it that contains example IBANs and whether they validate or not. If any of them does not validate, an error should occur. Or does VBA have a unit test framework? Then, use that instead. Have a look at this <a href=\"https://rosettacode.org/wiki/IBAN#VBA\" rel=\"noreferrer\">example code at Rosetta Code</a>, which contains a half-automatic test; you still have to inspect its output manually.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T19:04:35.137", "Id": "465759", "Score": "1", "body": "Would using the lookup string not hurt maintainability? I expect that the values will change - if only because new countries come into existence." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T19:11:11.673", "Id": "465762", "Score": "2", "body": "I weighed the maintainability cost against having to copy the two spreadsheet areas into every VBA application where you want to use the IBAN validator. Having all the code in a single place sounded more maintainable and error-proof than having to update the validation code from time to time." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:56:44.933", "Id": "237507", "ParentId": "237492", "Score": "5" } } ]
{ "AcceptedAnswerId": "237507", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T12:39:19.723", "Id": "237492", "Score": "8", "Tags": [ "vba", "validation" ], "Title": "Validate an IBAN" }
237492
<p>I have a working solution to my problem, but I'm less than satisfied with the result, both when it comes to style and performance.</p> <p>In short, I need to be able to shift 256 bits of data, say an array of 4 64 bit integer, by n bit, right and left. If other type are easier to work with for some reason, it's really all the same to me.</p> <p>My current implementation, which seems to work:</p> <pre><code>void shl( uint64_t * const b, uint_fast8_t n ) { for( int i = 3-(n/64); i &gt;= 0 &amp;&amp; n &gt;=64; --i ) b[i+n/64] = b[i]; for( int i = n/64-1; i &gt;= 0; --i) b[i] = 0; for( int_fast8_t i = 3; i &gt; 0 &amp;&amp; (n%64); --i ) b[i] = (b[i] &lt;&lt; (n%64)) | (b[i-1] &gt;&gt; (64-(n%64))); b[0] &lt;&lt;= n%64; } void shr( uint64_t * const b, uint_fast8_t n ) { for( int i = 0; i &lt; 4-(n/64) &amp;&amp; n &gt;=64; ++i ) b[i] = b[i+n/64]; for( int i = 4-n/64; i &lt; 4; ++i ) b[i] = 0; for( int i = 0; i &lt; 3 &amp;&amp; (n%64); ++i ) b[i] = (b[i] &gt;&gt; (n%64)) | (b[i+1] &lt;&lt; (64-(n%64))); b[3] &gt;&gt;= n%64; } </code></pre> <p>I have no need for a general solution, and in case it matters, I need not shift more than 192 bits in a given direction.</p> <p>Anyway, what I have made, is absolutely awful. I have been searching for alternatives, but what little I've found has been limited to work within the width of the chosen type, in this case 64, or it has simply not been working. I'm sure the above can be optimized, but frankly, I'd prefer a different solution all together.</p> <p>My first thought was to mess around with pointers, but I have yet to come up with with how that would actually work, so I've got nothing.</p> <p>I would very much appreciate any ideas.</p> <p>Also, I did just find one mistake, which has been corrected, so there may be more.</p> <p>Update: Another approach, that is really the same, though slightly more efficient:</p> <pre><code>void shl( uint64_t * const b, const uint_fast8_t n ) { // If n != 0, we run through the 4 elements descending. for( int i = 3; n &amp;&amp; i &gt;= 0; --i ) // Do we need to assign current element a value? if( i &gt;= n/64 ) { b[i] = b[i - n/64] &lt;&lt; ( n%64 ); // Check to avoid OOB and special case where n is a multiple of 64. if( i &gt; n/64 &amp;&amp; n%64 ) b[i] |= b[i - n/64 - 1] &gt;&gt; ( 64 - ( n%64 ) ); } // if not, value should be zero. else b[i] = 0; } void shr( uint64_t * const b, const uint_fast8_t n ) { // If n != 0, we run through the 4 elements ascending. for( int i = 0; n &amp;&amp; i &lt; 4; ++i ) // Do we need to assign current element a value? if( i &lt; 4 - n/64 ) { b[i] = b[i + n/64] &gt;&gt; ( n%64 ); // Check to avoid OOB and special case where n is a multiple of 64. if( i &lt; 4 - n/64 - 1 &lt; 4 &amp;&amp; n%64 ) b[i] |= b[i + n/64 + 1] &lt;&lt; ( 64 - ( n%64 ) ); } // if not, value should be zero. else b[i] = 0; } </code></pre> <p>It seems to work, and unlike the other version, I can live with this, but still, there must be another way.</p>
[]
[ { "body": "<p>Stylistic (not asked) the wording can be more to the point. Sometimes that gives an optimisation idea.</p>\n\n<p>Much elegance one might not expect, shifting in arrays in C. But I did find a spot.</p>\n\n<p>As such:</p>\n\n<pre><code>void shl(uint8_t * const words, uint_fast_t n) {\n const int word_bits = 8;\n const int word_count = 256 / word_bits;\n const int word_shift = n / word_bits;\n const int bit_shift = n % word_bits;\n if (word_shift != 0) {\n for (int i = word_count - 1 - word_shift; i &gt;= 0; --i) { // Or memcpy\n words[i + word_shift] = words[i];\n }\n for (int i = word_shift - 1; i &gt;= 0; --i) { // Or memset\n words[i] = 0;\n }\n }\n uint8_t carry = 0;\n uint8_t mask = (1 &lt;&lt; word_bits) - 1;\n for (int_fast8_t i = word_shift; i &lt; word_count; ++i) {\n uint8_t m = carry;\n carry = (words[i] &gt;&gt; (word_bits - bit_shift)) &amp; mask;\n words[i] = (words[i] &lt;&lt; bit_shift) | m;\n }\n}\n</code></pre>\n\n<p>As you see I replaced one decreasing loop + plus handling of <code>[0]</code> with a single increasing loop with a <code>carry</code>.</p>\n\n<p>I used uint8_t instead of uint64_t (which is generally is faster), as the <code>carry</code> could then be done inside a larger uint16_t:</p>\n\n<pre><code> uint16_t carry = 0;\n uint16_t mask = (1 &lt;&lt; word_bits) - 1;\n for (int_fast8_t i = word_shift; i &lt; word_count; ++i) {\n uint8_t m = carry;\n carry = ((uint16_t)words[i]) &lt;&lt; bit_shift;\n words[i] = ((uint8)carry) | m;\n carry &gt;&gt;= bits_shift;\n }\n</code></pre>\n\n<p>This is my spotted \"improvement\" (which has to be proven by timing).</p>\n\n<p><code>uint32_t</code> instead of <code>uint64_t</code> would be a middle way.</p>\n\n<p>Which is realy faster has to be determined.</p>\n\n<p>By the way in C++'s <code>std::bitset</code> would be more elegant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T13:53:15.373", "Id": "465874", "Score": "0", "body": "Ya, std::bitset would be a nice to have, but then again, not really practical for my final use case, I think.\nI'll taker a closer look at your code later. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T16:02:29.670", "Id": "465894", "Score": "0", "body": "I've looked over your code now, and it looks very much like one of the examples I've found online, although I'm sure this actually works.\nStill I must admit that I much prefer my own second attempt, though I still intent to look into to more... exotic methods, at some point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T16:08:26.310", "Id": "465897", "Score": "0", "body": "Yes, one cannot win here, in contrast to gcd and other algorithmic things. At least memmove/memset might be a thought." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T10:17:00.527", "Id": "466263", "Score": "0", "body": "You don't need the mask in the first example, and don't even use it in the second, it seems." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T13:01:56.663", "Id": "237561", "ParentId": "237506", "Score": "3" } }, { "body": "<p>I tried to improve upon your second version, incorporating some changes of @JoopEggen and some of my own:</p>\n\n<h1>Word out ideas</h1>\n\n<p>As already pointed out, it can help much to simply define variables holding the values you will use later, eg. <code>word_shift</code>, etc. This does not cost any computation (or storage) time with any barely decent compiler but helps tremendously when thinking about the problem.</p>\n\n<h1>Use braces</h1>\n\n<p>I know, you didn't ask for code style improvements, but braces don't hurt either and having a multiline if-else within a for-loop without delimiting it with braces is not nicely readable and also often a source for future bugs.</p>\n\n<h1>Be explicit, write obvious code</h1>\n\n<p>Using <code>n &amp;&amp; i &gt;= 0</code> in the for loop just gives extra reading burden to the programmer. If I see a condition within the loop head I think about why it's checked every iteration. I wrote instead:</p>\n\n<pre><code>if (n == 0) { return; }\n\nfor ( /* ... */ )\n</code></pre>\n\n<p>And I removed the comment as now the code is, indeed, self-documenting and obvious and the comment basically redundant.</p>\n\n<h1>Split the loop, move the if-statement outside</h1>\n\n<p>The <code>if</code> within the loop basically checks, whether we're already done shifting words and can begin filling up with zero. There's a neat way to do that (IMHO):</p>\n\n<p></p>\n\n<pre><code>// Shift values into next word\nint i;\nfor (i = num_words-1; i &gt;= word_shift; i--) {\n // move word\n b[i] = b[i - word_shift] &lt;&lt; bit_shift;\n // move leftover carried bits\n if (i != word_shift) {\n b[i] |= b[i-word_shift - 1] &gt;&gt; (word_bits - bit_shift);\n }\n}\n// Fill in zeroes\nfor (; i &gt;= 0; i--) {\n b[i] = 0;\n}\n</code></pre>\n\n<p>I move the iterator declaration outside of the loop and instead of counting til zero, I count to <code>word_shift</code> for moving the values and then have a separate loop filling up the remaining bits. Now the loop body doesn't have different meanings in different iterations, making it easier to model in your head.</p>\n\n<p>I also removed the special case where <code>n</code> is a multiple of 64 since it doesn't matter for the semantics of the code and I doubt there's any gain performance-wise for that. If you want to keep it in, I'd rephrase it to <code>n % 64 == 0</code> because here, as well, being more explicit doesn't hurt. Usually good choice of style is to emit the <code>x == 0</code> check in cases where you want to check a Boolean, such as:</p>\n\n<pre><code>int flag = 0;\n/* ... */\nif (flag) { }\n</code></pre>\n\n<p>or the \"existence\" of a pointer:</p>\n\n<pre><code>int *p;\n/* ... */\nif (!p) { /* read: if p \"doesn't exist\" */\n /* ... */\n}\n</code></pre>\n\n<p>If you want to check whether an integer holds zero, use <code>x == 0</code>, just as you would compare to 42 using <code>x == 42</code>. While, to the compiler, it's equivalent, to the reader it eases understanding.</p>\n\n<h1>Don't hardcode values</h1>\n\n<p>Now it's easy to \"generalize\" your function, if you want to. Using <code>sizeof</code>, <code>CHAR_BIT</code> and an additional argument to your function, it can process any bitset that is a multiple of 64 Bits (one could now implement the same function using <code>uint8_t</code> instead to allow almost any-sized bitsets and use it instead or as a fallback function called from this, if `bits % word_bits !=</p>\n\n<pre><code>void shl(uint64_t *const b, const uint16_t bits, const uint_fast8_t n)\n{\n const uint8_t word_bits = sizeof (b[0]) * CHAR_BIT;\n const uint8_t word_shift = n / word_bits;\n const uint8_t bit_shift = n % word_bits;\n\n const uint8_t num_words = bits/word_bits;\n assert(bits % word_bits == 0);\n}\n</code></pre>\n\n<h1>Putting it together</h1>\n\n<pre><code>void shl(uint64_t *const b, const uint16_t bits, const uint_fast8_t n)\n{\n const uint8_t word_bits = sizeof (b[0]) * CHAR_BIT;\n const uint8_t word_shift = n / word_bits;\n const uint8_t bit_shift = n % word_bits;\n\n const uint8_t num_words = bits/word_bits;\n assert(bits % word_bits == 0);\n\n if (n == 0) { return; }\n\n // Shift values into next word\n int i;\n for (i = num_words-1; i &gt;= word_shift; i--) {\n // move word\n b[i] = b[i - word_shift] &lt;&lt; bit_shift;\n\n // move leftover carried bits\n if (i != word_shift) {\n b[i] |= b[i-word_shift - 1] &gt;&gt; (word_bits - bit_shift);\n }\n }\n // Fill in zeroes\n for (; i &gt;= 0; i--) {\n b[i] = 0;\n }\n\n}\n</code></pre>\n\n<h1>Final notes</h1>\n\n<p>Currently, your layout to represent eg. <code>0x01020408</code> is an array\n<code>{ 0x08, 0x04, 0x02, 0x01 }</code>. This, to me, feels a bit counter-intuitive and also makes it a bit more difficult to eventually \"upcast\" to an even higher bitset, if you'd order the bytes reversed, you'd simply copy them and append zeroes. But that decision personal preference and/or application dependent.</p>\n\n<p>While my solution definitely uses more vertical space, we thankfully do not write on teletype writers anymore, making that a rather irrelevant restriction :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T12:27:52.937", "Id": "237743", "ParentId": "237506", "Score": "2" } }, { "body": "<p>Using the head of larkey. I did some optimizations. Don't do the word loop if there are less than word_bits to shift and don't recalculate the values.</p>\n\n<pre><code>void shr(uint64_t *const b, const uint16_t bits, const uint_fast8_t n)\n{\n const uint8_t word_bits = sizeof (b[0]) * CHAR_BIT;\n const uint8_t word_shift = n / word_bits;\n const uint8_t bit_shift = n % word_bits;\n const uint8_t bit_rest = word_bits-bit_shift;\n const uint8_t num_words = bits/word_bits;\n assert(bits % word_bits == 0);\n\n if (n == 0) { return; }\n\n uint64_t *dst, *src;\n\n if(word_shift&gt;0) {\n for(dst = b+num_words-1, src = dst-word_shift; src&gt;=b; dst--, src--)\n *dst = *src;\n for(; dst&gt;=b; dst--)\n *dst = 0;\n }\n for(dst = b+num_words-1; dst&gt;b; dst--)\n *dst = (*dst&gt;&gt;bit_shift) | (dst[-1]&lt;&lt;bit_rest);\n *dst &gt;&gt;= bit_shift;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T13:46:20.677", "Id": "237905", "ParentId": "237506", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T18:52:50.303", "Id": "237506", "Score": "7", "Tags": [ "c", "bitwise", "bitset" ], "Title": "Bit shift 256 bits" }
237506
<p>I'm a beginner programmer and I came upon this problem which is to find the <em>n</em>​th number in the Fibonacci series.</p> <p>I used to solve the problem using a <code>for</code> loop; today I learned about recursion but there is a problem: when I pass 40 or 41 to the recursive function, it takes a bit of time to calculate it, while in the iterative method it would instantly give me the answers.</p> <p>I have these questions:</p> <ol> <li>Why do most people (on the Internet) recommend using recursion? Because it's simpler and easier to write the program? (Logically I thought that we should write it in a way that is fast and simple)</li> <li>Here are the 2 methods that a beginner like me can handle writing at the moment. Is there a better way than these two methods? And are these methods complex?</li> </ol> <p>Here is the recursive method:</p> <pre><code> #include &lt;iostream&gt; using namespace std; unsigned long long fibonacci(unsigned long long n); unsigned long long fibonacci(unsigned long long n){ if(n&lt;=1) return n; //base case return fibonacci(n-1) + fibonacci(n-2); //recursive case } int main(){ unsigned int a {}; cout &lt;&lt; "Enter number: "; cin &gt;&gt; a; cout &lt;&lt; fibonacci(a) &lt;&lt; endl; return 0; } </code></pre> <p>And here is the iterative (looping) method:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int n{}; unsigned long long t1{0}, t2{1}; unsigned long long sum{}; cout &lt;&lt; "Enter the number of terms: "; cin &gt;&gt; n; cout &lt;&lt; "Fibonacci Series: "; for (int i{2}; i &lt; n; ++i) { sum = t1 + t2; t1 = t2; t2 = sum; } cout &lt;&lt; t2; return 0; } </code></pre> <p>Note: I know that <code>using namespace std</code> is a bad idea but I have also tried the same thing without the namespace and still I get the delay, so I did it here because it's easy to understand.</p> <hr> <p>Edit1: First of all I would like to thank everyone who commented and answered my question...To be honest I didn't think that this question would bring a lot of attention to the community so I appreciate the time you put on this and it means a lot to me.</p> <p>Edit2: Let me demonstrate some of the things that might have been a little odd to you.</p> <p>Q: What do you mean by better when you say if there is a better way than these two methods?<br> A: By better, I meant that the code shall be <strong>simple</strong> and also takes <strong>less time</strong> to execute or perform the calculations </p> <p>Q: What do you mean when you say most people (on the internet) use recursion?<br> A: I've seen code out there that uses recursion to solve problems. The two common problems I've seen are <strong>Fibonacci</strong> and <strong>Factorial of a number</strong>. For factorial, I have also tried both methods (iteration and recursion) but I didn't get a delay for both of them when I type large numbers like 40 or 50. The common problem I saw with recursion is that eventually, you may run out of memory space because it is calling itself multiple times which results in a stack overflow (because stack as a part of memory will be filled). Although this problem doesn't occur in this example. So this raises another question here:</p> <p><strong>When should we use recursion?</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T19:27:39.837", "Id": "465764", "Score": "4", "body": "For most reviewers on the site, it is easier to understand if you done have the `using namespace std;` statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T06:20:29.057", "Id": "465838", "Score": "2", "body": "The recursive version is trivial to see you have done it correctly. The iterative version takes a bit of thought (not much but some). But you have stopped on the iterative version as if that is the correct answer. There is so much more to do. This is why I like this as an interview question (as a proxy for thinking as fib() solutions are obvious). But you can make candidates think about all the other issues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T06:29:18.070", "Id": "465839", "Score": "4", "body": "The `using namespace std;` is not about speed. It is about maintainability. It is a bad habit that in the long run will make your code hard to maintain (and cause bugs (see linked article). That is why it is considered bad practice. [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/14065)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T12:40:38.973", "Id": "465866", "Score": "9", "body": "\"*Iteration or recursion*\" -- neither, there's a [closed form solution](https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T12:52:36.720", "Id": "465867", "Score": "1", "body": "What @canton7 says. I sometimes use this as to kick off an wide-ranging interview discussion. Present the candidate with a recursive version, get them to explain what it does, then off you go into discussions of \"good/bad\" metrics, performance, iterative version, look-up tables, and eventually the fact that there's a closed form (the best, even if they don't know about that, on seeing that it's about fibonnacci, quickly ask if they can google it and come up with the closed form). With C++ there's also a compile-time solution as you can do it with templates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T13:30:33.010", "Id": "465870", "Score": "1", "body": "Congratulations on your first nice question badge. As an experiment, you might want to try putting both of these algorithms into the same main and time each function call and report back the elapsed time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T17:59:20.597", "Id": "465915", "Score": "2", "body": "Note: It is possible find any fibonacci number in O(log n) time, or, in some cases, O(1) time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T00:59:22.457", "Id": "465971", "Score": "6", "body": "@canton7: The closed form solution will be wrong starting at Fib(70), presuming binary64 doubles are used. The iterative solution will give a correct answer with 64-bit integer arithmetic up to Fib(92) inclusive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T11:26:18.793", "Id": "466014", "Score": "1", "body": "*Do* 'most people (on the internet) recommend using recursion'? Really? I doubt this is true. Evidence please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T14:19:25.543", "Id": "466036", "Score": "5", "body": "I'm completely not seeing the explanation of why the recursive method is slow in the answers: the reason is that it pretty much builds the Fibonacci number by adding lots of ones together (and therefore will add an exponentially growing number of them)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T14:56:10.070", "Id": "466040", "Score": "0", "body": "@user207421 I dont know if these count as evidence but here they are: [link](https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/) and this one [link](https://www.programming9.com/programs/c-programs/339-c-program-to-find-nth-fibonacci-number-using-recursion)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T22:19:04.263", "Id": "466086", "Score": "1", "body": "@PresidentJamesMoveonPolk The closed form solution can work for much larger values by using a multiprecision math library like https://gmplib.org/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T08:29:41.633", "Id": "466115", "Score": "1", "body": "\"Why do most people (on the internet) recommend using recursion\" - It depends on the purpose. Take the case of merge sort. For educational purposes, recursive top down merge sort is the most popular, but almost all stable sorts as implemented in libraries use some variation of a hybrid insertion sort and bottom up merge sort, such as [timsort](https://en.wikipedia.org/wiki/Timsort)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T20:49:13.870", "Id": "466212", "Score": "1", "body": "@mypronounismonicareinstate Also I don't like calling it _the_ recursive version. You can write a recursive version of `fib` that's pretty fast (as in, fast enough that stack space / number range limits are going to become an issue long before performance will) (although it'll still be a _bit_ slower than the iterative version unless your compiler is doing tail call elimination)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T01:03:27.267", "Id": "466392", "Score": "1", "body": "@DavidConrad: Of course, but then that isn't an apples-to-apples comparison. If we go to multiprecision then we compare this to the O(log(n))-multiplies algorithm for computing exact integer Fibonacci number, and that would again be apples-to-apples." } ]
[ { "body": "<p>In the recursive version of the code you don't need the function prototype <code>unsigned long long fibonacci(unsigned long long n);</code>.</p>\n\n<p>As you mentioned you shouldn't have the <code>using namespace std;</code> statement in the code.</p>\n\n<p>We can't answer </p>\n\n<blockquote>\n <p>Why do most people (on the internet) recommend using recursion because it's simpler and easier to write the program?(well logically I thought that we should write it in a way that is fast and simple)</p>\n</blockquote>\n\n<p>Because it is an opinion.</p>\n\n<p>In the iterative version you should also have the <code>fibonacci(unsigned long long n)</code> function to make <code>main()</code> simpler.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T19:43:10.710", "Id": "465768", "Score": "0", "body": "Thank you for your help..and also let's say that if we don't include using namespace std in our code then for every cout we should say std::cout...and so on and so forth for other elements....otherwise we get an error..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T04:02:55.297", "Id": "465834", "Score": "7", "body": "@DavidPeterson Yes, and `std::cout` is clearer than `cout` because the latter can mean either `std::cout` or `my::obscure::library::cout` (which overloads the `<<` operator to print the values in the form of nasal demons), depending on context and ADL, so code readers have to stop and think for a moment. This problem is not so evident with `cout`, but consider `data`, `arg`, `visit`, etc., none of which I can immediately realize is actually a name from the standard library. `using namespace std;` also pollutes the global namespace with tons of common identifiers, causing name clashes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T19:36:50.483", "Id": "237512", "ParentId": "237508", "Score": "5" } }, { "body": "<p>By using that iterative solution, you are indirectly using Dynamic Programming (DP)</p>\n\n<p><strong>Answer for question number 1:</strong></p>\n\n<p>Recursion <em>might</em> be faster in some cases.</p>\n\n<p>For example, let's say you have a 2d road of size <code>n * m</code>. There are blockages in the road, so you can't pass through them.</p>\n\n<p>The objective is to check if there exists <em>any path</em> from the top-left corner to the bottom-right (You can only move right or down).</p>\n\n<p>The recursive solution would win as the iterative solution will take <code>O(N * M)</code> in the best and the worst case, but the recursive solution will take <code>O(N + M)</code> for the best case and <code>O(N * M)</code> for the worst case. </p>\n\n<p>An iterative <a href=\"https://www.geeksforgeeks.org/check-possible-path-2d-matrix\" rel=\"nofollow noreferrer\">solution</a> with a detailed explanation is given here, but I can't find any sources for a recursive solution.</p>\n\n<p><strong>Answer for question number 2:</strong></p>\n\n<p>The recursive solution of yours is much slower than the iterative one because you are not using <a href=\"https://www.geeksforgeeks.org/overlapping-subproblems-property-in-dynamic-programming-dp-1\" rel=\"nofollow noreferrer\">memoization</a>.</p>\n\n<p>Memoization is not that hard to understand.</p>\n\n<p>Please do try visiting this link: <a href=\"https://www.quora.com/How-should-I-explain-dynamic-programming-to-a-4-year-old\" rel=\"nofollow noreferrer\">https://www.quora.com/How-should-I-explain-dynamic-programming-to-a-4-year-old</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T11:56:02.177", "Id": "465863", "Score": "1", "body": "I don't understand why two people down-voted my answer. Would someone please explain why so that I won't repeat the same mistake in the future? Thanks a lot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T13:35:35.363", "Id": "465871", "Score": "4", "body": "I fail to see how you answer the questions (why is recursion usually recommended for calculating the Fibonacci sequence? What are possible alternatives to these 2 approach?), it doesn't comment on the code itself, and uses pictures to display text, which is bad form since it cannot be searched and used as a reference in the future. The first 2 points make your answer look like an ad for dynamic programming rather than a code review, and you should use blockquotes and links to the sources for the 3rd point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T17:18:08.303", "Id": "465903", "Score": "2", "body": "A giant purple rectangle is just hideous, and when scrolling down the page just screams \"ADVERTISEMENT!\" which causes me to just skip way further down fast and get that thing off my screen. There is absolutely **NO reason** to have that here. If you're going to have a quote, use text to do it. Although that bit seems completely irrelevant to the requested code review (IMHO)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T17:35:31.150", "Id": "465906", "Score": "1", "body": "@1201ProgramAlarm Nice point! I've changed that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T17:38:38.373", "Id": "465907", "Score": "1", "body": "@gazoh You are right. I thought the OP asked for recursion in general and not specifically for Fibonacci. I am quite sorry. I will edit my answer as soon as possible!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T21:42:43.233", "Id": "237515", "ParentId": "237508", "Score": "3" } }, { "body": "<blockquote>\n <p>Why do most people (on the internet) recommend using recursion because it's simpler and easier to write the program? Logically I thought that we should write it in a way that is fast and simple.</p>\n</blockquote>\n\n<p>This is a perceptive question. I wrote an article about exactly this topic in 2004, which you can read here:</p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/archive/blogs/ericlippert/how-not-to-teach-recursion\" rel=\"noreferrer\">https://docs.microsoft.com/en-us/archive/blogs/ericlippert/how-not-to-teach-recursion</a></p>\n\n<p>Summing up: there are <em>two</em> good reasons to teach people to use recursion to solve Fib:</p>\n\n<ul>\n<li>First, because it clearly illustrates what you have learned today. <strong>A naive translation of a recursive definition into a recursive function can often lead to poor performance</strong>. That's an important lesson for beginners to take away. (EXERCISE: How many <em>additions</em> does your naive recursive program execute for a given n? The answer may surprise you.)</li>\n<li>Second, because the first lesson then gives us an opportunity to lead the beginner to learn <strong>how to write a recursive algorithm so that it performs well</strong>.</li>\n</ul>\n\n<p>Unfortunately, as you have discovered, a great many people on the internet have not internalized that <strong>teaching recursion via fib is solely useful as an illustration of bad uses of recursion and how to fix them</strong>, and not in itself an example of a good use of recursion.</p>\n\n<p>It would be much better if people attempting to teach recursion did so by providing a mix of good and bad recursive algorithms, and taught how to spot and avoid the bad ones. </p>\n\n<blockquote>\n <p>Is there a better way than these two methods?</p>\n</blockquote>\n\n<p>Another lesson you'll quickly learn is that asking \"which is better?\" is a sure way to get back the reply: \"can you describe a clear metric for betterness?\"</p>\n\n<p>So: <em>can you describe a clear metric for betterness?</em></p>\n\n<p>If the goal is to print out the nth fib number, you can do way \"better\" than either of your solutions:</p>\n\n<pre><code>unsigned long long fibs[] = { 1, 1, 2, 3, 5, 8, ... }\nif (0 &lt;= n &amp;&amp; n &lt; sizeof(fibs... blah blah blah))\n cout &lt;&lt; fibs[n];\n</code></pre>\n\n<p>Done. There are only so many fib numbers that fit into a long. You can look them up on the internet, copy them into your program, and you've got a short, fast fib program with no loops at all. That's \"better\" to me.</p>\n\n<p>But remember, the point of this exercise is to teach you something about recursion, so by that metric my program is certainly not \"better\".</p>\n\n<blockquote>\n <p>are these methods complex?</p>\n</blockquote>\n\n<p>By \"these methods\" I think you mean \"methods of writing recursively-stated algorithms into code other than naive recursion and unrolling the recursion into a loop\".</p>\n\n<p>That's a matter of opinion. Let me put it this way. </p>\n\n<p>I work on a compiler team, and I interview a lot of people. My standard coding question involves writing a simple recursive algorithm on binary trees that is inefficient when written the naive way, but can be made efficient by making a few simple refactorings. If the candidate is unable to write that clear, straightforward, efficient code, that's an easy no-hire.</p>\n\n<p>Where things get interesting is when I ask \"suppose you had to remove the left-hand recursion from this tree traversal; how might you do it?\" </p>\n\n<p>There are standard techniques for removing recursions. Dynamic programming reduces recursions. You could make an explicit stack and use a loop. You could make the whole algorithm tail recursive and use a language that supports tailcalls. You could use a language with cocalls. You could use continuation passing style and build a \"trampoline\" execution loop.</p>\n\n<p>Some of these techniques are, from the perspective of the novice, terribly complicated. I ask the question because I want to know what is in the developer's toolbox.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T06:38:26.313", "Id": "465840", "Score": "3", "body": "I also like this as an interview question. Not because of the code (as everybody can write the recursive version and anybody that has looked at any coding test has seen the iterative version). But because it leads into lots of discussions about techniques. Love the article." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T08:59:27.650", "Id": "465844", "Score": "1", "body": "\"are these methods complex\" - there are iterative algorithms specific to Fibonacci unrelated to optimizing recursion, one involves raising a matrix to a power, the other involves a Lucas sequence. I think this is what the OP is asking about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:00:37.420", "Id": "465931", "Score": "0", "body": "Thank you for your complete answer...I would also like to add this to your answer...Let's say this in a very beginner friendly way...a memory has four main parts: heap(free store), stack, static variables & code area...let's talk about stack here in this fibonacci example...what I find or consider a problem with recursion is that every time the function is called, it's gonna stack the functions together sort of like calling itself multiple times...eventually you may run out of memory space...and I'm not sure but I think the term \"stack overflow\" is called for this solution" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:02:48.977", "Id": "465932", "Score": "2", "body": "@DavidPeterson: That's right; in many operating systems, particularly Windows, you only get a fixed amount of stack space and by default, the activation frames for method calls go on the stack. That implies that unbounded or very deep recursions will \"blow the stack\". One reason for knowing about the techniques I discussed for removing recursions is to prevent stack overflows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:04:21.663", "Id": "465934", "Score": "1", "body": "@DavidPeterson: A concept you might want to study is that of *continuation*. The *continuation* of a particular piece of code is *the thing that will happen when this code is done*. The stack is how we reify continuation in \"normal\" function calls: you call a function, and what happens next? Either the function throws, in which case the continuation is the exception handler, or it never returns normally, or it does return normally; the \"normal return\" continuation information is stored on the stack." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:05:23.877", "Id": "465935", "Score": "1", "body": "@DavidPeterson: Since activations of asynchronous calls *do not logically form a stack*, we do not use the stack to store continuations of async workflows -- or, rather, we use it less. Getting your head around continuations is tricky, but once you do, many facts about programming become much more clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T09:03:33.743", "Id": "466118", "Score": "1", "body": "@EricLippert - \"normal return ... information stored on the stack\". A big exception to this is legacy code convention for IBM mainframes, which uses a caller provided save area (pointed to by R13, sometimes allocated from the equivalent of a heap). Most financial institutions are still using this legacy code (a combination of Cobol and assembly), since it's not worth the risk or time it would take to convert this huge legacy code base. Reentrant code can use a \"linkage stack\", but it still involves allocating (and later freeing) save areas from the heap, as opposed to an actual stack." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T09:29:13.967", "Id": "466121", "Score": "1", "body": "@EricLippert - \"suppose you had to remove the left-hand recursion\" ... . This seems to be similar to limiting quicksort's stack space complexity to O(log(n)) by recursing only on the smaller partition, and looping back to handle the larger partition. It limits stack space, but worst case time complexity is still O(n^2), unless other methods (like choice of pivot) are involved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T16:10:47.047", "Id": "466180", "Score": "1", "body": "@rcgldr: That's a good point, but I had a different motivation. I try to ask interview questions about problems that the candidate is likely to encounter because I encountered them previously. Consider the problem of running a compiler pass on the parse tree for `1 + 1 + 1 + 1 + 1... + 1` The parse tree will be extremely left-heavy, so if you can remove just the left-hand recursion, you can make it less likely that the compiler will run out of stack space. Machine-generated code often generates long string concatenations or other additions." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:53:35.577", "Id": "237519", "ParentId": "237508", "Score": "38" } }, { "body": "<blockquote>\n <p>Is there a better way than these two methods?And are these methods complex?</p>\n</blockquote>\n\n<p>There are better methods, and although not that complex, few people would be able to develop such methods (such as Lucas sequence relations) on their own without relying on some reference.</p>\n\n<p>For the recursive version shown in the question, the number of instances (calls) made to fibonacci(n) will be 2 * fibonacci(n+1) - 1. </p>\n\n<p>As for better methods, Fibonacci(n) can be implemented in O(log(<em>n</em>)) time by raising a 2 x 2 matrix = {{1,1},{1,0}} to a power using exponentiation by repeated squaring, but this takes 12 variables. This can be reduced to 5 variables using a method based on Lucas sequence relations.</p>\n\n<p>Example code; <em>c</em> and <em>d</em> are used for the repeated squaring, while <em>a</em> and <em>b</em> are the cumulative results and end up as a = fib(n+1), b = fib(n).</p>\n\n<p>Note: older compilers may be missing <code>&lt;inttypes.h&gt;</code> or <code>&lt;stdint.h&gt;</code>. If <code>&lt;inttypes.h&gt;</code> is not present (Visual Studio 2010), use compiler specific format string for <code>uint64_t</code>. If <code>&lt;stdint.h&gt;</code> is not present (Visual Studio 2005), use <code>typedef ... uint64_t</code> (usually <code>unsigned long long</code>) and the appropriate format string.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;inttypes.h&gt;\n\nuint64_t fib(uint64_t n)\n{\n uint64_t a, b, c, d;\n a = d = 1;\n b = c = 0;\n while (1) {\n if (n &amp; 1) {\n uint64_t ad = a*d;\n a = ad + a*c + b*d;\n b = ad + b*c;\n }\n n &gt;&gt;= 1;\n if (n == 0)\n break;\n {\n uint64_t dd = d*d;\n d = dd + 2 * d*c;\n c = dd + c*c;\n }\n }\n return b;\n}\n\nint main(void)\n{\n uint64_t n;\n for (n = 0; n &lt;= 93; n++)\n printf(\"%20\" PRIu64 \" %20\" PRIu64 \"\\n\", n, fib(n));\n return 0;\n}\n</code></pre>\n\n<hr>\n\n<p>The code is based on Lucas sequence relations for Fibonacci numbers.</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Lucas_sequence#Other_relations\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Lucas_sequence#Other_relations</a></p>\n\n<p>Specifically these equations:</p>\n\n<pre><code>F(m) = F(m-1) + F(m-2)\nF(m+n) = F(m+1) F(n) + F(m) F(n-1)\nF(2n) = F(n) L(n) = F(n) (F(n+1) + F(n-1))\n = F(n)((F(n) + F(n-1)) + F(n-1))\n = F(n) F(n) + 2 F(n) F(n-1)\n</code></pre>\n\n<p>Initial state:</p>\n\n<pre><code>a = F(1) = 1\nb = F(0) = 0\nc = F(0) = 0\nd = F(1) = 1\n</code></pre>\n\n<p>n is treated as the sum of powers of 2: 2^a + 2^b + ... \nfor each iteration <em>i</em> (starting from 0), let p = 2^i, then </p>\n\n<pre><code>c = F(p-1)\nd = F(p)\n</code></pre>\n\n<p>To advance to the next iteration, c and d are advanced to F(next power of 2):</p>\n\n<pre><code>d' = F(2p) = F(p) F(p+1) + F(p) F(p-1)\n = F(p)(F(p) + F(p-1)) + F(p) F(p-1)\n = F(p) F(p) + F(p) F(p-1) + F(p) F(p-1)\n = F(p) F(p) + 2 F(p) F(p-1)\n = d d + 2 c d\n\nc' = F(2p-1) = F(p+p-1) = F(p+1) F(p-1) + F(p) F(p-2)\n = (F(p) + F(p-1)) F(p-1) + F(p) (F(p) - F(p-1))\n = F(p) F(p-1) + F(p-1) F(p-1) + F(p) F(p) - F(p) F(p-1)\n = F(p) F(p) + F(p-1) F(p-1)\n = d d + c c\n</code></pre>\n\n<p>During the calculation of a and b, let <em>m</em> = current cumulative sum of bits of n:</p>\n\n<pre><code>b = F(m)\na = F(m+1)\n</code></pre>\n\n<p>To update a and b for 1 bits in n corresponding to <em>p</em> = current power of 2:</p>\n\n<pre><code>a' = F(m+1+p) = F(m+2) F(p) + F(m+1) F(p-1)\n = (F(m+1)+F(m)) F(p) + F(m+1) F(p-1)\n = F(m+1) F(p) + F(m) F(p) + F(m) F(p-1)\n = a d + b d + b c\n\nb' = F(m+p) = F(m+1) F(p) + F(m) F(p-1)\n = a d + b c\n</code></pre>\n\n<hr>\n\n<p>Note that if b' is the max value for uint64_t, a' will overflow, but it's not an issue. However, the algorithm can be modified so that when completed, a = fib(n-1):</p>\n\n<pre><code>a = fib(-1) = 1\nb = fib(0) = 0\n\na = fib(m-1)\nb = fib(m)\n\nb' = fib(m+p)\n = fib(m+1)fib(p) + fib(m)fib(p-1)\n = (fib(m) + fib(m-1))fib(p) + fib(m)fib(p-1)\n = fib(m)fib(p) + fib(m-1)fib(p) + fib(m)fib(p-1)\n = bd + ad + bc\n\na' = fib(m-1+p)\n = fib(m)fib(p) + fib(m-1)fib(p-1)\n = bd + ac\n\nuint64_t fib(uint64_t n)\n{\n uint64_t a, b, c, d;\n a = d = 1;\n b = c = 0;\n while (1) {\n if (n &amp; 1) {\n uint64_t bd = b*d;\n b = bd + a*d + b*c;\n a = bd + a*c;\n }\n n &gt;&gt;= 1;\n if (n == 0)\n break;\n {\n uint64_t dd = d*d;\n d = dd + 2*d*c;\n c = dd + c*c;\n }\n }\n return b;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T01:52:40.613", "Id": "465973", "Score": "2", "body": "The `#define` makes this program needlessly complicated. Plus the bad variable names. And `main` is missing the return type. We are not in the 1980s anymore." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T02:35:23.977", "Id": "465976", "Score": "1", "body": "@RolandIllig - The variable names are the same as those used in other examples of Lucas sequence methods, with the variation that `c` and `d` are sometimes named `p` and `q`. I don't how the int on main got lost, but it is fixed now. I've been having issues trying to find current examples of this code that clearly state it's a variation of Lucas sequence. I'll update my answer with link(s) if/when I find them. The defines are probably a legacy issue in case a compiler doesn't optimize the two products to a single variable (register). This is an old algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T02:50:07.390", "Id": "465978", "Score": "1", "body": "@RolandIllig - I found a variation of the method using a, b, p, q [here](https://github.com/zed/txfib/blob/41ea022cc8cffc1d4b63996d313e644b494be7dd/fibonacci.py#L165), but no reference to Lucas sequence." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T11:03:44.560", "Id": "466010", "Score": "1", "body": "@RolandIllig - I haven't been able to find a link for how this code works, so I updated my answer with my own explanation, based on Lucas sequence relations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T19:22:44.333", "Id": "466065", "Score": "1", "body": "@RolandIllig - the defines are gone, replaced by block local variables. Toby Speight updated the printf to use inttypes.h. (Note VS2010 doesn't have inttypes.h, and VS2005 doesn't have stdint.h, which I mentioned in my answer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T21:14:54.920", "Id": "466077", "Score": "1", "body": "Thanks for adding the missing details. It would be good if you referred to VS2010 and VS2005 directly in your answer instead of this comment. When you said \"older compilers\" I had thought about the 1990s. The words \"old\" and \"new\" should not be used in text that is supposed to stay up-to-date for several years." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T22:36:13.610", "Id": "466088", "Score": "1", "body": "@RolandIllig - fixed now. I also added an alternate version where at completion a = fib(n-1), while b = fib(n) (same as before). I could just switch the explanation and code to the alternate version to keep the answer simple, but after doing a web search, I've found examples of both methods (a = fib(n+1), a = fib(n-1))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T17:02:58.727", "Id": "466468", "Score": "0", "body": "FYI, in my opinion, the clearest version of the fibonacci \"doubling\" rules which lead to an O(log(n))-multiplies algorithm is [here](https://math.stackexchange.com/a/2368738/552). By defining things in terms of the special `mult` operator, the resulting code seems much simpler and cleaner. I'm fairly certain it is equivalent to your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T18:55:06.627", "Id": "466484", "Score": "1", "body": "@PresidentJamesMoveonPolk - the code is similar. Note that the python code would need to be modified to handle F(0): such as power((1,0),0) == (0,1), but I don't know how to do this generically. The python example is calculating a \"power\" of {F(1),F(0)}, while my code separates this into an initial state {F(m±1), F(m)}, and then \"advances\" the initial state by a power of {F(0), F(1)}. By switching from uint64_t to int64_t, the initial state can use negative values for m, since the \"advancing\" involves calculating F(m+p)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-14T13:48:53.330", "Id": "468478", "Score": "0", "body": "Actually you use the symmetry of [1,1;1,0]^n = [F_{n+1},F_n;F_n;F_{n-1}] represented by pair (F_n,F_{n-1}) ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-15T01:55:05.310", "Id": "468526", "Score": "0", "body": "@SamGinrich - the matrix based method involves 12 variables, the Lucas sequence based method involves 5 variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-21T16:11:27.610", "Id": "469265", "Score": "0", "body": "@rclgdr This is correct for common matrix products, where our matrix has symmetry and dependency by the recursive definition, so that it is sufficient to evaluate the right part of the power matrix, leading exactly to the same algorithm as your approach with Lucas numbers." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T09:34:28.410", "Id": "237553", "ParentId": "237508", "Score": "4" } }, { "body": "<p>As other answers state, your iterative algorithm outperforms your recursive algorithm because the former remembers previous intermediate results (or at least one such result) while the latter doesn’t. Of course, one can write recursive algorithms that remember previous results.</p>\n\n<p>For Fibonacci numbers that’s simple enough since you only need to remember one such result. Using the tuple unpacking syntax of C++17 for sake of readability:</p>\n\n<pre><code>#include &lt;utility&gt;\n\nnamespace mynamespace {\n\nnamespace detail {\n\nstd::pair&lt;unsigned long long, unsigned long long&gt;\nfibonacci_impl(unsigned long long n)\n{\n if (n &lt;= 1)\n return { n, 0 };\n\n auto [fib1, fib2] = fibonacci_impl(n - 1);\n return { fib1 + fib2, fib1 };\n}\n\n} // end namespace detail\n\nunsigned long long fibonacci(unsigned long long n)\n{\n return detail::fibonacci_impl(n).first;\n}\n\n} // end namespace mynamespace\n</code></pre>\n\n<p><code>detail::fibonacci_impl</code> returns the result of <code>fibonacci(n)</code> <em>and</em> <code>fibonacci(n-1)</code> (as a <code>pair</code>) for reuse by the caller. A sufficiently smart compiler can optimize away the overhead of pair packing and unpacking to leave the function call overhead (see <a href=\"https://godbolt.org/z/YrNRwr\" rel=\"nofollow noreferrer\">compiler explorer</a>) as the only disadvantage of the recursive algorithm over its iterative counterpart.</p>\n\n<h2>Addendum: Namespaces</h2>\n\n<p>I enclosed the function declarations into their own namespace <code>mynamespace</code> and a sub-namespace <code>mynamespace::detail</code>.</p>\n\n<p>If your program is more than trivial you should place your declarations (functions, classes or otherwise) into a separate namespace. For declarations that are meant to be used outside of your own program (e. g. a programming library) it’s highly recommended to do so to avoid name shadowing issues and confusion in general.</p>\n\n<p>If your library declares stuff that is only meant to be used from inside this library, it’s customary to place it inside a sub-namespace whose name indicates its intended nature. Examples that I encountered for such sub-namespace names include: <code>detail</code>, <code>internal</code>, <code>implementation</code> or, shorter, <code>impl</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T01:54:21.390", "Id": "465974", "Score": "8", "body": "Don't define names starting with two underscores." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T14:48:43.617", "Id": "466168", "Score": "2", "body": "A single underscore is not as bad as two of them, but still unusual. I don't remember the exact rules for the single underscore, but some of these names are still reserved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T19:18:50.150", "Id": "466200", "Score": "2", "body": "Why are you putting underscores at the start of your function's name?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T20:48:19.593", "Id": "466318", "Score": "1", "body": "@RolandIllig: Acknowledged and fixed. I read up on C++ naming styles which recommend (anonymous) sub-namespaces for declarations relating to implementation details." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T20:48:33.360", "Id": "466319", "Score": "1", "body": "@theonlygusti: see above" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T22:21:29.683", "Id": "466634", "Score": "1", "body": "Note in C defining a global identifier with a leading underscore is undefined (C11, §7.1.3): *\"All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.\"* & *\"No other identifiers are reserved. If the program declares or defines an identifier in a\ncontext in which it is reserved [...] or defines a reserved identifier as a macro name, the behavior is undefined.\"*" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T18:49:27.140", "Id": "237575", "ParentId": "237508", "Score": "7" } }, { "body": "<p>Neither nor!</p>\n\n<p>David Foerster's __fibonacci_impl has a matrix representation, where the matrix can be brought into a diagonal shape, evaluating to a difference of two exponential functions, where the absolute value of the latter one is less than one and so may be replaced by a rounding operator.</p>\n\n<p><a href=\"https://i.stack.imgur.com/gSz56.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gSz56.png\" alt=\"Recursion and iteration free evaluation of Fibonacci numbers\"></a></p>\n\n<pre><code> const double sqr5 = sqrt(5);\n const double phi = 0.5 * (sqr5+1);\n\n double Fn = floor( pow(phi,n) / sqr5 + 0.5); // n&lt;=70\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T01:05:31.650", "Id": "465972", "Score": "2", "body": "This fails starting at Fib(71)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T06:30:26.123", "Id": "465989", "Score": "4", "body": "@MonicaPolk it just has accuracy limitations due to numerical errors of double. Integer `int64` based slower approach will hit integeroverflow around Fib(92) thus failing miserably and not just being inaccurate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T08:21:01.970", "Id": "466114", "Score": "1", "body": "@ALX23z - for unsigned 64 bit integers, the limit is Fib(93)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T12:36:14.103", "Id": "466275", "Score": "1", "body": "I just hope this is meant as a joke as this answers almost none of OP's questions and totally misses the point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T00:58:02.267", "Id": "466391", "Score": "1", "body": "@ALX23z: Then by your own analysis the integer version is superior in an apple-to-apples comparison. Explain how the failure of this method starting at Fib(71) is less miserable than the failure of the integer iteration at Fib(93)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T04:15:21.417", "Id": "466396", "Score": "1", "body": "@PresidentJamesMoveonPolk providing accurate answer within 1e-14 relative accuracy is a success in most situations. Getting a completely different unrelated number is typically considered a failure. Is it so hard?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T12:14:03.977", "Id": "466426", "Score": "1", "body": "@ALX23z: The problem is to find the fibonacci number, not an *estimate* of the fibonacii number. 1e-14 relative accuracy represents a total and complete failure in this case. The method you're defending gets an incorrect, completely unrelated number. The integer iteration technique gets the exact correct answer. Do you not understand that a wrong answer is useless?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T13:59:38.150", "Id": "466441", "Score": "1", "body": "@PresidentJamesMoveonPolk who said that the task is to find fibonacci number exactly? There is function `sin` and `sin(pi)` is not 0 as it should be. Do you say that all `sin` also a total failure? Perhaps, also claim that PI in incorrectly represented?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T16:49:42.647", "Id": "466465", "Score": "1", "body": "@ALX23z: There is no possibly way to read the original question and conclude that an approximation to Fib(n) is acceptable. It's either equal to Fib(n) or it's not and it's useless." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T19:39:49.723", "Id": "466492", "Score": "1", "body": "@PresidentJamesMoveonPolk Thank you for your comment. I added a precondition according to limits of standard doubles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-24T20:13:39.257", "Id": "466493", "Score": "1", "body": "@PresidentJamesMoveonPolk exactly there is no exact question, only a vague one: how to compute fibinacchi numbers and what is the fastest way. It lacks necessary context what answer is perfectly correct - only what kind of answers are reasonable. Honestly, you have a severe lack of communication skills or common sense to make any form of judgement of what other people say." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T22:02:51.347", "Id": "237591", "ParentId": "237508", "Score": "5" } }, { "body": "<p>The debate around recursive vs iterative code is endless. Some say that recursive code is more \"compact\" and simpler to understand.. In both cases (recursion or iteration) there will be some 'load' on the system when the value of n i.e. fib(n) grows large.Thus fib(5) will be calculated instantly but fib(40) will show up after a slight delay. Of course your data type must also be large enough to hold the result.In C I think unsigned long long int on a 64-bit system is the largest that you can get.Beyond that you might want to try to hold the intermediate results in an array.Then the only constraint will be memory.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T06:51:45.023", "Id": "237609", "ParentId": "237508", "Score": "2" } }, { "body": "<p>While this question already has many answers, one of which is accepted, I would like to point out that the (naïve) recursive solution presented by OP has a much worse complexity than the iterative version. However, it is perfectly possible to split up the problem into a main function to be called by the user, and an internal helper function doing the work recursively. The below has the same complexity as the OP's iterative solution (and will, in fact, be compiled into an iterative solution by a good compiler), and essentially consists of two one-liners:</p>\n\n<pre><code>unsigned long long\nfibonacci_internal(unsigned long long n,\n unsigned long long t1,\n unsigned long long t2) {\n return (n == 0) ? t1 : fibonacci_internal(n - 1, t2, t2 + t1);\n}\n\nunsigned long long fibonacci(unsigned long long n) {\n return fibonacci_internal(n, 0, 1);\n}\n</code></pre>\n\n<p><strong>EDIT:</strong> Fixed typos in code.</p>\n\n<p><strong>EDIT 2:</strong> The reason a sufficiently smart compiler can transform the above into an iterative solution (essentially a loop that uses no extra stack frames) is that the recursive call occurs at the end of a logical branch before returning, with no other operation between the recursive call and the return. This is called <em>tail recursion</em>. Please have a look at <a href=\"https://stackoverflow.com/questions/33923\">https://stackoverflow.com/questions/33923</a> for more information. The OP's original function has an addition between the recursive call and the return, therefore it is not tail-recursive, the recursive call must use extra stack frames, and the compiler cannot turn it into an iterative solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T08:37:42.180", "Id": "237614", "ParentId": "237508", "Score": "3" } }, { "body": "<p>The equation given by Binet:</p>\n\n<p>fib[n] = (phi^n - (-phi)^(-n)) / sqrt(5) where phi=(1+sqrt(5))/2</p>\n\n<p>will give an accurate answer (unlike the answer above of fib [n] = phi^n / sqrt(5) + 1/2), which breaks down at values of n greater than 70).</p>\n\n<p>Since you can calculate it directly, iteration and recursion are unnecessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T23:21:14.463", "Id": "466330", "Score": "3", "body": "1. Please cite correctly: \"[phi^n / sqrt(5) + 1/2]\" comes with Gaussian brackets!\n2. It is an accurate simplification of your \"Binet\"-formula, if you follow the math above, valid for all natural numbers, including zero.\n3. Inaccurate is the C++-double-power function for larger exponents. The Binet-formula has same dependency and limits in C++ runtime with IEEE doubles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-25T04:10:17.810", "Id": "466525", "Score": "0", "body": "Thanks for correcting my misunderstanding, Sam, about the Gaussian brackets. I see you are right about the simplification, due to taking the integer part, since the first part of Binet's Formula, i.e. phi^n/sqrt(5), alternates just above and just under the integer result that is adjusted to by the second part, i.e. -(-phi)^(-n)/sqrt(5). In other words, my comment was unnecessary, so I humbly withdraw. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T02:33:42.250", "Id": "237675", "ParentId": "237508", "Score": "1" } }, { "body": "<p>Evaluating Asymptotic Complexity e.g. with gmp library, shows that rcgldr's algorithm, implementing efficient matrix powers with O(log(n)) mutlipications, has best performance among presented algorithms.</p>\n\n<p>Below compared for n in range 0 .... 647028207</p>\n\n<ol>\n<li>Straight Iteration, n steps, takes <em>O(n^1.60)</em> time.</li>\n<li>\"Golden Ratio\", i.e. above called the \"Binet's Formula\" due to floating arithmetics takes <em>O(n^1.25)</em> time</li>\n<li>rcgldr's algorithm with <em>O(n^1.029)</em> time.</li>\n</ol>\n\n<p>The diagram shows evaluation time for <em>Fn</em> in seconds over <em>n</em>, both axis logarithmic with base 10, \n<a href=\"https://i.stack.imgur.com/KYU22.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KYU22.png\" alt=\"enter image description here\"></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T23:42:33.257", "Id": "237765", "ParentId": "237508", "Score": "3" } }, { "body": "<p>Finally tribute to </p>\n\n<h2>When should we use recursion?</h2>\n\n<p>In view of formal verification of an algorithm you would write an <em>invariant</em>, which is a mathematical model of your algorithm, valid for any variables and arguments, which you prove then. When your result is anyway defined as recursion, as we have it for Fibonacci or Factorial series, proof may be performed by complete induction, where the induction step is trivially the recursive definition.</p>\n\n<p>Investigating the asymptotic complexity, i.e. with large numbers, overhead for instantiating a function many times does not carry.</p>\n\n<p>Though, the recursion depth is crucial as in runtime environments like C++. You must not have a StackOverflow; a recursion depth of O(n) as in the initial example is not acceptable!</p>\n\n<p>So whenever you can control the asymptotic recursion depth and runtime is for the most part in evaluation of your intermediary results, a recursive algorithm is suggested.</p>\n\n<p>Following is an algorithm with digit-wise evaluation of Fibonacci numbers, using two integer series derived from the relationship of Binet's Formula and Hyperbolic Functions; Complexity and recursion depth is O(log(n)).</p>\n\n<p><a href=\"https://i.stack.imgur.com/cQTA0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cQTA0.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>#include &lt;iostream&gt;\n\ntypedef unsigned long long N;\n\nstatic void FibRec(int n, N&amp; S, N&amp;C)\n{\n if (n &gt;= 1)\n {\n N S1, C1;\n FibRec(n &gt;&gt; 1, S1, C1);\n if ((n &gt;&gt; 1) &amp; 1)\n {\n C = (5 * C1 * C1 + S1 * S1) &gt;&gt; 1;\n }\n else\n {\n C = (C1 * C1 + 5 * S1 * S1) &gt;&gt; 1;\n }\n S= C1 * S1;\n if (n &amp; 1)\n {\n N Cn0 = C;\n C = (C + S) &gt;&gt; 1;\n S= (5 * S+ Cn0) &gt;&gt; 1;\n }\n }\n else\n {\n S = 0;\n C = 2;\n }\n}\n\n\nN fibonacci(int n)\n{\n N S, C;\n FibRec(n, S,C);\n return (n &amp; 1) ? C : S;\n}\n\n\nint main()\n{\n for (int n = 0; n&lt;=93; n++)\n {\n std::cout &lt;&lt; \"Fib[\" &lt;&lt; n &lt;&lt; \"] = \" &lt;&lt; fibonacci(n) &lt;&lt; std::endl;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-29T10:02:45.340", "Id": "238152", "ParentId": "237508", "Score": "1" } } ]
{ "AcceptedAnswerId": "237519", "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T19:20:50.503", "Id": "237508", "Score": "23", "Tags": [ "c++", "beginner", "c++11", "comparative-review", "c++14" ], "Title": "Find nth Fibonacci Number, using iteration and recursion" }
237508
<p>I am mapping a complex JSON response to two JPA Entity model classes using Jackson. The classes are CxExport and Mention, Mention has a Many to one relationship with CxExport I.e. Many mentions belong to one CxExport. The HTTP Response returns a List of mentions 2. The JPA model is a flattened instance of one of the list of mention objects returned in the HTTP response. the Mention JPA Entitys model's field names are different from the ones returned in the JSON response, </p> <p>my code:</p> <pre><code>enum class ExportType(var type: Int){ mention(0), dashboard(1) } @SequenceGenerator(name = "seq_cx_export", sequenceName = "SEQ_CX_EXPORT", allocationSize = 1, initialValue = 1) @Access(AccessType.FIELD) @Entity class CxExport( @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_cx_export") override var pk_id: Long? = null, var accountId: Long? = null, @Enumerated @Column(columnDefinition = "smallint") var exportType: ExportType? = null, var exportCount: Int? = null, var exportStart: Timestamp? = null, var exportEnd: Timestamp? = null ) : AbstractJpaPersistable&lt;Long&gt;() {} @SequenceGenerator(name = "seq_ment", sequenceName = "SEQ_MENTION", allocationSize = 1, initialValue = 1) @Access(AccessType.FIELD) @Entity class Mention( @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_ment") override var pk_id: Long? = null, @ManyToOne(cascade = [(CascadeType.MERGE)]) @JoinColumn(name = "export_id") var cxExport: CxExport, var authorId: String? = null, var authorUrl: String? = null, var authorImg: String? = null, var authorTags: String?, var origAuthorName: String? = null, var messageTitle: String? = null, @Lob var messageContent: String? = null, var messageLanguage: String? = null, var messageSentiment: String? = null, var messageType: String? = null, var sourceId: String? = null, var sourceCategory: String? = null, var sourceType: String? = null, var sourceDomain: String? = null, var sourceUrl: String? = null, var sourceProfile: String? = null, var sourceProfileName: String? = null, var locContinent: String? = null, var locCountry: String? = null, var locCity: String? = null, var locRegion: String? = null, var locLongitude: String? = null, var locLatitude: String? = null, var permalink: String? = null, var priorityId: Int? = null, var priorityName: String? = null, var priorityColor: String? = null, var responseTime: Int? = null, var resolveTime: Int? = null, var handleTime: Int? = null, var dateAdded: Int? = null, var datePublished: Int? = null ) : AbstractJpaPersistable&lt;Long&gt;() @MappedSuperclass abstract class AbstractJpaPersistable&lt;T: Serializable&gt; : Persistable&lt;T&gt; { companion object { var serialVersionUID = -5554308939380869754L } abstract var pk_id: T? override fun getId() : T? { return pk_id } override fun isNew() = null == getId() override fun toString() ="Entity oftype ${this.javaClass.name} with id: $id" override fun equals(other: Any?): Boolean { other ?: return false if (this === other) return true if (javaClass != ProxyUtils.getUserClass(other)) return false other as AbstractJpaPersistable&lt;*&gt; return if (null == this.getId()) false else this.getId() == other.getId() } override fun hashCode(): Int { return 58 } } fun deserializeMentions(body: String) { var export = CxExport() var response = mapper.readTree(body) var count = response["response"]["count"].asInt() export.exportCount = count export.accountId= 51216 export.exportType = ExportType.mention export.exportStart = Timestamp.from(Instant.now()) export.exportEnd = Timestamp.from(Instant.now()) cxExportRepo.saveAndFlush(export) var mentions: MutableList&lt;Mention&gt; = ArrayList() var data = response["response"]["data"] data.forEach { println(it["permalink"]?.asText()) var locContinent: String? = null var locCountry: String? = null var locCity: String? = null var locRegion: String? = null var locLongitude: String? = null var locLatitude: String? = null var priorityId: Int? = null var priorityName: String? = null var priorityColor: String? = null it["priority"]?.let { priorityId = it["id"]?.asInt() priorityColor = it["color"]?.asText() priorityName = it["name"]?.asText() } it["location"]?.let { locContinent = it["continent"]?.asText() locCountry = it["country"]?.asText() locCity = it["city"]?.asText() locRegion = it["region"]?.asText() locLongitude = it["longitude"]?.asText() locLatitude = it["latitude"]?.asText() } var tags: String? = null it["author"]["tags"]?.forEach { it?.asText()?.let { tags += it } } mentions.add(Mention( cxExport = export, authorId = it["author"]["id"]?.asText(), authorUrl = it["author"]["url"]?.asText(), authorImg = it["author"]["img"]?.asText(), authorTags = tags, messageTitle =it["message"]["title"]?.asText(), messageContent =it["message"]["content"]?.asText(), messageLanguage = it["message"]["language"]?.asText(), messageSentiment =it["message"]["sentiment"]?.asText(), sourceId = it["source"]["id"]?.asText(), sourceCategory = it["source"]["category"]?.asText(), sourceType = it["source"]["type"]?.asText(), sourceDomain = it["source"]["domain"]?.asText(), sourceUrl = it["source"]["url"]?.asText(), sourceProfile = it["source"]["profile_id"]?.asText(), sourceProfileName = it["source"]["profile_name"]?.asText(), locContinent = locContinent, locCountry = locCountry, locCity = locCity, locRegion = locRegion, locLongitude = locLongitude, locLatitude = locLatitude, permalink = it["permalink"]?.asText(), priorityId = priorityId, priorityName = priorityName, priorityColor = priorityColor, responseTime = it["timestamps"]["response_time"]?.asInt(), resolveTime = it["timestamps"]["resolve_time"]?.asInt(), handleTime = it["timestamps"]["handle_time"]?.asInt(), dateAdded = it["date"]["added"]?.asInt(), datePublished = it["date"]["published"]?.asInt() ) ) } mentionRepo.saveAll(mentions) } </code></pre>
[]
[ { "body": "<p>I'm about kotlin, not about <a href=\"https://github.com/SalomonBrys/Kotson\" rel=\"nofollow noreferrer\">kotson</a> or <a href=\"https://kotlin.link/?q=json\" rel=\"nofollow noreferrer\">other kotlin-json libraries</a>.<br>\nAlso, when writing, I jumped into reification. This isn't really important...</p>\n\n<h1>Reified Inline Extension functions</h1>\n\n<p>The only reason I'm writing this is because I'm using extension-functions later on and I don't know your kotlin-level. You can skip this if you understand. </p>\n\n<p>You can skip reified completely.</p>\n\n<h1><a href=\"https://kotlinlang.org/docs/reference/extensions.html#extension-functions\" rel=\"nofollow noreferrer\">extension function</a></h1>\n\n<p>Extension-functions are functions which make it look like you add functions to an existing class. An example:</p>\n\n<pre><code>fun &lt;T&gt; Any.cast() : T= this as T\n</code></pre>\n\n<p>As you can see, we refer to the receiver (Any) with <code>this</code>.</p>\n\n<pre><code>override fun equals(other : Any?) : Boolean{\n ...\n val otherId = other.cast&lt;AbstractJpaPersistable&lt;*&gt;()\n .getId() ?: return false\n ...\n}\n</code></pre>\n\n<p>This function makes the code more flowable. </p>\n\n<h2><a href=\"https://kotlinlang.org/docs/reference/inline-functions.html\" rel=\"nofollow noreferrer\">Inline</a></h2>\n\n<p>Inline means that kotlin will replace the call to a function with the body of the function.</p>\n\n<pre><code>inline fun sayHi() = println(\"hi\")\nfun main() = sayHi()\n//will be replaced with\nfun main() = println(\"hi\")\n</code></pre>\n\n<hr>\n\n<h2><a href=\"https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters\" rel=\"nofollow noreferrer\">reified</a></h2>\n\n<p>Just to make inline extension functions interesting, we can write the safeCase-function:</p>\n\n<pre><code>fun &lt;T&gt; safeCast() : T? = when(this){\n is T -&gt; this // exception\n else -&gt; null\n}\n</code></pre>\n\n<p>At runTime, the generics are erased and become Any?\nThis means the former function becomes:</p>\n\n<pre><code>fun safeCast() : T? = when(this){\n is null -&gt; this // exception\n else -&gt; null\n}\n</code></pre>\n\n<p>As we know, kotlin can create extra code at compiletime by inlining code.<br>\nWe also know that the passed generics are know at compiletime.<br>\nWhen we combine those things, we can ask kotlin to create code, whereby it replaces the generics with the types it knows the generics represent.<br>\nWe do this by adding reified to the generic:</p>\n\n<pre><code>inline fun &lt;reified T&gt; Any.safeCast() : T? = when(this){\n is T -&gt; this\n else -&gt; null\n}\n\noverride fun equals(other : Any?) : Boolean{\n ...\n val otherId = other.safeCast&lt;AbstractJpaPersistable&lt;*&gt;()\n ?.getId() ?: return false\n ...\n}\n</code></pre>\n\n<p>at runtime, this will become:</p>\n\n<pre><code>override fun equals(other : Any?) : Boolean{\n ...\n val otherId = when(other){\n is AbstractJpaPersistable -&gt; other \n else -&gt; null\n }?.getId() ?: return false\n ...\n}\n</code></pre>\n\n<p>Because kotlin inlines the functions, it knows what the types are from parameters that go in and what come out.<br>\nTherefor, it's possible to rewrite the normal cast a bit safer using castOrThrow with or without generic param:</p>\n\n<pre><code>inline fun &lt;reified T&gt; Any.castOrThrow() : T{\n return when(this){\n is T -&gt; this\n else -&gt; throw ClassCastException(\"\")\n }\n}\n\nfun main(){\n val a : Any = 5.castOrThrow()\n val a = 5.castOrThrow&lt;Int&gt;()\n val string : String = 5.castOrThrow() //throws\n}\n</code></pre>\n\n<hr>\n\n<h1><a href=\"https://kotlinlang.org/docs/reference/scope-functions.html#scope-functions\" rel=\"nofollow noreferrer\">scope functions</a></h1>\n\n<p>I saw you using let:</p>\n\n<ul>\n<li>reference to the receiver using it</li>\n<li>returns result of lambda</li>\n<li><code>receiver.let{ it.toString() }</code></li>\n</ul>\n\n<p>You also have also:</p>\n\n<ul>\n<li>reference to the receiver using it</li>\n<li>returns the receiver</li>\n<li><code>receiver.also{ it.doSomething() }</code></li>\n</ul>\n\n<p>You can use this for creating CxExport:</p>\n\n<pre><code>val export = CxExport().also {\n it.exportCount = count\n it.accountId = 51216\n it.exportType = ExportType.mention\n val now = Timestamp.from(Instant.now())\n it.exportStart = now\n it.exportEnd = now\n}\n</code></pre>\n\n<p>But... we have 2 more:</p>\n\n<p>run:</p>\n\n<ul>\n<li>reference to receiver using this:</li>\n<li>returns result of lambda</li>\n<li><code>receiver.run{ this.toString() }</code></li>\n</ul>\n\n<p>And apply:</p>\n\n<ul>\n<li>reference to receiver using this</li>\n<li>returns the receiver</li>\n<li><code>receiver.apply{ this.doSomething() }</code></li>\n</ul>\n\n<p>And as this doesn't have to be written: <code>receiver.apply{ doSomething() }</code><br>\nthis means the code can be rewritten as:</p>\n\n<pre><code>val export = CxExport().apply {\n exportCount = count\n accountId = 51216\n exportType = ExportType.mention\n val now = Timestamp.from(Instant.now())\n exportStart = now\n exportEnd = now\n}\n</code></pre>\n\n<h1><a href=\"https://kotlinlang.org/docs/reference/scope-functions.html#scope-functions\" rel=\"nofollow noreferrer\">inline classes</a></h1>\n\n<p>Kotlin has inline classes (they work roughly the same as Integer/int in Java).<br>\nYou can create a inline class which takes one argument and add functions to that argument.<br>\nThe inlined class itself is not used (if you call it from kotlin and the type is known):</p>\n\n<p>When inline classes are boxed:</p>\n\n<ul>\n<li>When using generics</li>\n<li>Inline classes can implement interfaces. Passing it where interface is expected will box</li>\n<li>When making type nullable</li>\n</ul>\n\n<p>I believe this is the perfect way to make the data.foreach better</p>\n\n<pre><code>inline class Location(private val value : Map&lt;String, String?&gt;?){\n operator fun Map&lt;String, String?&gt;?.get(key: String) = this?.get(key)\n val continent get() = value[\"continent\"]?.asText()\n val country get() = value[\"country\"]?.asText()\n val city get() = value[\"city\"]?.asText()\n val region get() = value[\"region\"]?.asText()\n val longitude get() = value[\"longitude\"]?.asText()\n val latitude get() = value[\"latitude\"]?.asText()\n}\n\ninline class Priority(private val value : Map&lt;String, String?&gt;?){\n operator fun Map&lt;String, String?&gt;?.get(key: String) = this?.get(key)\n val id get() = value[\"id\"]?.asInt()\n val name get() = value[\"name\"]?.asText()\n val color get() = value[\"color\"]?.asText()\n}\n</code></pre>\n\n<p>As i said before, making the inline class nullable, means that the class is not inlined anymore.<br>\nBecause you have to call value?.get(\"id\") on a nullable map, I created an extension-function on the nullable Map. </p>\n\n<p>We can place this function in an interface as well. </p>\n\n<pre><code>inline class Location(private val value : Map&lt;String, String?&gt;?) : NullableMapGetter{\n val continent get() = value[\"continent\"]?.asText()\n val country get() = value[\"country\"]?.asText()\n val city get() = value[\"city\"]?.asText()\n val region get() = value[\"region\"]?.asText()\n val longitude get() = value[\"longitude\"]?.asText()\n val latitude get() = value[\"latitude\"]?.asText()\n}\n\ninterface NullableMapGetter{\n operator fun Map&lt;String, String?&gt;?.get(key: String) = this?.get(key)\n}\n\ninline class Priority(private val value : Map&lt;String, String?&gt;?) : NullableMapGetter{\n val id get() = value[\"id\"]?.asInt()\n val name get() = value[\"name\"]?.asText()\n val color get() = value[\"color\"]?.asText()\n}\n</code></pre>\n\n<p>And of course, you should use them:</p>\n\n<pre><code>data.forEach {\n println(it[\"permalink\"]?.asText())\n\n val location = Location(it[\"location\"])\n val priority = Priority(it[\"priority\"])\n createMention(location, priority)\n}\n\nfun createMention(\n location : Location,\n priority : Priority\n) = Mention(\n authorTags = authorTags,\n locContinent = location.continent,\n locCountry = location.country,\n locCity = location.city,\n locRegion = location.region,\n locLongitude = location.longitude,\n locLatitude = location.latitude,\n priorityId = priority.id,\n priorityName = priority.name,\n priorityColor = priority.color,\n)\n</code></pre>\n\n<h1>Collection functions</h1>\n\n<p>Don't know if it's possible, as most of the code doesn't compile as eg. mapper-declaration is absent. (code has to compile on code-review, so this question is actually of topic atm).</p>\n\n<h2><a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/map.html\" rel=\"nofollow noreferrer\">map</a></h2>\n\n<p>However, data.forEach does nothing else then mapping, so:</p>\n\n<pre><code>val mentions = mutableListOf&lt;Mention&gt;()\nval data = response[\"response\"][\"data\"]\ndata.forEach{\n //val newType = changeType(it)\n mensions.add(newType)\n}\n</code></pre>\n\n<p>can be rewritten to:</p>\n\n<pre><code>val mentions = response[\"response\"][\"data\"].map{\n changeType(it)\n // or return@map changeType(it)\n}\n</code></pre>\n\n<h2><a href=\"https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/join-to-string.html\" rel=\"nofollow noreferrer\">joinToString</a></h2>\n\n<p>Kotlin has buildin functions to join a collection to a string:\n it[\"author\"][\"tags\"]?.forEach {\n it?.asText()?.let {\n tags += it\n }\n }</p>\n\n<p>can be rewritten as:</p>\n\n<pre><code>val tags = it[\"author\"][\"tags\"].joinToString(\"\"){\n it?.asText()\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:55:59.647", "Id": "465887", "Score": "1", "body": "Thanks for the informative post, that's a lot to digest... When I use .map instead of forEach It fails when I try to persist it as it can't infer the type for some reason. Any idea why? I debugged and it is still an ArrayList<Mention> object after the .map body..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T15:06:13.463", "Id": "465889", "Score": "0", "body": "What happens if you provide the generics?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T17:52:07.207", "Id": "465914", "Score": "0", "body": "I tried many things but it kept complaining that it expects a type of (Itterable)<Mention>... for now I am back to the forEach as I had to get a sample of the data in the DB before tomorrow but would like to spend some time figuring this out still... I even tried .map{ }.toMutableList().asItterable ut no luck..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T18:16:55.153", "Id": "465918", "Score": "0", "body": "What did you mean by changeType(it)\n // or return@map changeType(it) in the .map body? I just had .map { Mention(/*constructor values)*/) } When I debugged I saw that it was a List<Mention> but it still didn't compile with the error being on the line where I call mentionRepo.saveAndFlush" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T20:21:27.467", "Id": "465942", "Score": "0", "body": "What is the function signature of saveAndFlush?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T13:04:47.303", "Id": "237563", "ParentId": "237513", "Score": "1" } } ]
{ "AcceptedAnswerId": "237563", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T20:04:06.683", "Id": "237513", "Score": "2", "Tags": [ "json", "spring", "kotlin" ], "Title": "Mapping a complex JSON response to two different JPA Entities" }
237513
<p>I have the following relationship in EF Core 3.1.1 (Many-To-Many):</p> <pre><code>public partial class Movie { public Movie() { Directors = new HashSet&lt;MovieDirector&gt;(); } public int Id { get; set; } public string Title { get; set; } public virtual ICollection&lt;MovieDirector&gt; Directors { get; set; } } public partial class Director { public Director() { MovieDirector = new HashSet&lt;MovieDirector&gt;(); } public string Id { get; set; } public string Name { get; set; } public virtual ICollection&lt;MovieDirector&gt; MovieDirector { get; set; } } public partial class MovieDirector { public int Id { get; set; } public int MovieId { get; set; } public string DirectorId { get; set; } public virtual Movie Movie { get; set; } public virtual Director Director { get; set; } } </code></pre> <p>And I have the following method to create a <code>Director</code>:</p> <pre><code>public Director CreateDirector(int movieId, Director director) { var movie = _repository.Movie.FirstOrDefault(w =&gt; w.Id == movieId); movie.Directors.Add(new MovieDirector{ Director = director }); _repository.SaveChanges(); return director; } </code></pre> <p>The <code>CreateDirector</code> method can perfectly create a new <code>Director</code> including relationships.</p> <p>My biggest question is if every time I need to insert in a table that has a relationship I will need:</p> <ol> <li><p>Find the parent/root entity (<code>Movie</code>)</p> </li> <li><p>Create a new <code>MovieDirector</code> object</p> </li> <li><p>Associate the new <code>MovieDirector</code> object with the parent/root, like:</p> <pre><code>movie.Directors.Add(new MovieDirector) </code></pre> </li> </ol> <p>Is this correct or is there some kind of shortcut?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T07:25:41.460", "Id": "465842", "Score": "2", "body": "This is a One-To-Many relationship not Many-To-Many. Or can the same Review reference to many Movies?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:47:02.917", "Id": "465881", "Score": "0", "body": "@keuleJ The example was Many-To-Many, but the context no! One review belong to one Movie. I change the context sample! ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-21T09:23:19.867", "Id": "500330", "Score": "0", "body": "Why are all of these `partial class`? Also, `CreateDirector` doesn't do what you say it does. The director is already created and passed as an argument, the method creates a `MovieDirector` and then returns the director for some reason." } ]
[ { "body": "<p>In this case you know the id value of the movie the new director should be associated with. That makes it easy to set the relationships without pulling the entire movie entity from the database:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public Director CreateDirector(int movieId, Director director)\n{\n director.MovieDirectors.Add(new MovieDirector { MovieId = movieId });\n\n _repository.Add(director);\n _repository.SaveChanges();\n\n return director;\n}\n</code></pre>\n<p>You may need another repository type, but the code you show isn't conclusive on that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T19:44:57.303", "Id": "244972", "ParentId": "237516", "Score": "1" } }, { "body": "<p>When two entities are related in many-to-many relationship, neither of them are a parent/root entity nor a dependent/child entity. They are two individual entities totally independent of each other. They are related, but neither of them depends on the other.</p>\n<p>At database level a parent/child dependency is mapped through a foreign-key. For a many-to-many relationship there is no foreign-key involved, and the relationship is mapped through a joining table, which we model with a joining entity at code level, (the <code>MovieDirector</code> entity in your example).</p>\n<p>So, if <code>Director</code> and <code>Movie</code> are in a many-to-many relationship, then <code>Movie</code> is by no means a parent entity of <code>Director</code>, or vice-versa. Therefore, you should always be able to create a <code>Director</code> entity independent of any information referencing any movie. And from that perspective I see a major flaw in your code - currently you cannot create a <code>Director</code> entity independently, you need a <code>movieId</code> for that (which you shouldn't).</p>\n<p>Think about a possible scenario where you might need to select one or more directors while creating a new movie, and that might be the first time some of those directors gets linked with a movie. What I'm trying to imply is, you can always have a director, or want to create one, for whom there is no movie in the database.</p>\n<p>The signature of your <code>CreateDirector</code> method should be like -</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public Director CreateDirector(Director director)\n</code></pre>\n<p>First setup any related entities (if there is any) before reaching the <code>CreateDirector</code> method -</p>\n<pre class=\"lang-cs prettyprint-override\"><code>director.MovieDirectors.Add(new MovieDirector { MovieId = movieId });\n</code></pre>\n<p>and then call for creating the new director -</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public Director CreateDirector(Director director)\n{\n _repository.Directors.Add(director);\n _repository.SaveChanges();\n return director;\n}\n</code></pre>\n<p>Now you can create a director independently or, along with its related entities. I hope that simplifies your current approach too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-20T21:33:10.153", "Id": "253722", "ParentId": "237516", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-18T22:03:13.377", "Id": "237516", "Score": "6", "Tags": [ "c#", "entity-framework-core" ], "Title": "Many-To-Many movie director system" }
237516
<p>I've been studying Java for some days and I'm just now starting to make some simple programs, I'd like to know if there's any 'noob' mistakes or habits that I could avoid.</p> <p>In other words: <strong><em>how could my code be more streamlined to Java?</em></strong></p> <p>My code:</p> <pre class="lang-java prettyprint-override"><code>import java.util.Scanner; public class Main { private static String reverse_string(String my_string) { String reversed_string = ""; for(int j = my_string.length() - 1; j &gt;= 0; j--) { reversed_string = reversed_string + my_string.charAt(j); } return reversed_string; } public static void main(String[] args) { System.out.print("Insert a 'String': "); Scanner input = new Scanner(System.in); String user_string = input.nextLine().toLowerCase().replace(" ", ""); if (user_string.equals(reverse_string(user_string))) { System.out.println("It is a palindrome."); } else { System.out.println("It is not a palindrome."); } } } </code></pre> <p>I believe there are already other alternatives to my <code>reverse_string</code> function, hence the 'reinventing the wheel' tag.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T11:54:34.477", "Id": "465862", "Score": "6", "body": "You know you don't actually have to produce a reversed copy of the string to check for palindromes, right? Use indices for the start/end and walk inwards until you meet / cross in the middle. (Handling Unicode surrogate pairs has to happen on the fly here, but I think it's possible to detect a surrogate pair when looking at the 2nd half.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T15:02:27.800", "Id": "465888", "Score": "0", "body": "@PeterCordes Sounds like a good potential answer to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T15:59:28.353", "Id": "465893", "Score": "0", "body": "@MJ713: A rewrite from scratch isn't really a code *review*. Examples of meet-in-the-middle implementations exist all over the place in all languages (although the vast majority are just for char[], not handling surrogate pairs). e.g. the canonical SO Q&A's top answer: [Check string for palindrome](//stackoverflow.com/q/4138827) (which happens to be in Java). Other answers there point out that Java's StringBuilder already has a `.reverse()` method so writing your own is unnecessary if you want simple (but inefficient) code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T16:06:45.713", "Id": "465896", "Score": "0", "body": "@PeterCordes Per [this meta answer](https://codereview.meta.stackexchange.com/questions/5045/complete-code-rewrite): \"Are answers that suggest complete rewrite of the code acceptable? Yes. Always. But not a code-only 'Here is how I would do it' answer.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T16:09:19.563", "Id": "465898", "Score": "0", "body": "@MJ713: Ah, I hadn't read that, and had the wrong impression from a comment that paraphrased it. Thanks. Anyway, given that there's a canonical Q&A about it on SO, and http://componentsprogramming.com/palindromes/ with detailed analysis of algorithm efficiency, I'm content to just link those and leave UTF-16 surrogate-pair handling as an exercise for the reader. (Especially since I don't have a Java dev env set up to test anything I might write.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T11:20:10.793", "Id": "466011", "Score": "0", "body": "Just a comment, but if your learning java you want to do something with objects not just static methods as you have here. As thats where the majority of the real world complexity will happen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T01:16:42.520", "Id": "466096", "Score": "0", "body": "I'm still learning haha, but i'll see what i can do" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-21T08:12:48.490", "Id": "466109", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. 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)*." } ]
[ { "body": "<p>To answer your comment, yes there are equivalent of PEP8 in java. I suggest <a href=\"https://checkstyle.sourceforge.io/\" rel=\"noreferrer\"><code>checkstyle</code></a>, this plugin works in lots of IDE / text editors and can be configured with your code style.</p>\n\n<h2>Code review</h2>\n\n<h3><code>reverse_string</code> method</h3>\n\n<ol>\n<li>In java, we try to use the upper-case version of <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"noreferrer\"><code>Snake case</code></a> only on constants / enums. For the methods and variables, I suggest that you use the <a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"noreferrer\"><code>Camel case</code></a> style.</li>\n</ol>\n\n<p><em>Before</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static String reverse_string(String my_string) \n{\n //[..]\n}\n</code></pre>\n\n<p><em>After</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static String reverseString(String myString) \n{\n //[..]\n}\n</code></pre>\n\n<ol start=\"2\">\n<li>When concatenating <code>String</code> in a loop, it's generally recommended to use a <a href=\"https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/StringBuilder.html\" rel=\"noreferrer\"><code>java.lang.StringBuilder</code></a> to gain performance and take fewer operations.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static String reverseString(String myString) \n{\n StringBuilder reversedString = new StringBuilder();\n\n for (int j = myString.length() - 1; j &gt;= 0; j--) \n {\n reversedString.append(myString.charAt(j));\n }\n\n return reversedString.toString();\n}\n</code></pre>\n\n<p>If you want not to use it, then I suggest the <code>+=</code> operator instead of the <code>+</code>; it will give the same result and make the code shorter.</p>\n\n<h2>Other observations</h2>\n\n<p>The code was missing a bit of formatting, but nothing too important, I sugest that you pick a formatter for your style (Horstmann style) depending on your IDE / text editor.</p>\n\n<h2>Refactored code</h2>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static String reverseString(String myString)\n{\n String reversedString = \"\";\n\n for (int j = myString.length() - 1; j &gt;= 0; j--) \n {\n reversedString += myString.charAt(j);\n }\n\n return reversedString;\n}\n\npublic static void main(String[] args) \n{\n System.out.print(\"Insert a 'String': \");\n\n Scanner input = new Scanner(System.in);\n String userString = input.nextLine().toLowerCase().replace(\" \", \"\");\n\n if (userString.equals(reverseString(userString))) \n {\n System.out.println(\"It is a palindrome.\");\n } \n else \n {\n System.out.println(\"It is not a palindrome.\");\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T01:23:22.260", "Id": "465810", "Score": "3", "body": "\"Refactored code\" section is still using snake case for the `reversed_string` variable. Also the last `}` is missing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T01:28:23.453", "Id": "465811", "Score": "1", "body": "For clarity, you could explain that constants are written in ALL_CAPS snake case, not just _any_ snake case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T01:39:37.400", "Id": "465813", "Score": "2", "body": "Fixed, thanks !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T11:48:16.497", "Id": "465861", "Score": "2", "body": "I'd suggest writing \"Camel case\" as \"camelCase\". When underlined as a link, it looks like capitalized Snake_case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T14:45:41.820", "Id": "465880", "Score": "1", "body": "Doesn't the official style guide for java recommend same-line braces, and not newline braces?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T15:13:30.633", "Id": "465890", "Score": "0", "body": "@Cruncher For C-like languages in general, it seems like [everyone has their favorite indentation style](https://en.wikipedia.org/wiki/Indentation_style#Brace_placement_in_compound_statements)...honestly it is more important to be consistent within a project, regardless of which style is actually picked. But yeah, I think same-line braces are \"official\" for Java." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T15:56:06.067", "Id": "465891", "Score": "1", "body": "@MJ713 I find it interesting how C-like languages, people just say to be consistent, but with languages like python people are like the gestapo when it comes to styling." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T16:02:38.367", "Id": "465895", "Score": "2", "body": "@Cruncher Whitespace actually has semantic meaning in Python, so there's both less room to play around and more reason to pay attention to style in the first place. There might also be historical factors; Python is younger than C, and its rise coincided with the rise of the web, which may have made it easier to share/enforce style standards...I'm just speculating." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T01:20:44.740", "Id": "237527", "ParentId": "237523", "Score": "13" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/237527/192133\">Doi9t's answer</a> is very good, but even with their improvements, there is still a problem: your code does not produce the correct answer in all cases.</p>\n\n<p>Java strings use <a href=\"https://en.wikipedia.org/wiki/UTF-16\" rel=\"nofollow noreferrer\">UTF-16</a> encoding. This means that a Java <code>char</code> is not large enough to store all Unicode characters. Instead some characters (for example, ) are stored as a <em>pair</em> of <code>char</code>s, and reversing the pair (as your code does) will result in nonsense data. See <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Character.html#unicode\" rel=\"nofollow noreferrer\">this documentation</a> for more details.</p>\n\n<p>Fortunately, the way UTF-16 is defined, <code>char</code>s that are <em>surrogates</em> (half-characters) have a completely separate range of values from <code>char</code>s that are Unicode characters by themselves. This means it is possible to test each <code>char</code> individually to see if it is a surrogate, and then have special handling to preserve the pairs.</p>\n\n<pre><code>import java.lang.Character;\nimport java.lang.StringBuilder;\nimport java.util.Scanner;\n\n&lt;...&gt;\n\n private static String reverseString(String myString) {\n StringBuilder reversedString = new StringBuilder();\n\n for (int j = myString.length() - 1; j &gt;= 0; j--) {\n char c = myString.charAt(j);\n if (Character.isLowSurrogate(c)) {\n j--;\n reversedString.append(myString.charAt(j));\n }\n reversedString.append(c);\n }\n\n return reversedString.toString();\n }\n</code></pre>\n\n<p>If you <em>really</em> wanted to re-invent the wheel, I think <code>Character.isLowSurrogate(c)</code> could be replaced with <code>c &gt;= '\\uDC00' &amp;&amp; c &lt;= '\\uDFFF'</code>, though I have not personally tested this.</p>\n\n<hr>\n\n<p>As <a href=\"https://codereview.stackexchange.com/users/50567/peter-cordes\">Peter Cordes</a> pointed out in a comment, we do not even <em>need</em> to reverse the string in order to detect a palindrome. Instead we can examine the input string in place, comparing the first character to the last, the second to the next-to-last, etc., until we reach the middle. This may be more performant.</p>\n\n<p>We need special handling for 2-<code>char</code> characters in this case as well; fortunately, the String class has methods for pulling <em>code point</em> values instead of pulling <code>char</code> values directly.</p>\n\n<ul>\n<li><code>codePointAt(int index)</code> behaves similarly to <code>charAt(int index)</code> in most cases, but if the <code>char</code> at the given index is the first half of a surrogate pair, it will return the full value of the pair.</li>\n<li><code>codePointBefore(int index)</code> approaches the problem from the other end; if the <code>char</code> <em>before</em> the given index is the <em>last</em> half of a surrogate pair, it will return the full value of the pair.</li>\n</ul>\n\n<pre><code> private static boolean isPalindrome(String myString) {\n int len = myString.length();\n for (int i = 0; i &lt; len / 2; ++i) {\n int frontHalfCharacter = myString.codePointAt(i);\n int backHalfCharacter = myString.codePointBefore(len - i)\n if (frontHalfCharacter != backHalfCharacter) {\n return false;\n }\n if (Character.isSupplementaryCodePoint​(frontHalfCharacter)) { // i.e. if this is a 2-char character\n i++;\n }\n }\n return true; \n }\n</code></pre>\n\n<hr>\n\n<p>And while we're on the topic of Unicode, you should of course read <a href=\"https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/\" rel=\"nofollow noreferrer\">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a>, if you haven't already.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T02:41:25.853", "Id": "465819", "Score": "3", "body": "Knowing that a letter can take two characters is vital. A close next is the StringBuilder.reverse() method. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T02:45:00.713", "Id": "465824", "Score": "1", "body": "@TorbenPutkonen They deliberately chose to do it the hard way, hence the [reinventing-the-wheel tag](https://codereview.stackexchange.com/questions/tagged/reinventing-the-wheel)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T02:57:33.143", "Id": "465830", "Score": "1", "body": "OP specifically asked for an alternative to the home grown reverse algorithm. The reinventing-the-wheel tag is stupid because it uses categorization tools as content and the tag name doesn't describe it's purpose. You have to go read the tag's description to figure out what it means." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T03:01:11.930", "Id": "465831", "Score": "1", "body": "@TorbenPutkonen OP didn't actually ask for alternatives, they just said they were aware that alternatives probably existed...but I see your point. Maybe post to https://codereview.meta.stackexchange.com/?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T02:11:02.183", "Id": "237528", "ParentId": "237523", "Score": "9" } }, { "body": "<p>In java is the preferred way of curly brace placing on the same line like you can see in code snippets in <a href=\"https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141270.html\" rel=\"nofollow noreferrer\">Oracles Style Guide</a>.</p>\n\n<hr>\n\n<p><code>reverse_string</code> has a <a href=\"https://blog.codinghorror.com/code-smells/\" rel=\"nofollow noreferrer\">type embedded</a> in its name which leads to a code smell.</p>\n\n<p>The disadvantage is that if you want to change the type of the parameter you have to change the method name too.</p>\n\n<p>Additional the invocation looks messy and redundant compared to a method name without the embedded type:</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if (user_string.equals(reverse_string(user_string)))\n</code></pre>\n</blockquote>\n\n<p>compared to</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (user_string.equals(reverse(user_string)))\n</code></pre>\n\n<hr>\n\n<p>Code can be descriptive by choosing good variable names.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>Scanner input = new Scanner(System.in);\nString user_string = input.nextLine().toLowerCase().replace(\" \", \"\");\n</code></pre>\n</blockquote>\n\n<p>I think <code>input</code> fits better than <code>user_string</code> to describe the input of a user:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Scanner scanner = new Scanner(System.in);\nString input = scanner.nextLine().toLowerCase().replace(\" \", \"\");\n\nif (input.equals(reverse(input))) { /*...*/ }\n</code></pre>\n\n<hr>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if (user_string.equals(reverse_string(user_string)))\n{\n System.out.println(\"It is a palindrome.\");\n} else\n{\n System.out.println(\"It is not a palindrome.\");\n}\n</code></pre>\n</blockquote>\n\n<p>The two <code>System.out.println</code> are a bit like a duplication. You could save the message you want to print in a variable and then print it once to the console:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>String message;\nif (user_string.equals(reverse_string(user_string))) {\n message = \"It is a palindrome.\";\n} else {\n message = \"It is not a palindrome.\";\n}\n\nSystem.out.println(message);\n</code></pre>\n\n<p>Or even shorter with the <a href=\"https://docs.oracle.com/cd/E57185_01/IRWUG/ch21s03s01s02.html\" rel=\"nofollow noreferrer\">ternary operator</a>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>String message = user_string.equals(reverse_string(user_string)) ? \"It is a palindrome.\" : \"It is not a palindrome.\";\nSystem.out.println(message);\n</code></pre>\n\n<hr>\n\n<p>I know that this a small script but I would like to introduce to think in objects:</p>\n\n<pre><code>public class Main {\n\n private static final WhiteSpaceFreeScanner scanner = new WhiteSpaceFreeScanner(new Scanner(System.in));\n\n public static void main(String[] args) {\n final Input input = scanner.nextLine();\n\n String message = input.isPalindrome() ? \"It is a palindrome.\" : \"It is not a palindrome.\";\n System.out.println(message);\n }\n}\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>class WhiteSpaceFreeScanner {\n\n private final Scanner scanner;\n\n CustomScanner(Scanner scanner) {\n this.scanner = scanner;\n }\n\n Input nextLine() {\n String input = scanner.nextLine().toLowerCase().replace(\" \", \"\");\n return new Input(input);\n }\n\n}\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Input {\n private final String value;\n\n public Input(String value) {\n this.value = value;\n }\n\n Input reversed() { /* ... */ }\n\n boolean isPalindrome() {\n return this.equals(reversed());\n }\n\n @Override\n public boolean equals(Object o) { /* ... */ }\n\n @Override\n public int hashCode() { /* ... */ }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T15:59:00.860", "Id": "465892", "Score": "0", "body": "While the object example seems clearly over-engineered to me, it is a good learning point. +1 just for composition over inheritance. EDIT: Any reason to not publicize reversed? While not required for the program specifically, it would be generally useful for the api. EDIT2: Nvm, forgot java default is same-package, not protected" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T16:20:55.647", "Id": "466045", "Score": "0", "body": "`String message = \"It is\" + (user_string.equals(reverse_string(user_string)) ? \"\":\"not\" ) +\" a palindrome.\";` - very nice review!!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T16:24:44.793", "Id": "466046", "Score": "0", "body": "`CustomScanner` would be an `AlphaNumericScanner` or an `WhiteSpaceFreeScanner` if it would remove other white space" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T08:22:48.410", "Id": "237544", "ParentId": "237523", "Score": "10" } }, { "body": "<p>For <code>reverse_string</code>, it would probably be most efficient to create an array of <code>char</code>s and then construct a string from it. Note that I have not tested this code.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static String reverse_string(String my_string)\n{\n char[] chars = new char[my_string.length()];\n for(int i = 0; i &lt; chars.length; ++I)\n {\n chars[i] = my_string.charAt(chars.length - 1 - i); // The two indices can be swapped\n }\n return new String(chars);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T11:52:11.563", "Id": "237629", "ParentId": "237523", "Score": "2" } }, { "body": "<p>Do you actually need to create the reversed string. Why not just go over the string from both directions.</p>\n\n<pre><code> String palindrome = \"radar\";\n isPalindrome(palindrome, 0, palindrome.length() -1); \n\n // Could be converted to loop if wanted.\n private static boolean isPalindrome(String candidate, int startIndex, int endIndex) {\n if(startIndex &gt;= endIndex) {\n // Has passed each other or pointing towards same character.\n return true;\n }\n else if (candidate.charAt(startIndex) == candidate.charAt(endIndex)) {\n return isPalindrome(candidate, startIndex + 1, endIndex - 1);\n }\n\n return false;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T17:10:51.403", "Id": "466049", "Score": "0", "body": "Yeah, great idea! I'll try that later" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-20T15:23:40.053", "Id": "237640", "ParentId": "237523", "Score": "2" } } ]
{ "AcceptedAnswerId": "237527", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-19T00:03:17.140", "Id": "237523", "Score": "9", "Tags": [ "java", "beginner", "reinventing-the-wheel", "palindrome" ], "Title": "Palindrome checker program" }
237523