body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I've made a solution for a problem which involves changing order of objects having some mass, so it costs a mass of an object A and a mass of an object B to make a swap. The program needs to read a number of objects, their masses, their starting and ending order and calculate lowest cost of swapping objects to final order. The solution is correct in terms of calculations. The txt file has numbers in each line and name of a file is passed as command line argument. I would like to ask how should I split operations into separate functions and load data? What can I do to make a code cleaner? I am also wondering what exceptions should I made for invalid inputs?</p> <pre><code>#define min(a,b) ((a) &lt; (b) ? (a) : (b)) #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;vector&gt; void readFromFile(int argc, char* argv[],const int MAX_VERTEXES, const int MIN_VERTEXES, int &amp;n, int &amp;minWeightGlobally, std::vector&lt;int&gt; &amp;weights, std::vector&lt;int&gt; &amp;startingOrder, std::vector&lt;int&gt; &amp;endingOrder) { std::ifstream file; if (argc &gt;= 2) { file.open(argv[1]); } else { throw std::exception("No parameter passed"); } std::string line; if (file.is_open()) { for (int z = 0; z &lt; 4; z++) { std::getline(file, line); if (line.empty()) throw std::logic_error("Invalid input"); std::istringstream iss(line); if (z == 0) { iss &gt;&gt; n; if (n&lt;MIN_VERTEXES || n&gt;MAX_VERTEXES) throw std::exception("Invalid amount of vertices"); } if (z == 1) { weights.reserve(n); for (int a = 0; a &lt; n; a++) { int d; iss &gt;&gt; d; weights.push_back(d); minWeightGlobally = min(minWeightGlobally, weights[a]); } } if (z == 2) { startingOrder.reserve(n); for (int a = 0; a &lt; n; a++) { int d; iss &gt;&gt; d; startingOrder.push_back(d - 1); } } if (z == 3) { endingOrder.reserve(n); for (int a = 0; a &lt; n; a++) { int d; iss &gt;&gt; d; endingOrder.push_back(d - 1); } } } file.close(); } else { throw std::exception("Unable to open file"); } } long long calculateLowestCostOfWork(int const &amp;n, int const &amp;MAX_WEIGHT, int const &amp;minWeightGlobally, std::vector&lt;int&gt;&amp; weights, std::vector&lt;int&gt;&amp; startingOrder, std::vector&lt;int&gt;&amp; endingOrder) { std::vector&lt;int&gt; permutation(n); std::vector&lt;bool&gt; visitedVertexes(n); long long result = 0; //constructing permutation p for (int i = 0; i &lt; n; i++) permutation[endingOrder[i]] = startingOrder[i]; for (int i = 0; i &lt; n; i++) { int numberOfElementsInCycle = 0; int minWeightInCycle = MAX_WEIGHT; long sumOfWeightsInCycle = 0; if (!visitedVertexes[i]) { int x = i; //decomposition for simple cycles and calculating parameters for each cycle while (!visitedVertexes[x]) { visitedVertexes[x] = true; numberOfElementsInCycle++; x = permutation[x]; sumOfWeightsInCycle += weights[x]; minWeightInCycle = min(minWeightInCycle, weights[x]); } //calculating lowest cost for each cycle result += (long long)min((sumOfWeightsInCycle + (numberOfElementsInCycle - 2) * minWeightInCycle), (sumOfWeightsInCycle + minWeightInCycle + (numberOfElementsInCycle + 1) * minWeightGlobally)); } } return result; } int main(int argc, char *argv[]) { const int MAX_WEIGHT = 6500, MAX_VERTEXES = 1000000, MIN_VERTEXES = 2; std::vector&lt;int&gt; weights, startingOrder, endingOrder; int n=0; int minWeightGlobally = MAX_WEIGHT; try { readFromFile(argc, argv,MAX_VERTEXES, MIN_VERTEXES, n, minWeightGlobally, weights, startingOrder, endingOrder); } catch (...) { std::cout &lt;&lt; "Error"; } std::cout &lt;&lt; calculateLowestCostOfWork(n,MAX_WEIGHT,minWeightGlobally,weights,startingOrder,endingOrder); return 0; } </code></pre> <hr> <p>The input file is in form like below, first line (int n in code) it's telling about amount of objects (that's a nice name to include). Second line has their weights, third line startingOrder and last endingOrder. The task is to calculate a cost of move of objects(a cost is defined by sum of weights of two objects that are moved) from starting to ending order. </p> <blockquote> <pre><code>8 197 170 124 180 128 163 188 140 2 5 7 8 1 3 6 4 5 6 1 8 2 4 7 3 </code></pre> </blockquote> <p>So ideally there should be exactly as many numbers in each row in each vector as in first line. The worst case scenario is obviously no values in any line after first line, so we will move through undeclared memory or out of bounds and we will get out of bounds exception. In the other cases program could calculate something, although there is a little possibility that it will calculate something good e.g input like this is valid e.g</p> <blockquote> <pre><code>8 197 170 124 180 128 163 188 140 1 2 3 3 1 2 </code></pre> </blockquote> <p>is valid, but obviously it should calculate for 8 numbers, not for only three.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T05:56:21.533", "Id": "439527", "Score": "0", "body": "Hello. I am new to C++.Could you explain what `long long functionName` does ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T06:04:53.193", "Id": "439528", "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)*. If your changes to the code are substantial, consider asking a follow-up question instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T14:16:55.193", "Id": "439622", "Score": "0", "body": "@ManosKounelakis It's calculating the lowest cost of swaping of objects(swap is defined by changing two objects position and cost of that swap is sum of masses first and second object) from starting order into ending order. Permutation array is kinda function of changing (permutation) collection->collection, so i've included it into function permutation(ending order)=startingOrder. It's creating a simple graph with edges that e.g 1 has to be in place 2, that's what permutation function is saying. VisitedVertexes array is default set with false values. So loops are traveling through graph." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T14:22:03.560", "Id": "439625", "Score": "0", "body": "Then you can have two methods of swapping, either you make swaps with lowest weight in cycle or you can \"borrow\" an object with lowest weight globally and make swaps with it. So in min(method1, method2) i am picking the lowest cost. Then i sum it up into result and do loops as long as there are cycles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T14:45:32.137", "Id": "439630", "Score": "0", "body": "@JanDycz no I was asking about the function signature `long long functionName`. I haven't seen something similar." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T16:00:49.830", "Id": "439636", "Score": "0", "body": "@ManosKounelakis Well i am returning a result of the type - long long, it's just normal type like any other. As far as i know Long long is 64 bit type on any platform (32 or 64-bit platform), but a type long can be 32 or 64 bits depending on platform. So i've avoided to return long, because my function can exceed 32-bit value. Please see https://en.cppreference.com/w/cpp/language/types" } ]
[ { "body": "<p>Some minor comments:</p>\n\n<ul>\n<li><p>No need to define <code>min</code>. Just <code>#include &lt;algorithm&gt;</code>and use <code>std::min</code>.</p></li>\n<li><p>Move your magic numbers (like <code>MAX_WEIGHT</code>) right after the includes. That way, you avoid passing them around your methods.</p></li>\n<li><p>Rather than returning all your vectors from <code>readFromFile</code> as output variables, and in order to shorten your type signature, return a struct instead in that function: </p></li>\n</ul>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>struct MassObjectsDescription {\n std::vector&lt;int&gt; weights;\n std::vector&lt;int&gt; startingOrder;\n std::vector&lt;int&gt; endingOrder;\n // Probably more fields here...\n}\n\nMassObjectsDescription readFromFile(int argc, char* argv[]) {\n // ...\n}\n</code></pre>\n\n<p>You may want to move to classes in further iterations of your code.</p>\n\n<ul>\n<li><p>No need to <code>return 0</code> at the end of the main method.</p></li>\n<li><p>Rather than reserving <span class=\"math-container\">\\$n\\$</span> elements on vectors, instantiate them with the appropriate size as you have done in <code>std::vector&lt;int&gt; permutation(n);</code>.</p></li>\n<li><p><code>int const &amp;n</code>. You may want to remove the reference to <code>n</code> as it is const, and there is no benefit (in fact, any) by passing the reference of such a little variable as an integer. Good job, though, doing it with vectors; it is a good practice doing so in order to avoid unnecessary copies.</p></li>\n<li><p>Consider splitting your line <code>result +=</code> into several lines with auxiliary variables. It is impossible guessing what's going on with such long line.</p></li>\n<li><p><code>int x = i;</code>. You first assign <code>x</code> to <code>i</code>, but suddenly it's got a value from <code>permutation</code> vector. Use <code>i</code> until changing its value and consider renaming the variable.</p></li>\n<li><p>You are chaining <code>if(z==0)</code>, <code>if(z==1)</code>, <code>if(z==2)</code>... It is good practice to use <code>else if</code> or even switch statements. Plus, it would be a good idea creating a function that you may reuse to create vectors from istringstreams:</p></li>\n</ul>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>vector&lt;int&gt; readVector(std::istringstream&amp; iss, int n) {\n vector&lt;int&gt; v(n);\n for (int i = 0; i &lt; n; ++i) {\n int d;\n iss &gt;&gt; d;\n v[i] = d - 1;\n }\n return v;\n}\n</code></pre>\n\n<ul>\n<li><p>As a general rule, try to initialize variables <em>as close</em> to their first use. For instance, in your code you shouldn't be able to see the word <em>vector</em> in your main method; everything should be encapsulated on your methods.</p></li>\n<li><p>Also, as a general rule, try to minimize the number of parameters of your functions. With the tips that I have given you above, probably you will end up having up to 3 or 4 parameters per function. </p></li>\n</ul>\n\n<p>Hopefully somebody else can give you some advice about exceptions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T02:10:55.760", "Id": "439339", "Score": "0", "body": "Thank you for your feedback and advices.\nIs it advisable to include whole <algorithm> only for one std::min()? \n>Rather than reserving n elements on vectors, instantiate them with the appropriate size as you have done in std::vector<int> permutation(n);.\nBut how if i don't know the size before reading n from file?\n\n>Your line while (!visitedVertexes[x]) seems redundant and should be replaced by an if, as at most 1 iteration is performed.\n>int x = i; \nWell i could put here x=0, since i am iterating from 0, first index of any container." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T02:11:12.757", "Id": "439340", "Score": "0", "body": "While loop is needed for traversal, you will move from vertex to vertex as long as there is a need for each cycle e.g1 2 3 4 5 |||||||\n4 3 2 1 5\nIt's 2 cycles 1->4 4->1 and 2->3 3->2 and third cycle already in place 5->5. So in best case scenario all objects are in same place, so you iterate i<n times and do nothing in while loop, because in this case permutation[5-1]=[5-1], so it's already pointing to itself and it will set visitedVertexes to true, so with iterator i, i ensure that i will visit every vertex/node, even when there is no jumping around." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T02:11:15.413", "Id": "439341", "Score": "0", "body": "Otherwise you need to jump to next (unvisited) vertex and get values from there to swap masses in the cycle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T02:24:49.093", "Id": "439342", "Score": "0", "body": "\"at most 1 iteration is performed\" - no, don't miss `x = permutation[x];`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T07:02:07.157", "Id": "439355", "Score": "0", "body": "The define about min is not only not needed, it is UB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T10:57:24.800", "Id": "439392", "Score": "0", "body": "My bad about the ```while``` loop -- got confused with ```x```." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T15:39:31.937", "Id": "439429", "Score": "0", "body": "It doesn't make any difference whether you reserve or pre-allocate with a trivial type like `int`, but it can make a huge difference with heavier weight classes (where you have to default construct, and then copy assign). I think \"always use reserve\" is a good habit to get into." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T18:31:37.083", "Id": "439456", "Score": "0", "body": "@L.F. How is it UB?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T19:51:36.897", "Id": "439466", "Score": "0", "body": "@trentcl Suppose that `<algorithm>` contains the code `template <class T> const T& min(const T& a, const T& b);` and another header includes it. Then it becomes `template <class T> const T& ((const T& a) < (const T& b) ? (const T& a) : (const T& b));`. Boom!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T20:14:46.657", "Id": "439473", "Score": "0", "body": "@L.F. I don't think that's UB. It's just a syntax error. Undefined behavior is a property of an *executing* program; if your program doesn't even compile, it doesn't have any behavior, so it can't be undefined." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T20:17:54.277", "Id": "439475", "Score": "0", "body": "Technically, that program would be [*ill-formed*](https://en.cppreference.com/w/cpp/language/ub)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T20:19:50.890", "Id": "439476", "Score": "0", "body": "@trentcl That’s just an example. The implementation can (theoretically) use the name in a way that makes the program compile and do the “undefined” thing. See [macro.names]/1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T20:29:31.107", "Id": "439481", "Score": "0", "body": "Ah, I see, the compiler is allowed to invoke UB because you violated a constraint for which a diagnostic was not issued. Fair enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T04:33:04.743", "Id": "439522", "Score": "0", "body": "I've rebuilded a code, according to your advices. Thank you for your feedback." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T00:27:26.200", "Id": "226148", "ParentId": "226145", "Score": "9" } }, { "body": "<p>I would just point out that the macro version of min is inferior.</p>\n\n<pre><code>#define min1(a,b) ((a) &lt; (b) ? (a) : (b))\ntemplate&lt;typename T&gt;\ninline min2(T const&amp; a, T const&amp; b) {return a &lt; b ? a : b;}\n</code></pre>\n\n<p>Think of this situation.</p>\n\n<pre><code>min1(a1++, 5) // how many times is a incremented?\nmin2(a1++, 5)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T07:04:14.337", "Id": "439357", "Score": "0", "body": "It is not only inferior, it is UB. (And it will actually cause a ton of problems on an implementation that doesn’t bother parenthesizing min everywhere.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T10:58:15.267", "Id": "439393", "Score": "1", "body": "Pardon my ignorance, but what is UB?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T11:37:09.810", "Id": "439400", "Score": "2", "body": "@JnxF: Undefined Behaviour, which basically means the compiler is allowed to generate any code it wants to, including no code at all, code that formats your hard disk, or code that kills your kitten." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T11:58:31.730", "Id": "439402", "Score": "0", "body": "Completely true." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T18:03:18.420", "Id": "439449", "Score": "0", "body": "@L.F. It doesn't seem to be UB (see rule 7 [here](https://en.cppreference.com/w/cpp/language/eval_order))." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T19:48:05.527", "Id": "439463", "Score": "1", "body": "@HolyBlackCat I am talking about the macro name `min` which may screw up the header. I wasn’t really thinking about order of evaluation :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T19:48:33.270", "Id": "439464", "Score": "1", "body": "@HolyBlackCat Its still multiple updates in the same expression. So even if it is not UB its still going to give you nasty surprizes with multiple updates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T19:52:49.077", "Id": "439468", "Score": "0", "body": "@HolyBlackCat To copy my another comment: `template <class T> const T& min(const T& a, const T& b);` becomes `template <class T> const T& ((const T& a) < (const T& b) ? (const T& a) : (const T& b));`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T20:13:21.177", "Id": "439472", "Score": "1", "body": "(See [\\[macro.names\\]/1](http://eel.is/c++draft/macro.names#1).)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T06:20:12.063", "Id": "226154", "ParentId": "226145", "Score": "7" } }, { "body": "<ul>\n<li>Don’t use macros in place of functions (or function templates). Use standard functions where appropriate (i.e. <code>std::min</code>).</li>\n<li>Include all necessary headers (<code>&lt;exception&gt;</code>, <code>&lt;stdexcept&gt;</code>).</li>\n<li>Fix the compile errors in your code: <code>std::exception</code> has no constructor accepting a C string.</li>\n<li>Separate concerns: each function should have a single responsibility. In particular, this means that <code>readFromFile</code> should not receive <code>argc</code> and <code>argv</code>. It probably also shouldn’t receive all the other arguments, and instead <em>return</em> the result (as an appropriately defined struct of vectors).</li>\n<li>In C++, unlike in C, <code>*</code> and <code>&amp;</code> in declarations go with the <em>type</em>, not with the variable name: <code>int&amp; n</code>, not <code>int &amp;n</code>.</li>\n<li>Do not use RANDOM_CAPITALS in parameter names, regardless of whether the parameter is <code>const</code>.</li>\n<li>Respect natural ordering: <code>min_vertexes</code> should come before <code>max_vertexes</code>.</li>\n<li>Use guard clauses and early exit: Don’t indent the whole body of your function if the file successfully opened. Instead, check for failure and return/throw. Then continue without <code>else</code>.</li>\n<li>But do not test whether the file was successfully opened, that’s useless. Instead, you <em>must</em> test whether each individual file reading operation was successful. You currently fail to do this.</li>\n<li>I know people claim that this is a matter of opinion, but your bracing style is wasting <em>a lot</em> of vertical space: Your <code>readFromFile</code> function is 64 lines long. When putting the opening brace (and <code>else</code>) on the previous line, the function shrinks to 50 lines. 15% less. That’s a substantial reduction, and the whole function now fits on my screen. This is a <em>drastic readability improvement</em>.</li>\n<li>Use consistent whitespace around operators. You mostly do this, but not everywhere.</li>\n<li>Do not <code>close</code> the file explicitly unless you handle potential errors. The file will be closed automatically once the variable falls out of scope.</li>\n<li>Use descriptive names. Single-letter variables in loops <em>can</em> be fine but <code>z</code>,\n<code>a</code> and <code>d</code> are cryptic names. <code>i</code>… as a loop variable is conventional.</li>\n<li>Avoid magic constants. Why does the main loop go to 4? You seem to encode a state machine but the code doesn’t make this obvious.</li>\n<li>Keep variable scope as close as possible (e.g. declare <code>line</code> inside the loop).</li>\n<li>Use appropriate standard algorithms; for instance, to read n values in a loop, use <code>std::copy_n</code> with <code>istream_iterator</code>s.</li>\n<li>Don’t pass <code>int</code> (nor similar, small types) as <code>const&amp;</code>, pass it by value.</li>\n<li>I think the <code>if (!visitedVertexes[x])</code> code is redundant and could be merged with the inner loop, but I currently don’t see how to do this well (= readably and efficiently). Still, consider whether this part of the algorithm can be restructured.</li>\n<li>Don’t use C-style casts. In fact, the widening cast to <code>long long</code> here is unnecessary anyway.</li>\n<li>Use local variables to break up excessively long expressions.</li>\n<li>Use comments that describe <em>why</em> something is being done. The current comments don’t help me understand the code.</li>\n<li>Use helper functions for repeated code, or when extracting code makes the logic more readable.</li>\n<li><code>MAX_WEIGHT</code> is unnecessary, and its value is completely arbitrary</li>\n<li>Don’t swallow errors: your <code>catch (...)</code> means that all the informative error messages you had get lost.</li>\n<li>In case of error, do <em>not</em> <code>return 0</code> from <code>main</code>. You need to return an error code (usually 1).</li>\n<li>Output error messages to STDERR, not STDOUT.</li>\n</ul>\n\n<p>Which leaves us with something like this:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;iterator&gt;\n#include &lt;limits&gt;\n#include &lt;sstream&gt;\n#include &lt;stdexcept&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\nstruct ObjectCollection {\n std::vector&lt;int&gt; weights;\n std::vector&lt;int&gt; startingOrder;\n std::vector&lt;int&gt; endingOrder;\n int minWeight;\n};\n\nstd::vector&lt;int&gt; readOrder(std::istream&amp; is, int const n) {\n std::vector&lt;int&gt; output;\n output.reserve(n);\n std::copy_n(std::istream_iterator&lt;int&gt;{is}, n, std::back_inserter(output));\n std::transform(begin(output), end(output), begin(output), [](int x) {return x - 1;});\n // FIXME: Optionally test for `is.fail()` here.\n return output;\n}\n\nObjectCollection readFromFile(std::string const&amp; filename, int const min_vertexes, int const max_vertexes) {\n std::ifstream file{filename};\n std::vector&lt;int&gt; weights;\n std::vector&lt;int&gt; startingOrder;\n std::vector&lt;int&gt; endingOrder;\n int n;\n\n for (int state = 0; state &lt; 4; ++state) {\n std::string line;\n if (! std::getline(file, line)) throw std::logic_error{\"Unable to read file\"};\n // FIXME: This test is pretty useless: You filter empty input but not truncated input or too long input.\n if (line.empty()) throw std::logic_error{\"Invalid input\"};\n std::istringstream iss{line};\n\n if (state == 0) {\n if (! (iss &gt;&gt; n)) throw std::logic_error{\"Failed to read n\"};\n if (n &lt; min_vertexes || n &gt; max_vertexes) throw std::logic_error(\"Invalid amount of vertices\");\n } else if (state == 1) {\n weights.reserve(n);\n std::copy_n(std::istream_iterator&lt;int&gt;{iss}, n, std::back_inserter(weights));\n } else if (state == 2) {\n startingOrder = readOrder(iss, n);\n } else {\n endingOrder = readOrder(iss, n);\n }\n }\n\n int const minWeight = *std::min_element(begin(weights), end(weights));\n return {weights, startingOrder, endingOrder, minWeight};\n}\n\nlong long calculateLowestCostOfWork(ObjectCollection const&amp; objects) {\n int const n = objects.weights.size();\n std::vector&lt;int&gt; permutation(n);\n\n // constructing permutation p\n for (int i = 0; i &lt; n; ++i)\n permutation[objects.endingOrder[i]] = objects.startingOrder[i];\n\n long long result = 0;\n std::vector&lt;bool&gt; visitedVertexes(n);\n\n for (int i = 0; i &lt; n; ++i) {\n int numberOfElementsInCycle = 0;\n int minWeightInCycle = std::numeric_limits&lt;int&gt;::max();\n long sumOfWeightsInCycle = 0;\n if (! visitedVertexes[i]) {\n int x = i; // FIXME: Use proper name for `x`.\n // decomposition for simple cycles and calculating parameters for each cycle\n while (! visitedVertexes[x]) {\n visitedVertexes[x] = true;\n ++numberOfElementsInCycle;\n x = permutation[x];\n sumOfWeightsInCycle += objects.weights[x];\n minWeightInCycle = std::min(minWeightInCycle, objects.weights[x]);\n }\n // calculating lowest cost for each cycle\n // FIXME: Use proper names.\n int const cycleCost = (numberOfElementsInCycle - 2) * minWeightInCycle;\n int const globalCost = minWeightInCycle + (numberOfElementsInCycle + 1) * objects.minWeight;\n result += sumOfWeightsInCycle + std::min(cycleCost, globalCost);\n }\n }\n return result;\n}\n\nint main(int argc, char *argv[]) {\n if (argc != 2) {\n std::cerr &lt;&lt; \"Error: missing filename\\n\";\n return 1;\n }\n int const MIN_VERTEXES = 2;\n int const MAX_VERTEXES = 1000000;\n try {\n auto objects = readFromFile(argv[1], MIN_VERTEXES, MAX_VERTEXES);\n std::cout &lt;&lt; calculateLowestCostOfWork(objects);\n } catch (std::exception const&amp; ex) {\n std::cerr &lt;&lt; \"Error: \" &lt;&lt; ex.what() &lt;&lt; \"\\n\";\n return 1;\n }\n}\n</code></pre>\n\n<p>(Untested, since I have no test data and don’t know what the algorithm is supposed to do.)</p>\n\n<p>As mentioned elsewhere, the <em><code>reserve</code>-and-<code>push_back</code></em> pattern could be replaced by resizing the objects and then just copying directly. This means that you’d be performing redundant zero-initialisation, but on the other hand you’d avoid an out-of-bounds test inside the <code>push_back</code>. You need to benchmark to find out which of these variants is faster. However, this is unlikely to be a bottleneck in your code. Don’t sweat the small stuff.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T04:32:36.187", "Id": "439520", "Score": "0", "body": "I've rebuilded a code, according to your advices. Thank you for your feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T12:46:49.617", "Id": "226171", "ParentId": "226145", "Score": "4" } }, { "body": "<h2>Design</h2>\n\n<p>You biggest problem is encapsulation.<br>\nYou treat your three different properties as three different data items rather than as a single data item. I feel it would be more logical to combine the data into a single item.</p>\n\n<p>I suppose you did it this way because of the design of the input file. If given the chance I would change the format of this file. Define the properties of each item (start, end, weight) all on the same line. But even if you can't change the format I would still try and encapsulate the data into a single item.</p>\n\n<h2>Error</h2>\n\n<p>If the input file is mis-formed then you probably will not detect it and simply fill the input arrays with garbage values.</p>\n\n<h1>Code Review</h1>\n\n<p>Please no:</p>\n\n<pre><code>#define min(a,b) ((a) &lt; (b) ? (a) : (b))\n</code></pre>\n\n<p>There is no reason to use macros (apart from the one thing they are good at which is conditional compilation of code, preferably to take into account different system implementations).</p>\n\n<p>Looks like <code>MAX_VERTEXES</code> and <code>MIN_VERTEXES</code> and <code>MAX_WIGHT</code> should simply be global static state, rather than passed around the application. Note global variables are OK iff they are constant (ie non mutable).</p>\n\n<pre><code>int constexpr MaxVertexes = 1000000;\nint constexpr MinVertexes = 2;\nint constexpr MaxWeight = 6500;\n</code></pre>\n\n<p>The other thing you should note is that all capitol identifiers are traditionally reserved for macros. Using them as variable names is iffy at best going to cause issues at worst. Please make sure all non macros use standard variable names.</p>\n\n<p>If things are non mutable then mark them with <code>const</code> or <code>constexpr</code> to indicate that they are non mutable. This will make sure the compiler tells you about an error if you accidentally change their value.</p>\n\n<p>I would throw exception if the file name is not passed or the file did not open. Opps having read it threw now I see you do throw on open. I would change the order though so all the throwing is at the top. Then your code is all at the same indent level.</p>\n\n<pre><code> std::ifstream file;\n if (argc &gt;= 2)\n {\n file.open(argv[1]);\n }\n else\n {\n throw std::exception(\"No parameter passed\");\n }\n std::string line;\n\n if (file.is_open())\n {\n</code></pre>\n\n<p>Your code is of the form:</p>\n\n<pre><code> if (isGood()) {\n doGoodStuff();\n }\n else {\n throw error;\n }\n</code></pre>\n\n<p>Putting all your error tests at the top puts all your explicit checking and error handling at the top.</p>\n\n<pre><code> // Check pre-conditions.\n if (!isGood()) {\n throw error;\n }\n\n // All your pre-conditions have been checked.\n doGoodStuff();\n</code></pre>\n\n<p>So your code above I would have written like this:</p>\n\n<pre><code> std::ifstream file;\n if (argc &lt; 2)\n {\n throw std::exception(\"No parameter passed\");\n }\n\n // Initialize and open in one go.\n std::ifstream file(argv[1]);\n\n if (!file) // don't specifically check for a good state\n { // there are several bad states so check to see if the file\n // is not bad.\n throw std::exception(\"Unable to open file\");\n }\n\n // Now spend time reading the file.\n</code></pre>\n\n<p>Exceptions. The <code>std::exception</code> is the base class and has several derived types for different situations. In pre C++11 this class did not even take a string in the constructor so you could not use it like this:</p>\n\n<pre><code>std::exception(\"No parameter passed\");\n</code></pre>\n\n<p>I would choose the more generic <code>std::runtime_error</code>. You will need to include <code>&lt;stdexcept&gt;</code> to get the definition.</p>\n\n<p>OK this loop is absolutely <strong>not</strong> needed.</p>\n\n<pre><code> for (int z = 0; z &lt; 4; z++)\n</code></pre>\n\n<p>In the code you basically go:</p>\n\n<pre><code> for (int z = 0; z &lt; 4; z++) {\n if (z == 0) {taskOne();}\n if (z == 1) {taskTwo();}\n if (z == 2) {taskThree();}\n if (z == 3) {taskFour();}\n }\n</code></pre>\n\n<p>This whole construct can simply be replaced with:</p>\n\n<pre><code> taskOne();\n taskTwo();\n taskThree();\n taskFour();\n</code></pre>\n\n<p>In the next section you never check that any read operation worked. Any stream operation should be checked to make sure it worked.</p>\n\n<pre><code> iss &gt;&gt; n;\n</code></pre>\n\n<p>Did that actually read the value? Or is <code>n</code> left in its original state (thus causing you to add the last value read repeatedly). If you have a one off error then this kind of thing results in the last value being placed into the data twice (common issue).</p>\n\n<pre><code> startingOrder.reserve(n);\n for (int a = 0; a &lt; n; a++)\n {\n int d;\n iss &gt;&gt; d;\n startingOrder.push_back(d - 1);\n }\n</code></pre>\n\n<p>I would so something more like this:</p>\n\n<pre><code> startingOrder.reserve(n);\n while(iss &gt;&gt; d) {\n startingOrder.push_back(d - 1);\n }\n if (startingOrder.size() != n) {\n throw std::runtime_exception(\"Malformed input file .... some text\");\n }\n</code></pre>\n\n<p>Technically you don't even need a loop you can simply use istream iterators to initiate an array. But while learning I would use the loop form and graduate to this form once you have started understanding more of the standard library.</p>\n\n<pre><code> // How to create an array from stream iterators.\n startingOrder = std::vector&lt;int&gt;(std::istream_iterator&lt;int&gt;{iss},\n std::istream_iterator&lt;int&gt;{});\n</code></pre>\n\n<p>Don't see the point in this.</p>\n\n<pre><code> file.close();\n</code></pre>\n\n<p>I would just let the destructor do its job and close the file.</p>\n\n<p>This function header is not const correct.</p>\n\n<pre><code>long long calculateLowestCostOfWork(int const &amp;n, int const &amp;MAX_WEIGHT, int const &amp;minWeightGlobally, std::vector&lt;int&gt;&amp; weights, std::vector&lt;int&gt;&amp; startingOrder, std::vector&lt;int&gt;&amp; endingOrder)\n</code></pre>\n\n<p>You pass several parameters by reference that are non-mutable (all the input arrays).</p>\n\n<p>This is a bad habit (not using the curly braces).</p>\n\n<pre><code> for (int i = 0; i &lt; n; i++)\n permutation[endingOrder[i]] = startingOrder[i];\n</code></pre>\n\n<p>When you don't put braces only the one next statement is part of the loop. The trouble is that it is not always obvious that there are two (or more) statements and thus you could have some hard to find errors.</p>\n\n<pre><code> // Not immediately obvious example. But still not 100% easy to spot.\n // But a lot of code reviewers can still easily miss this.\n for (int i = 0; i &lt; n; i++)\n permutation[endingOrder[i]] = startingOrder[i];\n plop[i] = pile[i];\n\n // This kind of thing has happened to me\n #define UpdatePerm(permutation, endingOrder, startingOrder, plop, pile, i) \\\n permutation[endingOrder[i]] = startingOrder[i]; \\\n plop[i] = pile[i]\n\n // ... Lots of other code.\n\n for (int i = 0; i &lt; n; i++)\n UpdatePerm(permutation, endingOrder, startingOrder, plop, pile, i);\n</code></pre>\n\n<p>Moral of the story always put the braces on and you will never be wrong.</p>\n\n<pre><code> for (int i = 0; i &lt; n; i++) {\n UpdatePerm(permutation, endingOrder, startingOrder, plop, pile, i);\n }\n\n // In your case:\n for (int i = 0; i &lt; n; i++) {\n permutation[endingOrder[i]] = startingOrder[i];\n }\n</code></pre>\n\n<p>Only putting the try around one function seems strange.</p>\n\n<pre><code>try\n{\n readFromFile(argc, argv,MAX_VERTEXES, MIN_VERTEXES, n, minWeightGlobally, weights, startingOrder, endingOrder);\n}\ncatch (...)\n{\n std::cout &lt;&lt; \"Error\";\n}\n\nstd::cout &lt;&lt; calculateLowestCostOfWork(n,MAX_WEIGHT,minWeightGlobally,weights,startingOrder,endingOrder);\n</code></pre>\n\n<p>In the main I would have all the code inside the try block. So that any future errors would be caught by the try (people change code and don't always check were the code is use). But in addition to just printing error I would print the message as well. Then I would re-throw the exception so that the external operating system knows there was an error.</p>\n\n<pre><code>try\n{\n // All real code that is not simply initializing constants.\n\n readFromFile(argc, argv,MAX_VERTEXES, MIN_VERTEXES, n, minWeightGlobally, weights, startingOrder, endingOrder);\n int result = calculateLowestCostOfWork(n,MAX_WEIGHT,minWeightGlobally,weights,startingOrder,endingOrder);\n std::cout &lt;&lt; result &lt;&lt; \"\\n\";\n}\ncatch (std::exception const&amp; e) {\n std::cerr &lt;&lt; \"Error: \" &lt;&lt; e.what() &lt;&lt; \"\\n\";\n throw;\n}\ncatch (...) {\n std::cerr &lt;&lt; \"Error: Unknown?\\n\";\n throw;\n}\n</code></pre>\n\n<p>One variable per line please.</p>\n\n<pre><code>std::vector&lt;int&gt; weights, startingOrder, endingOrder;\n</code></pre>\n\n<p>This is simply horrible to read and make sure you got correct.</p>\n\n<p>Let us have meaningful names.</p>\n\n<pre><code>int n=0;\n</code></pre>\n\n<p>I did a search of the code for the variable <code>n</code> to see where it is used. Do you know how many times <code>n</code> is in the code. Use meaningful names so it becomes easy to search and see the variables. Its not used by the way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T15:44:14.090", "Id": "439430", "Score": "0", "body": "`int n` is a good name for a loop limit (in my view) - and `i` is an *excellent* name for a loop counter. A meaningful name doesn't have to be long." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T19:46:29.383", "Id": "439462", "Score": "0", "body": "@MartinBonner Well I will argue that you are wrong. And not just wrong but data provably wrong. As I mentioned above. Open up the file above in an editor and search for the variable `n`. How many characters are highlighted? From the beginning of `main()` how many times do I have to hit next to reach the declaration of n? 8 times. And its only usage is at 11 times? and its exceedingly hard to spot the usage without tabbing through to the point of usage as `n` is in both identifiers and keywords." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T21:35:21.433", "Id": "439490", "Score": "1", "body": "@MartinYork While I agree with you on `n` being less than ideal, any decent editor should be able to search on word boundaries. In Vim, this can be done with the `\\<` and `\\>` patterns or using the `*` or `#` keyword search. In GUI-based editors, there's usually a checkbox for \"match whole word only\" or something similar. The `i` loop counter is fine just because it's a standard practice, though raw loops are best avoided when possible, and iterator-based (\"foreach\") loops are preferable when raw loops are necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T00:08:25.027", "Id": "439505", "Score": "0", "body": "@Bloodgain Yes I agree there are workarounds. But you are added cognative load for the maintainer when there is no need to do this. It is not hard to add meaningful names so best practice is to make identifiers meaningful. Even loop variables can be made more useful and reduce the cognitive burden of the maintainer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T04:32:46.183", "Id": "439521", "Score": "0", "body": "I've rebuilded a code, according to your advices. Thank you for your feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T05:00:09.957", "Id": "439524", "Score": "0", "body": "@MartinYork Bloodgain has explained why your 'proof' is flawed. The OP should take from this \"coding style is a subject on which many people have strong opinions. Consider your style, and choose one you find easy to understand.\"" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T13:46:57.137", "Id": "226175", "ParentId": "226145", "Score": "4" } }, { "body": "<p>I've tried my best and updated my code according to your valuable feedback, please have a look. \nWhat i am failing to do is to check whether there is a whitespace after numbers so the input\n1 2 3 4whitespaces is not correct.</p>\n\n<pre><code> #include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;sstream&gt;\n#include &lt;stdexcept&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\nint constexpr MaxWeight = 6500, MinVertexes = 2, MaxVertexes = 1000000;\n\nstruct ObjectCollection \n{\n int amountOfObjects = 0;\n std::vector&lt;int&gt; weights;\n std::vector&lt;int&gt; startingOrder;\n std::vector&lt;int&gt; endingOrder;\n int minWeight = MaxWeight;\n};\n\nstd::vector&lt;int&gt; readOrder(std::istringstream&amp; iss, int const amountOfObjects) \n{\n std::vector&lt;int&gt; v;\n v.reserve(amountOfObjects);\n int i = 1;\n while(!iss.eof() &amp;&amp; i &lt;= amountOfObjects)\n {\n int number;\n iss &gt;&gt; number;\n if (number - 1 &gt; amountOfObjects) throw std::logic_error(\"Too high index in order\");\n v.push_back(number-1);\n i++;\n }\n if (v.size() != amountOfObjects) throw std::logic_error(\"Too few values in line\");\n return v;\n}\n\nvoid readWeightsAndSetMinWeight(std::istringstream&amp; iss, ObjectCollection&amp; objects)\n{\n objects.weights.reserve(objects.amountOfObjects);\n int i = 1;\n while (!iss.eof() &amp;&amp; i &lt;= objects.amountOfObjects)\n {\n int number;\n iss &gt;&gt; number;\n if (number&gt; MaxWeight) throw std::logic_error(\"Too high weight\");\n objects.weights.push_back(number);\n objects.minWeight = std::min(objects.minWeight, number);\n i++;\n }\n if (objects.weights.size() != objects.amountOfObjects) throw std::logic_error(\"Too few values in line\");\n}\n\n//todo version for weight\n\nObjectCollection readFromFile(std::string const&amp; filename)\n{\n ObjectCollection objects;\n std::ifstream file(filename);\n\n if (!file.is_open()) throw std::exception(\"Unable to open file\");\n\n for (int i = 0; i &lt; 4; i++)\n {\n std::string line;\n std::getline(file, line);\n if (line.empty()) throw std::logic_error(\"Invalid input\");\n std::istringstream iss(line);\n\n if (i == 0)\n {\n iss &gt;&gt; objects.amountOfObjects;\n if (objects.amountOfObjects&lt;MinVertexes || objects.amountOfObjects&gt;MaxVertexes) throw std::exception(\"Invalid amount of vertexes\");\n }\n else if (i == 1)\n {\n objects.weights.reserve(objects.amountOfObjects);\n for (int j = 0; j &lt; objects.amountOfObjects; j++)\n {\n //int number;\n //iss &gt;&gt; number;\n //objects.weights.push_back(number);\n //objects.minWeight = std::min(objects.minWeight, objects.weights[j]);\n readWeightsAndSetMinWeight(iss, objects);\n }\n }\n else if (i == 2)\n {\n objects.startingOrder = readOrder(iss,objects.amountOfObjects);\n }\n else if (i == 3)\n {\n objects.endingOrder = readOrder(iss, objects.amountOfObjects);\n }\n }\n return objects;\n}\n\nlong long calculateLowestCostOfWork(ObjectCollection const&amp; objects)\n{\n int n = objects.amountOfObjects;\n std::vector&lt;int&gt; permutation(n);\n\n //constructing permutation\n for (int i = 0; i &lt; n; i++) \n {\n permutation[objects.endingOrder[i]] = objects.startingOrder[i];\n }\n\n long long result = 0;\n std::vector&lt;bool&gt; visitedVertexes(n);\n\n for (int i = 0; i &lt; n; i++)\n {\n int numberOfElementsInCycle = 0;\n int minWeightInCycle = MaxWeight;\n long long sumOfWeightsInCycle = 0;\n if (!visitedVertexes[i])\n {\n int vertexToVisit = i;\n //decomposition for simple cycles and calculating parameters for each cycle\n while (!visitedVertexes[vertexToVisit])\n {\n visitedVertexes[vertexToVisit] = true;\n numberOfElementsInCycle++;\n vertexToVisit = permutation[vertexToVisit];\n sumOfWeightsInCycle += objects.weights[vertexToVisit];\n minWeightInCycle = std::min(minWeightInCycle, objects.weights[vertexToVisit]);\n }\n //calculating lowest cost for each cycle\n long long swappingWithMinWeightInCycle = sumOfWeightsInCycle + (static_cast&lt;long long&gt;(numberOfElementsInCycle) - 2) * static_cast&lt;long long&gt;(minWeightInCycle);\n long long swappingWithMinWeight = sumOfWeightsInCycle + minWeightInCycle + (static_cast&lt;long long&gt;(numberOfElementsInCycle) + 1) * static_cast&lt;long long&gt;(objects.minWeight);\n result += std::min(swappingWithMinWeightInCycle, swappingWithMinWeight);\n }\n }\n return result;\n}\n\nint main(int argc, char* argv[])\n{\n if (argc &lt; 2)\n {\n std::cerr &lt;&lt; \"Error: missing filename\\n\";\n return 1;\n }\n\n ObjectCollection elephants;\n try\n {\n elephants = readFromFile(argv[1]);\n std::cout &lt;&lt; calculateLowestCostOfWork(elephants);\n }\n catch (std::exception const&amp; ex) \n {\n std::cerr &lt;&lt; \"Error: \" &lt;&lt; ex.what() &lt;&lt; \"\\n\";\n return 1;\n }\n catch (...)\n {\n std::cerr &lt;&lt; \"Error unknown \\n\";\n return 1;\n }\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T13:44:56.223", "Id": "226264", "ParentId": "226145", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-14T23:26:59.533", "Id": "226145", "Score": "5", "Tags": [ "c++", "comparative-review" ], "Title": "Least cost swapping in C++" }
226145
<p>I have the following function that takes a string and returns a function pointer; currently its a long if-else block; thats continuing to grow this will make it difficult to maintain. </p> <p>The logic of this function is repeated but the return type has changed. </p> <pre><code>typedef int (*FP)(char** params, int numberOfParams); typedef int (*FP1)(int x); static FP getFunction1(char* name) { if(strcmp(name, "str1") == 0) { return fun1; } else if(strcmp(name, "str2") == 0) { return fun2; } } static FP1 getFunction2(char* name) { if(strcmp(name, "str1") == 0) { return fun3; } else if(strcmp(name, "str2") == 0) { return fun4; } } </code></pre> <p>Is there a better way that this could be refactored to remove the duplicate code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T11:42:28.847", "Id": "439401", "Score": "0", "body": "This doesn't look like code from a real project; code-review is about improving actual code within a concrete context (the context is important in determining how the code should be structured): hypothetical code and general questions are not on-topic here. Take a look at the [help centre](https://codereview.stackexchange.com/help/dont-ask) to find out how you can make the most out of this site." } ]
[ { "body": "<p>You could create a table mapping strings to functions:</p>\n\n<pre><code>typedef struct {\n char* name;\n FP func;\n} FP_mapping;\n\nFP_mapping FP_map[] = {\n { \"str1\", fun1 },\n { \"str2\", fun2 },\n { NULL, NULL }\n};\n</code></pre>\n\n<p>Then iterate over the array:</p>\n\n<pre><code>static FP getFunction1(char* name)\n{\n for (int i=0; FP_map[i].name != NULL; i++)\n {\n if strcmp(FP_map[i].name, name)\n {\n return FP_map[i].func;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T07:03:13.013", "Id": "439356", "Score": "0", "body": "… and after this transformation it's worth considering whether to sort the names so that a binary search can be used, or to use an actual map type with constant lookup time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T10:06:42.403", "Id": "439389", "Score": "0", "body": "And if different function pointer types are going to be used, a `void *` instead of `FP` might be more adequate (in POSIX, at least)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T06:03:57.267", "Id": "226153", "ParentId": "226146", "Score": "2" } } ]
{ "AcceptedAnswerId": "226153", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-14T23:30:21.270", "Id": "226146", "Score": "1", "Tags": [ "c" ], "Title": "Return Function Pointer based upon String" }
226146
<p>I have written a python script that requests information from several Sports Betting API's, processes and standardises the results into a dictionary, Matches items between dictionaries and then performs a calculation based on the results. The code works however I am facing two problems:</p> <ol> <li><p>The code is very slow taking up to an hour to execute</p></li> <li><p>When the code is executed it seems to use my CPU instead of GPU which may be a contributing factor to how slow it is</p></li> </ol> <p>Currently my code uses for loops and fuzzywuzzy to match names and bet types in different dictionaries I have standardised from several API's against a list of tuples. Once a match is found the code then executes a calculation which is returned if it is below 1. This works but is very slow.</p> <pre><code>from fuzzywuzzy import fuzz,process BETennis = {'Frances Tiafoe v Roberto Bautista Agut': {'PVP': {'PlayerA/Match/Win': 3.6, 'PlayerB/Match/Win': 1.28, 'PlayerA/Set1/Win': 2.94, 'PlayerB/Set1/Win': 1.39, 'PlayerA/FirstService/Win/Yes': 1.28, 'PlayerA/FirstService/Win/No': 3.3, 'PlayerB/FirstService/Win/Yes': 1.11, 'PlayerB/FirstService/Win/No': 5}, 'ID': {'EventID': '4806539', 'PlayerA': 'Frances Tiafoe', 'PlayerB': 'Roberto Bautista Agut', 'Agency': 'BET'}}, 'Nick Kyrgios v Karen Khachanov': {'PVP': {'PlayerA/Match/Win': 1.72, 'PlayerB/Match/Win': 2.08, 'PlayerA/Set1/Win': 1.79, 'PlayerB/Set1/Win': 1.96, 'PlayerA/FirstService/Win/Yes': 1.05, 'PlayerA/FirstService/Win/No': 8, 'PlayerB/FirstService/Win/Yes': 1.06, 'PlayerB/FirstService/Win/No': 7.5}, 'ID': {'EventID': '4804932', 'PlayerA': 'Nick Kyrgios', 'PlayerB': 'Karen Khachanov', 'Agency': 'BET'}}} TBTennis = {'Frances Tiafoe v Roberto Bautista Agut': {'PVP': {'PlayerA/Match/Win': 9, 'PlayerB/Match/Win': 1.99, 'PlayerA/Set1/Win': 2.94, 'PlayerB/Set1/Win': 1.42, 'PlayerA/FirstService/Win/Yes': 1.35, 'PlayerA/FirstService/Win/No': 3.67, 'PlayerB/FirstService/Win/Yes': 1.11, 'PlayerB/FirstService/Win/No': 5}, 'ID': {'EventID': '4806539', 'PlayerA': 'Frances Tiafoe', 'PlayerB': 'Roberto Bautista Agut', 'Agency': 'TB'}}, 'Nick Kyrgios v Karen Khachanov': {'PVP': {'PlayerA/Match/Win': 1.78, 'PlayerB/Match/Win': 2.98, 'PlayerA/Set1/Win': 1.99, 'PlayerB/Set1/Win': 1.96, 'PlayerA/FirstService/Win/Yes': 1.15, 'PlayerA/FirstService/Win/No': 8.1, 'PlayerB/FirstService/Win/Yes': 1.09, 'PlayerB/FirstService/Win/No': 7.5}, 'ID': {'EventID': '4804932', 'PlayerA': 'Nick Kyrgios', 'PlayerB': 'Karen Khachanov', 'Agency': 'TB'}}} PVPtuples = [(('PlayerA/Match/Win'), ('PlayerB/Match/Win')), (('PlayerA/Set1/Win'), ('PlayerB/Set1/Win')), (('PlayerA/Set2/Win'), ('PlayerB/Set2/Win')), (('PlayerA/Aset/Win/Yes'), ('PlayerA/Aset/Win/No'))] ###BETennis/TBTennis### for i in BETennis: for e in BETennis[i]['PVP']: for p in TBTennis: for m in TBTennis[p]['PVP']: for y in PVPtuples: try: if fuzz.token_sort_ratio(BETennis[i]['ID']['PlayerA'], TBTennis[p]['ID']['PlayerA']) &gt; 80 and fuzz.token_sort_ratio(BETennis[i]['ID']['PlayerB'], TBTennis[p]['ID']['PlayerB']) &gt; 80: if e == m and y[0] == e: c = 1/float(TBTennis[p]['PVP'][y[1]]) + 1/float(BETennis[i]['PVP'][y[0]]) if c &lt; 1: print(TBTennis[p]['ID']['Agency'] + '/' + TBTennis[p]['ID']['PlayerB'] + '/' + y[1] + ' ' + BETennis[i]['ID']['Agency'] + '/' + BETennis[i]['ID']['PlayerA'] + '/' + y[0] + ' ' + str(c)) except: continue for i in BETennis: for e in BETennis[i]['PVP']: for p in TBTennis: for m in TBTennis[p]['PVP']: for y in PVPtuples: try: if fuzz.token_sort_ratio(BETennis[i]['ID']['PlayerA'], TBTennis[p]['ID']['PlayerA']) &gt; 80 and fuzz.token_sort_ratio(BETennis[i]['ID']['PlayerB'], TBTennis[p]['ID']['PlayerB']) &gt; 80: if e == m and y[0] == e: c = 1/float(TBTennis[p]['PVP'][y[0]]) + 1/float(BETennis[i]['PVP'][y[1]]) #print(TBTennis[p]['ID']['Agency'] + y[0] + '/' + BETennis[i]['ID']['Agency'] + y[1] + c) if c &lt; 1: print(TBTennis[p]['ID']['Agency'] + '/' + TBTennis[p]['ID']['PlayerA'] + '/' + y[0] + ' ' + BETennis[i]['ID']['Agency'] + '/' + BETennis[i]['ID']['PlayerB'] + '/' + y[1] + ' ' + str(c)) except: continue </code></pre> <p>The code works more or less as expected however as I am new to python and programming in general I think I may be doing this in a very inefficient way. One remedy I am currently exploring is using CUDA to try run this using my NVIDIA GPU instead of my CPU as it currently does. Any and all suggestions would be greatly appreciated. One last thing to note is the dictionaries in my code are significantly longer and more extensive than the ones used in the example above.</p>
[]
[ { "body": "<p>I'm not the Python expert you might be expecting to perform some magic on your code and make it run in fractions of a second and there are lots of much more experienced guys than myself on the website however here are some general things you should consider before asking for advice/review/whatever:</p>\n\n<ul>\n<li>Nesting levels: I suggest you separate the nested dictionaries each\nhaving a unique name and a unique purpose.</li>\n<li>If you expect anyone to try to work/suggest improvements on the code, I suggest you make it more readable for human beings: a line shouldn't exceed 120 characters, variable names should be descriptive (for i for e for p for m for n) what exactly i, e, m, n, whatever_the_name_is are meant to do</li>\n<li>The try and except are meant to catch errors, not a decoration for the code and you're not excepting anything btw, you should specify the exception expected to occur and what you actually did is try block_of_code ... except nothing_indicated ... so I guess it's pointless.</li>\n<li>I'm surprised this code only takes an hour to execute with 9 nested fors and ifs, the moment you start nesting the 2nd for, you might start considering another approach for solving whatever the problem at hand or the running time is going to grow exponentially.</li>\n<li>When you fix some of many things that I did and I did not mention, you might post the modified working version of the code and ask for some advice.</li>\n<li>from fuzzywuzzy import fuzz,process ... No one is expected to decode what these things do, if you're not going to include what they contain in your code at least give us the honor of writing some comments that begin with # that indicate what these things do.</li>\n<li>You must include a description for what your code is exactly meant to do not some vague remarks \"Once a match is found the code then executes a calculation which is returned if it is below 1.\" what kind of calculation that is being executed?</li>\n<li>Separate your dictionaries including the nested ones, make your code more readable, write comments, give a clear description for what the code is expected to do then repost this code because most probably no one will be able to decode what this is meant for.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T08:50:03.410", "Id": "439374", "Score": "0", "body": "Hi thanks for the reply. I’ll try addresses your points. First, I tried minimise the code length and explanation to key important points as this website suggests when posting a question, apologies if it confused you. As such ill start with a more in-depth explanation. My code is fairly simple it makes requests to several Sports Book APIs for betting data. This API data is stored in what is essentially nested dictionaries. Each API uniquely stores and names bets for example one API might name the bet for the Match winner as PlayerAHeadtoHead whereas another might call it PlayerAMatchWin." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T08:50:16.577", "Id": "439375", "Score": "0", "body": "As such I created new dictionaries from each API in a standardised format, ie PlayerA/Match/Win in dictionary1 is the same as PlayerA/Match/Win in dictionary2 except obviously with different odds from respective websites." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T08:50:29.107", "Id": "439376", "Score": "0", "body": "If the same bet type (such as match winner) is contained in both dictionaries then a simple arbitrage calculation is done which is the sum of 1 divided by the odds of a bet in both directions. For example: 1/Odds for player A to win + 1/Odds for player B to win. To do this my code verifies that the matches being compared are the same by comparing PlayerA and PlayerB names in dictionary 1 and dictionary 2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T08:50:48.203", "Id": "439377", "Score": "0", "body": "As mentioned earlier each API has slightly varied names, this extends to Match/Player names so for example Rafael Nadal may be called by his full name in one API as Rafael Nadal but may be called by an abbreviated version in another like R.Nadal. To overcome this, I used fuzzy wuzzy to compare and accept matches above 80%. If this is true matching bets are found using == as I have standardised bet names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T08:51:02.077", "Id": "439378", "Score": "0", "body": "To find the opposite type of bet in the other dictionary I created a list of tuples that contain each standardised bet name and its opposite ie ((PlayerA/Win), (PlayerB/Win)). The matched bets are compared to this list of tuples to find the opposite bet in each dictionary and perform the arbitrage calculation. This is what the I, e, m and n are referring." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T08:51:15.937", "Id": "439379", "Score": "0", "body": "As to the try and except ‘decorations’ I assumed that in the event of any exception the code would simply skip that loop and continue to the next one, which seems to work as even in the absence of explicitly stating expected exceptions the code seems to skip exceptions such as KeyErrors etc. I hope this makes things clearer, thanks for your suggestions ill try improve the question/code." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T02:59:19.130", "Id": "226151", "ParentId": "226150", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T01:48:03.740", "Id": "226150", "Score": "2", "Tags": [ "python", "performance", "beginner", "python-3.x", "hash-map" ], "Title": "Comparing web-scraped data from several sports betting APIs" }
226150
<p>Inspired by a Numberphile <a href="https://www.youtube.com/watch?v=M7kEpw1tn50" rel="noreferrer">video</a> I made a little program that shows the principles of RSA encryption and decryption. To calculate the keys I used the explanation in this link: <a href="http://jcla1.com/blog/rsa-public-private-key-encryption-explained" rel="noreferrer">rsa public private key encryption explained</a>. Fascinating what you can do in a few lines of code and how Python can handle to powering of large numbers. </p> <p>One observation is that with large prime numbers encryption goes relatively fast starting with ascii code numbers that are relatively small less than 200 or so, but the decryption goes much slower as the encrypted numbers are magnitudes larger. How is this solved in practice? and how is this all working with really large primes?</p> <p>Comments, suggestions welcome. </p> <pre><code>''' RSA encryption inspired on: https://www.youtube.com/watch?v=M7kEpw1tn50 and http://jcla1.com/blog/rsa-public-private-key-encryption-explained some conditions: - prime numbers must be &gt; 1 and not equal - prime factor must sufficiently large to accommodate the ascii numbers, let's say &gt; 150 - so for example (2, 191) will do as well as (11, 17) ''' class RSA(): ''' methods for calculating keys, encrypt and decrypt ascii messages ''' @staticmethod def gcd(a, b): while b: a, b = b, a % b return a @classmethod def encrypt(cls, message): message_letters = [ord(letter) for letter in message] message_encrypted = ''.join([chr(letter**cls.public_key % cls.prime_factor) for letter in message_letters]) return message_encrypted @classmethod def decrypt(cls, message_encrypted): message_encrypted_letters = [ord(letter) for letter in message_encrypted] message = ''.join([chr(letter**cls.private_key % cls.prime_factor) for letter in message_encrypted_letters]) return message @classmethod def calc_keys(cls, prime_1, prime_2): cls.prime_factor = prime_1 * prime_2 totient = (prime_1 - 1) * (prime_2 - 1) # calculate the possible public keys where gcd(public_key, totient) == 1, then select the 5th one (this is abritary, any # of the public_keys could have been selected # (Note above link has an error that the gcd of public_key and totient must be 1, not public_key # and the prime_factor as suggested in the article) public_keys = [] for i in range(totient): if cls.gcd(i, totient) == 1: public_keys.append(i) cls.public_key = public_keys[4] # calculate the private key based on public key and totient when (public_key * private_key - 1) % totient == 0 cls.private_key = 0 x = -1 while x != 0: cls.private_key += 1 x = (cls.public_key * cls.private_key - 1) % totient return (cls.prime_factor, cls.public_key, cls.private_key) def main(): rsa = RSA() print(rsa.calc_keys(61, 53)) message = 'hello this is my encrypted message' encrypted_message = rsa.encrypt(message) decrypted_message = rsa.decrypt(encrypted_message) if message == decrypted_message: print('Hurray!!') print(f'message: {message}\nencrypted message: {encrypted_message}' f'\ndecrypted message: {decrypted_message}') else: print('Ough, someting wrong here ... !') if __name__=="__main__": main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T18:00:37.247", "Id": "439448", "Score": "0", "body": "Normally, you never encrypt the whole message with RSA. Usually you encrypt a randomely generated symmetric key (ex. AES), encryot the message with it and concatenate them together." } ]
[ { "body": "<p>1) Real implementation of RSA use the <em>Chinese Remainder Theorem</em>, which greatly <a href=\"https://crypto.stackexchange.com/a/2580/38781\">improves the performance</a>.</p>\n\n<p>2) The big performance difference between encryption and decryption is a normal thing for RSA. It comes from the fact, that the performance of the modular exponentiation used depends on the number of <em>1</em> bits in the exponent. If you either chose the public exponent to be very small (like you are doing in your code, which is insecure btw) or large but with a lot of zeroes in its binary representation (usually e=655537=100...001 is used) public key operations (=encryption) will be fast. The private exponent can not be controlled and will have ~1/2 of its bit set to one, making the decryption a lot slower.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-30T10:31:45.200", "Id": "227167", "ParentId": "226156", "Score": "3" } }, { "body": "<p><strong>Programming:</strong></p>\n\n<ol>\n<li>You can see that OpenSSL uses Chinese Remainder Theorem (CRT) for RSA modular exponentiation. CRT gives you approximately 4x speed up.</li>\n<li>There is nothing wrong with a small public key exponent <code>e</code> as long as a proper padding applied. Except 2, when public exponent is 2, you will have <a href=\"https://en.wikipedia.org/wiki/Rabin_cryptosystem\" rel=\"nofollow noreferrer\">Rabin-Cryptosystem</a>. See security section;</li>\n<li>The commons public keys are {3, 5, 17, 257 or 65537}. This helps to reduce the number of multiplications. This is considered helpful if you consider client's low power devices.</li>\n<li>The modular exponentiation should be performed modular version of repeated squaring method. Or you can use <a href=\"https://docs.python.org/2/library/functions.html#pow\" rel=\"nofollow noreferrer\">pow</a> function of python which already has fast modular multiplication. In your case, firstly the power is calculated this means that the number becomes bigger and bigger and therefore slow.</li>\n</ol>\n\n<p><strong>Security:</strong></p>\n\n<ol>\n<li>RSA is a trapdoor function and should never be used without a proper padding.</li>\n<li>For Encryption you can use <a href=\"https://en.wikipedia.org/wiki/PKCS_1\" rel=\"nofollow noreferrer\">PKCS#1.5 padding</a> scheme or better use <a href=\"https://en.wikipedia.org/wiki/Optimal_asymmetric_encryption_padding\" rel=\"nofollow noreferrer\">Optimal Asymmetric Encryption Scheme</a> (OAEP).</li>\n<li>For signatures you can use <a href=\"https://en.wikipedia.org/wiki/Probabilistic_signature_scheme\" rel=\"nofollow noreferrer\">Probabilistic Signature Scheme</a> (RSA-PSS).</li>\n<li>Normally RSA is not used for encryption. It is used for signatures.</li>\n<li>Usually, we prefer hybrid cryptosystem in that public key algorithms are used for key exchange/establishment then a symmetric algorithm is used.</li>\n<li>There is once useful case is where RSA encryption is used, <a href=\"https://en.wikipedia.org/wiki/Key_encapsulation\" rel=\"nofollow noreferrer\">RSA-KEM</a> where it is used to establish key for symmetric algorithms</li>\n<li>Never use small private exponent, this is insecure.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-26T13:36:30.693", "Id": "229702", "ParentId": "226156", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T06:29:47.560", "Id": "226156", "Score": "7", "Tags": [ "python", "primes", "cryptography" ], "Title": "A simple implementation of the principle of RSA encryption" }
226156
<p>I have this code that is supposed to compare two Excel sheets. The code is working fine for small comparisons. I did a test run with 7 rows and 2 columns.</p> <p>The code itself works as follows: it compares the two sheets and copies the differences into a new workbook.</p> <p>However, the code should be applied to files that have around 16 columns and a lot of rows (around 206700). It doesn't seem to scale very well to these larger sheets - the process is shown “Not Responding”, for more than ten minutes when I gave up.</p> <p>This is how my excel file columns looks likem, keeping in mind that most of them contain text and only few times numbers are used. <a href="https://i.stack.imgur.com/oMaVe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oMaVe.png" alt="enter image description here"></a></p> <p>I'd like to improve the performance with these larger files; any other suggestions for improvement are also welcome.</p> <pre><code>Sub Compare2WorkSheets(ws1 As Worksheet, ws2 As Worksheet) Dim ws1row As Long, ws2row As Long, ws1col As Integer, ws2col As Integer Dim maxrow As Long, maxcol As Integer, colval1 As String, colval2 As String Dim report As Workbook, difference As Long Dim row As Long, col As Integer Set report = Workbooks.Add With ws1.UsedRange ws1row = .Rows.Count ws1col = .Columns.Count End With With ws2.UsedRange ws2row = .Rows.Count ws2col = .Columns.Count End With maxrow = ws1row maxcol = ws1col If maxrow &lt; ws2row Then maxrow = ws2row If maxcol &lt; ws2col Then maxcol = ws2col difference = 0 For col = 1 To maxcol For row = 1 To maxrow colval1 = "" colval2 = "" colval1 = ws1.Cells(row, col).Formula colval2 = ws2.Cells(row, col).Formula If colval1 &lt;&gt; colval2 Then difference = difference + 1 Cells(row, col).Formula = colval1 &amp; "&lt;&gt; " &amp; colval2 Cells(row, col).Interior.Color = 255 Cells(row, col).Font.ColorIndex = 2 Cells(row, col).Font.Bold = True End If Next row Next col Columns("A:B").ColumnWidth = 25 report.Saved = True If difference = 0 Then report.Close False End If Set report = Nothing MsgBox difference &amp; " cells contain different data! ", vbInformation, _ "Comparing Two Worksheets" End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T09:49:45.183", "Id": "439387", "Score": "0", "body": "\"16 columns and a lot of rows (around 206700)\" Have you tried scaling up more slowly? What happens with 3 columns and 400 rows? 6 columns and 800 rows? Now all you can tell us you don't have the patience to see whether it still works after 10 minutes, which doesn't tell us much about the current inefficiency." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T09:53:29.517", "Id": "439388", "Score": "2", "body": "Can you tell us more about how this code is used (executed in 1 of the spreadsheets, or in a 3rd), what kind of data (length) we're talking about and how the cells are formatted (are they text, numbers, currency, date)? This could all be relevant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T11:15:32.550", "Id": "439395", "Score": "0", "body": "@Mast I actually have waited almost 1 hour and the file was stil saying \"Not responding\" . I just tried it with 10k rows and all the columns . It took more than a 1min. If you look at the question I also have added a picture oh how my excel file approx looks like" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T13:53:47.817", "Id": "439409", "Score": "0", "body": "It looks like you're comparing the formulas in each of the cells and not the values of the cells. Is this correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T13:56:26.237", "Id": "439410", "Score": "4", "body": "@Close-Voters: Please read the [tag:vba] tag wiki. Excel \"freezing\" and/or \"(not responding)\" **is not broken code**." } ]
[ { "body": "<p>There are some issues with your code:</p>\n\n<p>1) Try to avoid unqualified references, this means always specify the worksheet, when referencing a cell.</p>\n\n<p>2) Try to avoid formatting a lot of single cells, rather format them all at once at the end. Formatting slows down Excel a lot!</p>\n\n<p>3) When handeling a great deal of Ranges, <code>Integer</code> can be insufficient, use <code>Long</code> instead.</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Sub Compare2WorkSheets(ws1 As Worksheet, ws2 As Worksheet)\n\n Dim ws1row As Long, ws2row As Long, ws1col As Long, ws2col As Long\n Dim maxrow As Long, maxcol As Integer, colval1 As String, colval2 As String\n Dim report As Workbook, difference As Long\n Dim row As Long, col As Long\n Dim unionRng as Range\n\n Set report = Workbooks.Add\n\n With ws1.UsedRange\n ws1row = .Rows.Count\n ws1col = .Columns.Count\n End With\n\n With ws2.UsedRange\n ws2row = .Rows.Count\n ws2col = .Columns.Count\n End With\n\n maxrow = ws1row\n maxcol = ws1col\n If maxrow &lt; ws2row Then maxrow = ws2row\n If maxcol &lt; ws2col Then maxcol = ws2col\n\n difference = 0\n\n With report.Sheets(1)\n For col = 1 To maxcol\n For row = 1 To maxrow\n colval1 = \"\"\n colval2 = \"\"\n colval1 = ws1.Cells(row, col).Formula\n colval2 = ws2.Cells(row, col).Formula\n\n If colval1 &lt;&gt; colval2 Then\n difference = difference + 1\n .Cells(row, col).Value = colval1 &amp; \"&lt;&gt; \" &amp; colval2 'I guess you want to show, that the formulas used are not equal.\n If unionRng is Nothing Then\n Set unionRng = .Cells(row, col)\n Else\n Set unionRng = Application.Union(unionRng, .Cells(row, col))\n End If\n End If\n Next row\n Next col\n\n .Columns(\"A:B\").ColumnWidth = 25\n End With\n\n unionRng.Interior.Color = 255\n unionRng.Font.ColorIndex = 2\n unionRng.Font.Bold = True\n report.SaveAs Filename:=\"report.xlsx\"\n\n If difference = 0 Then\n report.Close False\n End If\n Set report = Nothing\n MsgBox difference &amp; \" cells contain different data! \", vbInformation, _\n \"Comparing Two Worksheets\"\nEnd Sub\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T14:44:39.167", "Id": "439417", "Score": "0", "body": "I'm getting error *Invalid procedure call or invalid argument* at __Set unionRng = Application.Union(unionRng, .Cells(row, col))__" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T14:49:27.970", "Id": "439419", "Score": "0", "body": "See the edit, forgot to check for the case, that `unionRng` is set for the first time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T15:36:49.193", "Id": "439428", "Score": "0", "body": "It's been 40 mins since the code is running, as it for no it's showing __Not Responding__ but I guess files are still being compared. The problem is, this is taking way to long and an end point doesn't look near." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T18:16:28.030", "Id": "439451", "Score": "0", "body": "I have serious apprehensions using union range method with large non contiguous area count at least in excel 2007. May refer my [post](https://codereview.stackexchange.com/questions/224874/brute-force-looping-formatting-or-create-union-range-format-which-is-effici/224937#224937) and may provide some more information.." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T13:29:06.163", "Id": "226173", "ParentId": "226160", "Score": "2" } }, { "body": "<p>May try the modified code using Arrays to Compare. Tested with 250000 rows X 26 columns of random data and every 5th cells have value difference (Total 130000 differences). It takes around 18 secs to compare and another 22 secs to completes report generation with total 40 seconds only.</p>\n\n<pre><code>Sub Compare2WorkSheets(ws1 As Worksheet, ws2 As Worksheet)\n Dim ws1row As Long, ws2row As Long, ws1col As Integer, ws2col As Integer\n Dim maxrow As Long, maxcol As Integer, colval1 As String, colval2 As String\n Dim Report As Workbook, difference As Long\n Dim row As Long, col As Integer\n Dim Arr1 As Variant, Arr2 As Variant, Arr3 As Variant, Rng As Range\n Dim tm As Double\n tm = Timer\n\n 'Application.ScreenUpdating = False\n 'Application.Calculation = xlCalculationManual\n 'Application.EnableEvents = False\n\n\n With ws1.UsedRange\n ws1row = .Rows.Count\n ws1col = .Columns.Count\n End With\n\n With ws2.UsedRange\n ws2row = .Rows.Count\n ws2col = .Columns.Count\n End With\n\n maxrow = ws1row\n maxcol = ws1col\n If maxrow &lt; ws2row Then maxrow = ws2row\n If maxcol &lt; ws2col Then maxcol = ws2col\n\n Debug.Print maxrow, maxcol\n Arr1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(maxrow, maxcol)).Formula\n Arr2 = ws2.Range(ws2.Cells(1, 1), ws2.Cells(maxrow, maxcol)).Formula\n ReDim Arr3(1 To UBound(Arr1, 1), 1 To UBound(Arr1, 2))\n\n difference = 0\n\n For col = 1 To maxcol\n For row = 1 To maxrow\n If Arr1(row, col) &lt;&gt; Arr2(row, col) Then\n difference = difference + 1\n Arr3(row, col) = Arr1(row, col) &amp; \"&lt;&gt; \" &amp; Arr2(row, col)\n Else\n Arr3(row, col) = \"\"\n End If\n Next row\n Next col\n\n Debug.Print \" Calc secs \" &amp; Timer - tm\n If difference &gt; 0 Then\n Set Report = Workbooks.Add\n\n With Report.ActiveSheet\n .Range(\"A1\").Resize(UBound(Arr3, 1), UBound(Arr3, 2)).Value = Arr3\n .Columns(\"A:B\").ColumnWidth = 25\n Set Rng = .Range(Report.ActiveSheet.Cells(1, 1), Report.ActiveSheet.Cells(UBound(Arr3, 1), UBound(Arr3, 2)))\n End With\n\n With Rng\n .FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:=\"=\"\"\"\"\" '\"\"\"\"\"\"\"\"\n .FormatConditions(Selection.FormatConditions.Count).SetFirstPriority\n With .FormatConditions(1)\n .Interior.Color = 255\n .Font.Bold = True\n .Font.ColorIndex = 2\n End With\n End With\n\n Debug.Print \"Report Generated secs \" &amp; Timer - tm\n End If\n 'Set Report = Nothing\n 'Application.ScreenUpdating = True\n 'Application.Calculation = xlCalculationAutomatic\n 'Application.EnableEvents = True\n\n MsgBox difference &amp; \" cells contain different data! \", vbInformation, \"Comparing Two Worksheets\"\nEnd Sub\n</code></pre>\n\n<p>Since I personally don't prefer to keep calculations, event processing and screen updating off (in normal cases) i haven't used that standard lines. However you may use these standard techniques, depending on the working file condition.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T06:50:55.303", "Id": "439535", "Score": "0", "body": "thank a lot , works so smooth. I have some small features I want to add. I might need some help with that. Should I ask here or just edit my question and add those parts there ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T07:14:55.440", "Id": "439545", "Score": "0", "body": "in case the row is identical, I want it to be copied on the report sheet (without any change of color of font). I tried iimplementing it on the code however, even the rows that are the same are canging color and getting the background color" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T15:57:48.350", "Id": "439635", "Score": "0", "body": "It is not clear, do you want to copy & list values of only identical rows in the report sheet and difference is not to be calculated?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T16:06:20.273", "Id": "439637", "Score": "0", "body": "@ Ahmed AU Is it ok if I post another question about that because since reviewing the files some I have to add something and the logic behind it is unclear and I'm not managing to find a way. I would link you to the question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T16:09:31.767", "Id": "439638", "Score": "0", "body": "if it is not about efficiency and performance may post it it on SO. If this question solves your efficiency problem may pl accept the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T20:10:23.737", "Id": "439945", "Score": "0", "body": "please have a look at my new question. It is in regard to your code from here [https://codereview.stackexchange.com/questions/226346/compare-two-excel-sheets-by-cell-content]" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T18:04:50.970", "Id": "226197", "ParentId": "226160", "Score": "2" } }, { "body": "<p>My answer makes the assumption that you mean to compare the <strong>values</strong> of the data and not the <strong>formulas</strong>, though much of the other comments here remain valid for your code.</p>\n\n<ol>\n<li><a href=\"https://www.excel-easy.com/vba/examples/byref-byval.html\" rel=\"nofollow noreferrer\">Identify your function parameters as <code>ByRef</code> or <code>ByVal</code></a>. As you may guess, passing a variable \"by reference\" generally allows you to reference the variable as held by the caller and make modifications to its value (there are some exceptions, but this is the concept). Passing a variable \"by value\" effectively copies the value of the variable to a new variable in your routine. When passing objects, such as <code>Worksheet</code>, to a function, I nearly always pass these objects <code>ByRef</code> so I'm thinking there is some deep copy action happening.</li>\n<li>It's generally recommended to declare your variables as close to its first use as possible. This will save you (and anyone else reviewing your code) from having to scroll up/down to determine variable types and definitions.</li>\n</ol>\n\n<p>So to declare references to the two source worksheets would look like this:</p>\n\n<pre><code>Dim area1 As Range\nDim area2 As Range\nSet area1 = ws1.UsedRange\nSet area2 = ws2.UsedRange\n</code></pre>\n\n<ol start=\"3\">\n<li>You can simplify how you determine the maximum number of rows and columns using two statements with the <code>IIf</code>.</li>\n</ol>\n\n<p>Notice how I'm overwriting the initial <code>Set</code> of each area variable, possibly expanding it to cover the largest possible range.</p>\n\n<pre><code>'--- calculate the max-sized range for the data and expand\n' the ranges as needed\nDim maxRows As Long\nDim maxCols As Long\nmaxRows = IIf(area1.Rows.Count &gt; area2.Rows.Count, _\n area1.Rows.Count, area2.Rows.Count)\nmaxCols = IIf(area1.Columns.Count &gt; area2.Columns.Count, _\n area1.Columns.Count, area2.Columns.Count)\nSet area1 = area1.Resize(maxRows, maxCols)\nSet area2 = area2.Resize(maxRows, maxCols)\n</code></pre>\n\n<ol start=\"4\">\n<li>Here's where the real speed improvement kicks in - <a href=\"https://excelmacromastery.com/excel-vba-array/\" rel=\"nofollow noreferrer\">memory-based arrays (see #19 and #20)</a>. When you're working with a <code>Range</code> object, Excel incurs a lot of overhead to manage all the aspects of that range object. This is expensive in execution time, especially if all you want is the value of each cell in the range. It's a quick step to copy all the values into an array.</li>\n</ol>\n\n<p>Note that each array is declared as a <code>Variant</code> without array dimensions. The assignment of the range <code>.Value</code> will cast the variant into an array:</p>\n\n<pre><code>'--- create memory-based arrays for the data in the ranges\nDim data1 As Variant\nDim data2 As Variant\ndata1 = area1.value\ndata2 = area2.value\n</code></pre>\n\n<ol start=\"5\">\n<li>In keeping with the idea of speed, I'm creating a <code>Collection</code> of items that captures all of the differences/discrepancies discovered between the two worksheet areas. Because the <code>Collection</code> is also a memory-based object, it will also be very fast.</li>\n</ol>\n\n<p>Each entry in the <code>Collection</code> is a comma separated value string, which we'll pull apart later on.</p>\n\n<pre><code>'--- we'll build up the report as a series of discrepancy\n' entries in a Collection for now\nDim report As Collection\nSet report = New Collection\n\nDim r As Long\nDim c As Long\nFor r = 1 To maxRows\n For c = 1 To maxCols\n If data1(r, c) &lt;&gt; data2(r, c) Then\n '--- add a discrepancy entry to log the difference\n ' as a comma separated string:\n ' \"row,column,value1 &lt;&gt; value2\"\n report.Add r &amp; \",\" &amp; c &amp; \",\" &amp; data1(r, c) &amp; \" &lt;&gt; \" &amp; data2(r, c)\n End If\n Next c\nNext r\n</code></pre>\n\n<ol start=\"6\">\n<li>The example here shows two different ways to present your results, depending on your requirements. The first simply reports the results as a virtual list (array) that is copied directly to a worksheet. (I didn't create a separate workbook, for simplicity of my example.) </li>\n</ol>\n\n<p>This list does not mimic the dimensions of the data areas at all.</p>\n\n<pre><code>'--- results as a simple list\nDim reportData As Variant\nReDim reportData(1 To report.Count + 1, 1 To 3)\nreportData(1, 1) = \"Row\"\nreportData(1, 2) = \"Column\"\nreportData(1, 3) = \"Difference\"\nFor r = 2 To report.Count + 1\n Dim parts() As String\n parts = Split(report.Item(r - 1), \",\")\n reportData(r, 1) = parts(0)\n reportData(r, 2) = parts(1)\n reportData(r, 3) = parts(2)\nNext r\nSet finalReport = reportWS.Range(\"A1\").Resize(report.Count + 1, 3)\nfinalReport.value = reportData\n</code></pre>\n\n<p>An alternative solution is to report the discrepancies in a worksheet range that is dimensionally similar to your source worksheets. Your original post is trying to applying shading to cells with differences. </p>\n\n<p>The example here works very fast for two reasons: 1) because of how we've collected the discrepancies earlier, there's no need to loop over every single cell in the range. We have the row and column of each discrepancy, so we can directly (and quickly) just set the highlight colors and be finished, and 2) by disabling/enabling <code>Application.ScreenUpdating</code> we prevent Excel from interacting with the display, and that gains more speed.</p>\n\n<pre><code>'--- results as a data range with highlighted cells\nApplication.ScreenUpdating = False\nSet reportWS = Sheet4\nSet finalReport = reportWS.Range(\"A1\").Resize(maxRows, maxCols)\nDim discrepancy As Variant\nFor Each discrepancy In report\n 'Dim parts() As String\n parts = Split(discrepancy, \",\")\n With finalReport.Cells(CLng(parts(0)), CLng(parts(1)))\n .value = parts(2)\n .Interior.Color = 255\n .Font.ColorIndex = 2\n .Font.Bold = True\n End With\nNext discrepancy\nApplication.ScreenUpdating = True\n</code></pre>\n\n<p>Here is the full module you can use for testing:</p>\n\n<pre><code>Option Explicit\n\nSub test()\n CompareData Sheet1, Sheet2\nEnd Sub\n\nSub CompareData(ByRef ws1 As Worksheet, ByRef ws2 As Worksheet)\n Dim area1 As Range\n Dim area2 As Range\n Set area1 = ws1.UsedRange\n Set area2 = ws2.UsedRange\n\n '--- calculate the max-sized range for the data and expand\n ' the ranges as needed\n Dim maxRows As Long\n Dim maxCols As Long\n maxRows = IIf(area1.Rows.Count &gt; area2.Rows.Count, _\n area1.Rows.Count, area2.Rows.Count)\n maxCols = IIf(area1.Columns.Count &gt; area2.Columns.Count, _\n area1.Columns.Count, area2.Columns.Count)\n Set area1 = area1.Resize(maxRows, maxCols)\n Set area2 = area2.Resize(maxRows, maxCols)\n\n '--- create memory-based arrays for the data in the ranges\n Dim data1 As Variant\n Dim data2 As Variant\n data1 = area1.value\n data2 = area2.value\n\n '--- we'll build up the report as a series of discrepancy\n ' entries in a Collection for now\n Dim report As Collection\n Set report = New Collection\n\n Dim r As Long\n Dim c As Long\n For r = 1 To maxRows\n For c = 1 To maxCols\n If data1(r, c) &lt;&gt; data2(r, c) Then\n '--- add a discrepancy entry to log the difference\n ' as a comma separated string:\n ' \"row,column,value1 &lt;&gt; value2\"\n report.Add r &amp; \",\" &amp; c &amp; \",\" &amp; data1(r, c) &amp; \" &lt;&gt; \" &amp; data2(r, c)\n End If\n Next c\n Next r\n\n Dim reportWB As Workbook\n Dim reportWS As Worksheet\n Dim finalReport As Range\n 'Set reportWB = Workbooks.Add\n 'Set reportWS = reportWB.Sheets(1)\n Set reportWS = Sheet3\n\n '--- results as a simple list\n Dim reportData As Variant\n ReDim reportData(1 To report.Count + 1, 1 To 3)\n reportData(1, 1) = \"Row\"\n reportData(1, 2) = \"Column\"\n reportData(1, 3) = \"Difference\"\n For r = 2 To report.Count + 1\n Dim parts() As String\n parts = Split(report.Item(r - 1), \",\")\n reportData(r, 1) = parts(0)\n reportData(r, 2) = parts(1)\n reportData(r, 3) = parts(2)\n Next r\n Set finalReport = reportWS.Range(\"A1\").Resize(report.Count + 1, 3)\n finalReport.value = reportData\n\n '--- results as a data range with highlighted cells\n Application.ScreenUpdating = False\n Set reportWS = Sheet4\n Set finalReport = reportWS.Range(\"A1\").Resize(maxRows, maxCols)\n Dim discrepancy As Variant\n For Each discrepancy In report\n 'Dim parts() As String\n parts = Split(discrepancy, \",\")\n With finalReport.Cells(CLng(parts(0)), CLng(parts(1)))\n .value = parts(2)\n .Interior.Color = 255\n .Font.ColorIndex = 2\n .Font.Bold = True\n End With\n Next discrepancy\n Application.ScreenUpdating = True\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T11:11:24.017", "Id": "439876", "Score": "0", "body": "thank you a lot for your detailed answer. I needed to add some new features to the code and unfortunately that is above my vba knowledge. can you please have a look at my new post ? [https://codereview.stackexchange.com/questions/226346/compare-two-excel-sheets-by-cell-content]" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T18:48:37.637", "Id": "226200", "ParentId": "226160", "Score": "1" } }, { "body": "<p>My answer is very similar to Ahmed AU with a few exceptions.<br>\n- I didn't bother adding the Conditional formatting because everything on the new worksheet represents changes. \n- The other main difference is that I match the Ranges using the Range addresses. These will automatically adjust for differences in column and rows count and starting cell.</p>\n\n<h2>Refactored Code</h2>\n\n<pre><code>Sub Compare2WorkSheets(ByRef Worksheet1 As Worksheet, ByRef Worksheet2 As Worksheet)\n Dim t As Double: t = Timer\n Dim Range1 As Range, Range2 As Range\n\n SetRanges Worksheet1, Worksheet2, Range1, Range2\n\n Dim Values1, Values2, Results\n Dim r As Long, c As Long, Count As Long\n Values1 = Range1.Value\n Values2 = Range2.Value\n ReDim Results(1 To UBound(Values1), 1 To UBound(Values1, 2))\n For r = 1 To UBound(Values1)\n For c = 1 To UBound(Values1, 2)\n If Values1(r, c) &lt;&gt; Values2(r, c) Then\n Count = Count + 1\n Results(r, c) = Values1(r, c) &amp; vbNewLine &amp; Values2(r, c)\n End If\n Next\n Next\n Workbooks.Add.Worksheets(1).Range(Range1.Address).Value = Results\n Debug.Print \"Compare2WorkSheets: \", Worksheet1.Name; \" to \"; Worksheet2.Name\n Debug.Print \"Runtime in Second(s):\"; Round(Timer - t, 2)\n Debug.Print \"Number of Cells per Worksheet: \"; Range1.CountLarge\n Debug.Print \"Number of Differences: \"; Count\n MsgBox \"There were \" &amp; Count &amp; \" Differences\"\nEnd Sub\n\nSub SetRanges(ByRef Worksheet1 As Worksheet, ByRef Worksheet2 As Worksheet, ByRef Range1 As Range, ByRef Range2 As Range)\n With Worksheet1\n Set Range1 = Union(.UsedRange, .Range(Worksheet2.UsedRange.Address))\n End With\n With Worksheet2\n Set Range2 = Union(.UsedRange, .Range(Worksheet1.UsedRange.Address))\n End With\nEnd Sub\n</code></pre>\n\n<h2>Results</h2>\n\n<p><a href=\"https://i.stack.imgur.com/Sd2gH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Sd2gH.png\" alt=\"Immediate Window Screenshot\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T00:14:31.183", "Id": "439508", "Score": "0", "body": "Again you win my respect, the way you matched the Ranges using the Range addresses. would you please throw some light on my recent serious apprehensions about using union range method with large non contiguous area count at least in excel 2007. May refer my to [boring post](https://codereview.stackexchange.com/questions/224874/brute-force-looping-formatting-or-create-union-range-format-which-is-effici/224937#224937)] and may provide some more information. Actually while posting that I hoped for some info from you, @Tim William etc" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T20:09:08.203", "Id": "439944", "Score": "0", "body": "@TinMan please have a look at my new post, it is regarding the code from question. [https://codereview.stackexchange.com/questions/226346/compare-two-excel-sheets-by-cell-content]" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T20:00:55.997", "Id": "226206", "ParentId": "226160", "Score": "2" } } ]
{ "AcceptedAnswerId": "226197", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T07:53:48.957", "Id": "226160", "Score": "4", "Tags": [ "performance", "vba", "excel" ], "Title": "Find differences between two spreadsheets" }
226160
<p>This program converts glob files' tabs to spaces. There is a special case to ignore content inside triple back ticks.</p> <p>Example usage is <code>./tab_2_spaces.py *.md</code></p> <p><strong>Main Concern</strong>: Can I write the while loop better? </p> <pre><code>#!/usr/bin/env python3 """ This program is used to convert markdown file's tab indentations to 2 spaces. """ import argparse from pathlib import Path import os import io import itertools from multiprocessing import Pool _TAB_2_SPACE = " " def fix_indent(filename): with io.open(filename, mode="r", encoding="utf-8") as h: text = h.read() lines = text.splitlines(True) c = len(lines) i = 0 # Replace tab to spaces while i &lt; c: line = lines[i] if line.startswith("```"): i += 1 while i &lt; c: if lines[i].startswith("```"): break i += 1 else: continue break elif line.startswith("\t"): lines[i] = line.replace("\t", _TAB_2_SPACE) i += 1 with io.open(filename, mode="w", encoding="utf-8") as h: h.write("".join(lines)) def main(): parser = argparse.ArgumentParser(description="Fix indent") parser.add_argument( "files", metavar="N", type=str, nargs="+", help="List of files to scan" ) args = parser.parse_args() all_files = tuple( itertools.chain( *[ (filename for filename in Path().glob("**/" + file_)) for file_ in args.files ] ) ) with Pool(2) as process_pool: process_pool.map(fix_indent, all_files) if __name__ == "__main__": main() </code></pre>
[]
[ { "body": "<p>A lot of the code in your while loop can be replaced with a for loop using <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"nofollow noreferrer\"><code>enumerate()</code></a> and a toggled boolean.</p>\n\n<p>You should be able to replace your code from <code>c = len(lines)</code> (line 21) down through your entire while loop with:</p>\n\n<hr>\n\n<pre><code>skip = False\nfor index, line in enumerate(lines):\n if line.startswith(\"```\"):\n skip = not skip\n else:\n if not skip:\n if line.startswith(\"\\t\"):\n lines[index] = line.replace(\"\\t\", _TAB_2_SPACE)\n</code></pre>\n\n<hr>\n\n<p>I can't test this right now, so please let me know if you run in to any problems with this implementation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-10T10:00:19.387", "Id": "443548", "Score": "0", "body": "You can merge `else` and `if` to an `elif` and next `if` with an `and`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-10T10:03:25.310", "Id": "443549", "Score": "2", "body": "`elif not skip and line.startswith(\"\\t\"):`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-10T17:14:03.237", "Id": "443627", "Score": "0", "body": "@bhathiya-perera I felt that my implementation was easier to read so I chose not to condense it, but you are correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-10T20:03:57.977", "Id": "443658", "Score": "1", "body": "Indeed. It's far better than the Java like Python I've written above. :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-10T03:07:02.247", "Id": "227754", "ParentId": "226164", "Score": "2" } } ]
{ "AcceptedAnswerId": "227754", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T09:43:04.390", "Id": "226164", "Score": "4", "Tags": [ "python", "python-3.x", "parsing", "markdown" ], "Title": "Tab 2 spaces convertor (for markdown)" }
226164
<p>This script based on previous <a href="https://codereview.stackexchange.com/questions/226101/nrpe-script-for-monitoring-load-average">NRPE script for monitoring load average</a>. Same purpouse - get NRPE friendly output with minimal usage of non built in commands. In this case wasn't need to count with floating point. So I could omit <code>bc</code>.</p> <p>Yes, I read <a href="https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice">Why is using a shell loop to process text considered bad practice.</a> And there is a lot of true. Bud I am still thinking about these NRPE scripts as about bash scripting trainnig to get more practice.</p> <p>Desired output:</p> <p><strong>MEMORY_TOTAL=2041316kB MEMORY_AVAILABLE=1049260kB | MEMORY_IN_PERCENTAGE=51;80;90</strong></p> <pre><code>#!/usr/bin/env bash set -o errexit -o pipefail warning=80 critical=90 while read -a meminfo_row; do # Remove the colon character. row_value_lenght=$(( ${#meminfo_row[0]} -1 )) row_value=${meminfo_row[0]:0:$row_value_lenght} case $row_value in MemTotal) mem_total=${meminfo_row[1]} mem_apercent=$(( meminfo_row[1] / 100 )) ;; MemAvailable) mem_available=${meminfo_row[1]} ;; esac done &lt; /proc/meminfo mem_percentage=$(( mem_available / mem_apercent )) if [[ -z $mem_percentage ]]; then returned_text="MEMORY UNKNOWN - check script" returned_code=3 else returned_text="MEMORY_TOTAL=${mem_total}kB MEMORY_AVAILABLE=${mem_available}kB | MEMORY_IN_PERCENTAGE=$mem_percentage;$warning;$critical" if [[ $mem_percentage -gt $critical ]]; then returned_code=2 elif [[ $mem_percentage -gt $warning ]]; then returned_code=1 else returned_code=0 fi fi echo "$returned_text" exit $returned_code </code></pre>
[]
[ { "body": "<p>I don't understand why it should be a warning to have over 80% of the system RAM available. If anything needs a warning, it should be having under 20% of RAM available, right?</p>\n\n<p>Reading each line into an array is overcomplicated. The <code>read</code> builtin command is quite good at splitting each line of input into multiple variables. (<code>row_value_lenght</code> is misspelled, by the way.)</p>\n\n<p>The <a href=\"http://man7.org/linux/man-pages/man5/proc.5.html\" rel=\"nofollow noreferrer\">proc(5) man page</a> says about <code>/proc/meminfo</code>:</p>\n\n<blockquote>\n <p>Each line of the file consists of a parameter name, followed by a colon, the value of the parameter, and an option unit of measurement (e.g., \"kB\").</p>\n</blockquote>\n\n<p>There's no guarantee that the unit will be <code>kB</code> (as you have assumed in your printout), or that both lines of interest will have the same units.</p>\n\n<p>Splitting up the calculation of <code>mem_percentage</code> is weird.</p>\n\n<p>The <code>echo</code> statement should be line-wrapped for readability.</p>\n\n<p>The cases for exit codes 0, 1 and 2 can be collapsed into one, using arithmetic.</p>\n\n<pre><code>#!/usr/bin/env bash\n\nset -o errexit -o pipefail\n\nwarning=80\ncritical=90\n\nwhile read -r label number unit ; do\n case \"$label\" in\n MemTotal:)\n mem_total=$number\n mem_total_unit=$unit\n ;;\n MemAvailable:)\n mem_avail=$number\n mem_avail_unit=$unit\n ;;\n esac\ndone &lt; /proc/meminfo\n\nif [ -z \"$mem_avail\" -o \"$mem_avail_unit\" != \"$mem_total_unit\" ]; then\n echo \"MEMORY UNKNWOWN - check script\"\n exit 3\nfi\n\nmem_avail_percent=$(( 100 * $mem_avail / $mem_total ))\necho \"MEMORY_TOTAL=$mem_total$mem_total_unit\" \\\n \"MEMORY_AVAILABLE=$mem_avail$mem_avail_unit\" \\\n \"|\" \\\n \"MEMORY_IN_PERCENTAGE=$mem_avail_percent;$warning;$critical\"\nexit $(( ($mem_avail_percent &gt; $warning) + ($mem_avail_percent &gt; $critical) ))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T09:10:01.450", "Id": "439573", "Score": "0", "body": "Thanks a lot for the great tips. I just turned aritmetic operation as: `warning=\"20\"; critical=\"10\"; mem_avail_percent=\"5\"; echo $(( $mem_avail_percent < $warning) + ($mem_avail_percent < $critical) ))` = 2. I really like that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T23:51:55.550", "Id": "226223", "ParentId": "226169", "Score": "2" } } ]
{ "AcceptedAnswerId": "226223", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T12:31:44.877", "Id": "226169", "Score": "1", "Tags": [ "bash", "linux", "shell", "plugin", "status-monitoring" ], "Title": "NRPE script for monitoring memory usage" }
226169
<p>I have a place where i have to include a HTML template. The HTML is written by employees only but i dont wanna be an idiot and include it without masking|checks :)</p> <p>It should allow HTML tags only without any attributes.</p> <p>So no <code>&lt;a href...</code> links and no <code>&lt;div style=...</code> divs or w/e.</p> <p>My test script:</p> <pre><code>$string = ' &lt;p&gt; &lt;strong&gt;Foo&lt;/strong&gt; &lt;/p&gt; &lt;p&gt;Bar&lt;/p&gt; &lt;p&gt; &lt;strong&gt;Baz&lt;/strong&gt;&amp;nbsp;Mmmpf &lt;/p&gt; &lt;ul&gt; &lt;li&gt;someting&lt;/li&gt; &lt;li&gt;someting more&lt;/li&gt; &lt;li&gt;even more&lt;/li&gt; &lt;/ul&gt; &lt;p&gt; &lt;strong&gt;Foo&lt;/strong&gt; &lt;/p&gt; &lt;i&gt;Foo &lt;u&gt;Bar&lt;/u&gt;&lt;/i&gt;Baz &lt;!-- xss --&gt; &lt;script&gt;alert(1)&lt;/script&gt; &lt;p onmouseover="alert(1)"&gt;&lt;/p&gt; &lt;!-- ... --&gt; '; $htmlWhitelist = [ 'u', 'i', 'p', 'strong', 'ul', 'li', ]; // replace allowed tags with placeholders // that not get changed by htmlspecialchars() foreach ($htmlWhitelist as $tag) { $string = str_replace( ["&lt;{$tag}&gt;", "&lt;/{$tag}&gt;"], ["{OPEN}{$tag}{OPEN}", "{CLOSE}{$tag}{CLOSE}"], $string ); } // htmlspecialchars() on everything $string = htmlspecialchars($string); // put back the allowed tags foreach ($htmlWhitelist as $tag) { $string = str_replace( ["{OPEN}{$tag}{OPEN}", "{CLOSE}{$tag}{CLOSE}"], ["&lt;{$tag}&gt;", "&lt;/{$tag}&gt;"], $string ); } </code></pre> <p>I cannot imagine anything could go wrong with this but would like to ask you guys if i missed someting.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T14:53:21.497", "Id": "439420", "Score": "0", "body": "Could you include the code that uses `$string`? I'd like to see how the output is used" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T14:56:47.323", "Id": "439421", "Score": "0", "body": "Could you also add how `$string` is really retrieved? I'd like to see how you get the user input" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T15:08:27.740", "Id": "439422", "Score": "0", "body": "$string is output from an internal micro service (HTTP local network) that returns internal templates. The string SHOULD be save, but ofc it would be an bad idea to rely on it. Thats why i use htmlspecialchars on everything (no twig or so, plain php|phtml atm). But this template must be rendered by the browser. I use `<?php echo cleanHtmlTagsOnly($string); ?>` to write it into the output, where `cleanHtmlTagsOnly()` is the code in the question." } ]
[ { "body": "<p>I did some testing and research on this, AFAIK your script is safe.</p>\n\n<p>However, you should also be aware of how you retrieve the input. For example, what if the String contained a <code>\"</code>, followed by executing PHP code. This would be an even worse vulnerability than malicious client-side code.</p>\n\n<p><a href=\"https://security.stackexchange.com/questions/100769/is-using-htmlentities-or-htmlspecialchars-functions-enough-to-block-xss-attack\">This post</a> states old versions of IE may be vulnerable if your char-set is UTF-7, which it probably isn't.</p>\n\n<p>If <code>&lt;div style...&gt;</code> is entered, it will be escaped. Therefore <code>&lt;div&gt;</code> and <code>&lt;span&gt;</code> should be included.</p>\n\n<p>I believe every tag can have an <code>onload=script</code>, (E.G <code>&lt;u onload=\"script\"&gt;</code>), so only allowing tags by themselves is a good idea. (As you are already doing)</p>\n\n<p>I suggest adding <code>div</code>, <code>span</code>, <code>b</code>, <code>br</code> and many other tags to the whitelist.</p>\n\n<p>Edit: Since you mentioned you use PHP to <code>echo</code> the output, I also suggest testing using PHP functions or variables in the input, such as <code>$_SERVER['REMOTE_ADDR']</code>. </p>\n\n<p>Will the output show the result of that variable, or the literal text?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T15:45:02.073", "Id": "439431", "Score": "0", "body": "Indeed it outputs a `$var`. `$string = \"<span>some html...</span> $var <div>...\"; echo $string;` -ofc executes|includes the variable - didnt thought about that. So an somebody that has access to the templates could add `</span> ... {$_SERVER['...']} ...` to get it printed|executed. How do i prevent that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T15:50:54.553", "Id": "439432", "Score": "1", "body": "No wait - forget it. I receive and handle a string. I was confused for a moment. Nothing in the string gets interpreted. I would have to use eval to do so, but ofc i dont :D" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T14:52:42.623", "Id": "226181", "ParentId": "226176", "Score": "1" } } ]
{ "AcceptedAnswerId": "226181", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T14:02:27.053", "Id": "226176", "Score": "2", "Tags": [ "php", "html", "security" ], "Title": "PHP allow template to use HTML only" }
226176
<p>I am a learner in Go and wrote example below in a day so I would like to get some suggestions to improve it. It is a simple rest api that currently just accepts request and returns a dummy message. My main aim here is to get comments and suggestions on how I structured the flow/logic. Although it currently works fine and easy to follow (at least to me), could it be done in a cleaner/scalable way?</p> <p><strong>cmd/server.go</strong></p> <pre><code>package main import ( "fmt" "football-api/internal/app/route" "log" "net/http" ) type server struct {} func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) { response, err := route.Handler(r) if err != nil { w.WriteHeader(http.StatusNotFound) } else { w.WriteHeader(http.StatusOK) } w.Write([]byte(response)) } func main() { fmt.Println("Server is running on port 8080 ...") err := http.ListenAndServe(":8080", &amp;server{}) if err != nil { log.Fatalf("Couldn't start server on :8080. [%s]", err.Error()) } } </code></pre> <p><strong>internal/app/route/handler.go</strong></p> <pre><code>package route import ( "errors" "net/http" "path/filepath" ) func Handler(r *http.Request) (response string, err error) { switch filepath.Clean(r.URL.Path) { case "/": return Home(r), nil case "/comments": return Comments(r), nil default: return "", errors.New("route was not found") } } </code></pre> <p><strong>internal/app/route/home.go</strong></p> <pre><code>package route import "net/http" func Home(r *http.Request) string { return "Home" } </code></pre> <p><strong>internal/app/route/comments.go</strong></p> <pre><code>package route import "net/http" func Comments(r *http.Request) string { return "Comments" } </code></pre>
[]
[ { "body": "<p>There's not so much code that it would be hard to read, looks clean enough to me.</p>\n\n<p>Regarding scalable ... in what way? The switch in <code>Handler</code> will be the limiting factor since adding another route will always have to have a corresponding edit in that function. Some frameworks will have ways around that (for better or worse), but as long as there are just a handful of routes I doubt it's a real issue (though if this is more of an exercise, go for it: if you have a hundred handlers, how could you register them instead of having a single point like here?).</p>\n\n<p>In <code>ServeHTTP</code> there'll definitely be an issue with the need for additional, more nuanced error codes. I'm not suggesting a particular solution, but I can see that happening quite quickly ... plus, 404 for an internal error looks wrong too, that should be 500 most likely, only if the route couldn't be found 404 would be appropriate.</p>\n\n<hr>\n\n<p>Okay two more, returning a <code>string</code> instead of directly writing output will be a scalability problem, it'd be much better to avoid additional memory allocations to construct that string and simply write to the output buffer / writer directly.</p>\n\n<p>And, the result of a <code>errors.New</code> can be stored in a global variable as long as the message doesn't change - one more memory allocation gone.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T19:54:14.887", "Id": "440553", "Score": "1", "body": "`scalable`: I was thinking of making things decoupled but I since discovered DI in go its ok for now. I inject structs into dependent structs with constructors now. `more routes`: I'll have to deal with them manually for now but it shouldn't be problem adding a line for a new route. `more status codes and content return`: I'll follow your suggestion and inject ResponseWriter to route files to direct output there rather than returning. `errors.New`: I'll follow your suggestion. Thanks for the input. +1. I hope I understood your suggestions correctly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T21:21:03.727", "Id": "226597", "ParentId": "226177", "Score": "1" } } ]
{ "AcceptedAnswerId": "226597", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T14:05:08.913", "Id": "226177", "Score": "2", "Tags": [ "beginner", "go", "rest", "url-routing" ], "Title": "Simple Go REST API that returns dummy messages" }
226177
<p>I want to implement cycle crossover in python, and I want to do this in the easiest way. In cycle crossover, a vertex should be copied into the child from one parent, but its position should be inherited from the other parent. Here is a link to how it works: <br><a href="http://www.rubicite.com/Tutorials/GeneticAlgorithms/CrossoverOperators/CycleCrossoverOperator.aspx" rel="nofollow noreferrer">http://www.rubicite.com/Tutorials/GeneticAlgorithms/CrossoverOperators/CycleCrossoverOperator.aspx</a> <br></p> <h3>Description</h3> <blockquote> <p>Cycle crossover is an operator in genetic algorithm, to create offsprings for the new population. This crossover is used for problems such as the travel salesman problem, to find the shortest possible route, over generations.</p> </blockquote> <h3>Algorithm</h3> <blockquote> <p><strong>Cycle Crossover Operator</strong> The Cycle Crossover operator identifies a number of so-called cycles between two parent chromosomes. Then, to form Child 1, cycle one is copied from parent 1, cycle 2 from parent 2, cycle 3 from parent 1, and so on.</p> <p>Here's an example:</p> <ul> <li>Parent 1: <code>8 4 7 3 6 2 5 1 9 0</code></li> <li>Parent 2: <code>0 1 2 3 4 5 6 7 8 9</code></li> </ul> <p><strong>Cycle 1</strong><br> <em>Values</em>: <code>8 9 0</code> which will be marked Orange. We start with the first value in Parent 1 and drop down to the same position in Parent 2. <code>8</code> Goes to <code>0</code>. Then, we look for <code>0</code> in Parent 1 and find it at the 10th position where we drop down to <code>9</code>. Again, we look for this value in Parent 1 and find it in the 9th position and drop down to <code>8</code>. Since we started with <code>8</code>, we've completed our cycle.</p> <ul> <li>Parent 1: <code>8 4 7 3 6 2 5 1 9 0</code></li> <li>Parent 2: <code>0 1 2 3 4 5 6 7 8 9</code></li> </ul> <p><strong>Cycle 2</strong><br> <em>Values</em>: 4 1 7 2 5 6 which will be marked Red. We start with <code>4</code> and drop down to <code>1</code>. <code>1</code> is found in the 8th position in Parent 1 and we drop down to <code>7</code>. <code>7</code> Drops down to <code>2</code>, <code>2</code> Drops down to <code>5</code>, <code>5</code> drops down to <code>6</code>, and <code>6</code> drops down to <code>4</code> - Our cycle is complete.</p> <ul> <li>Parent 1: <code>8 4 7 3 6 2 5 1 9 0</code></li> <li>Parent 2: <code>0 1 2 3 4 5 6 7 8 9</code></li> </ul> <p><strong>Cycle 3</strong><br> <em>Value</em>: 3 The only possible cycle left is of length 1 and contains the value <code>3</code>. </p> <p>Filling in the offspring:</p> <ul> <li>Parent 1: <code>8 4 7 3 6 2 5 1 9 0</code></li> <li><p>Parent 2: <code>0 1 2 3 4 5 6 7 8 9</code></p></li> <li><p>Child 1: <code>8 1 2 3 4 5 6 7 9 0</code></p></li> <li>Child 2: <code>0 4 7 3 6 2 5 1 8 9</code> </li> </ul> <p>Finishing steps:</p> <ul> <li><p>Copy Cycle 1: Cycle 1 values from Parent 1 and copied to Child 1, and values from Parent 2 will be copied to Child 2. Cycle 2 will by different.</p></li> <li><p>Copy Cycle 2: Cycle 2 values from Parent 1 will be copied to Child 2, and values from Parent 1 will be copied to Child 1.</p></li> <li><p>Copy Cycle 3: Cycle 3 is like Cycle 1, Parent 1 goes to Child 1, Parent 2 goes to Child 2.</p></li> </ul> </blockquote> <p>I am wondering that is there an easier way to do this.<br> Thank you </p> <pre class="lang-py prettyprint-override"><code>import numpy as np from copy import deepcopy class chromosome(): def __init__(self, genes, id=None, fitness=-1, flatten= False, lengths=None): self.id = id self.genes = genes self.fitness = fitness def describe(self): print('ID=#{}, fitenss={}, \ngenes=\n{}'.format(self.id, self.fitness, self.genes)) # gives the length of a chromosome def chrom_length(self): return len(self.genes) "Cycle crossover" def CX(pop, pop_size, selection_method, pc): p1 = chromosome(genes= np.array([8,4,7,3,6,2,5,1,9,0]),id=0,fitness = 125.2) p2 = chromosome(genes= np.array([0,1,2,3,4,5,6,7,8,9]),id=1,fitness = 125.2) chrom_length = chromosome.chrom_length(p1) print("\nParents") print("=================================================") chromosome.describe(p1) chromosome.describe(p2) c1 = chromosome(genes= np.array([-1]*chrom_length),id=0,fitness = 125.2) # childs c2 = chromosome(genes= np.array([-1]*chrom_length),id=1,fitness = 125.2) if np.random.random() &lt; pc: # if pc is greater than random number p1_copy = p1.genes.tolist() p2_copy = p2.genes.tolist() swap = True count = 0 pos = 0 while True: if count&gt;chrom_length: break for i in range(chrom_length): if c1.genes[i]==-1: pos=i break if swap==True: while True: c1.genes[pos] = p1.genes[pos] count+=1 pos = p2.genes.tolist().index(p1.genes[pos]) if p1_copy[pos] == -1: swap = False break p1_copy[pos] = -1 elif swap==False: while True: c1.genes[pos] = p2.genes[pos] count+=1 pos = p1.genes.tolist().index(p2.genes[pos]) if p2_copy[pos] == -1: swap = True break p2_copy[pos] = -1 for i in range(chrom_length): #for the second child if c1.genes[i]==p1.genes[i]: c2.genes[i]=p2.genes[i] else: c2.genes[i]=p1.genes[i] for i in range(chrom_length): #Special mode if c1.genes[i]==-1: if p1_copy[i]==-1: #it means that the ith gene from p1 has been already transfered c1.genes[i]=p2.genes[i] else: c1.genes[i]=p1.genes[i] else: # if pc is less than random number then don't make any change c1 = deepcopy(p1) c2 = deepcopy(p2) return c1, c2 cross = CX(20, 10,"tour",1) print("\nChilds") print("=================================================") for i in range(len(cross)): chromosome.describe(cross[i]) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T15:54:24.213", "Id": "439433", "Score": "4", "body": "Hi, I highly suggest that you explain *here* what's the \"cycle crossover\" because your link might rot and because it's the best way to get reviewers involved in the review (I, for example, pretty much never click on an external link, I'd skip the post instead)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T20:27:37.370", "Id": "439480", "Score": "3", "body": "At the least, the indentation of the code in this question needs to be fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T09:03:53.540", "Id": "439870", "Score": "0", "body": "Cycle crossover is an operator in genetic algorithm, to create offsprings for the new population. This crossover is used for problems such as the travel salesman problem, to find the shortest possible route, over generations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T15:35:23.660", "Id": "439910", "Score": "1", "body": "Define 'easiest way'." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T18:02:08.137", "Id": "439934", "Score": "2", "body": "Do the chromosomes actually have 10 genes, or is that a simplification for posting the problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T20:38:23.403", "Id": "440084", "Score": "0", "body": "The size of the chromosomes can be different according to the problem. Their values can also be binary, integer, or floating point. @RootTwo" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T20:43:08.410", "Id": "440085", "Score": "0", "body": "With least lines of codes. @Mast" } ]
[ { "body": "<h1>Docstrings</h1>\n\n<p>You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>docstring</code></a> at the beginning of every method, class, and module you write. It allows anyone to view how to use and implement your method, using <code>your_function_name.__doc__</code> or <code>help(your_function_name)</code>.</p>\n\n<h1>Class Naming</h1>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#class-names\" rel=\"nofollow noreferrer\">PEP-8 Compliance</a> requires that all class names should use the CapWords convention. In your case, since <code>Chromosome</code> is one word, it should be capitalized.</p>\n\n<h1>Reserved Keywords</h1>\n\n<p>You have an init header like so:</p>\n\n<pre><code>def __init__(self, genes, id=None, fitness=-1, flatten= False, lengths=None):\n ...\n</code></pre>\n\n<p>It is suggested <strong><em>not</em></strong> to use a variable/parameter name <code>id</code>, or any other reserved keywords. This can cause collision and other issues in your program. As a quick fix, I renamed it <code>id_</code>, but you can rename it to something more meaningful/easier to understand.</p>\n\n<h1>Unused Arguments</h1>\n\n<p>You have two method headers like so:</p>\n\n<pre><code>def __init__(self, genes, id=None, fitness=-1, flatten= False, lengths=None):\n ...\ndef CX(pop, pop_size, selection_method, pc):\n ...\n</code></pre>\n\n<p>You only use four (technically three, since <code>self</code> is required in class methods) in the <code>__init__</code> method, and one in the <code>CX</code> method. If you finish writing a program/method, and see that some parameters you take in aren't used, remove them. This can prevent confusion later on when you decide to take another look at your code and try to find the significance of the parameters you don't use.</p>\n\n<h1>Parameter Spacing</h1>\n\n<p>When writing default passed/accepting parameters, there should not be a space between the variable, the <code>=</code>, and the value. So, <code>flatten= False</code> is not okay, but <code>flatten=False</code> is okay. You can look at the updated code, as I fixed every occurrence of this.</p>\n\n<h1>Variable/Operator Spacing</h1>\n\n<p>On the contrary, when using variables and operators, there <em>should</em> be a space. This allows for better readability. This also accounts for lists. Seeing <code>[8,4,7,3,6,2,5,1,9,0]</code>, at least to me, is hard to read. Everything is clumped together. But <code>[8, 4, 7, 3, 6, 2, 5, 1, 9, 0]</code> is easier to read and comprehend. Everything is spaced out, and the numbers jump out at you more.</p>\n\n<h1>Main Guard</h1>\n\n<p>You have this code lying outside your class/methods:</p>\n\n<pre><code>cross = CX(20, 10,\"tour\",1)\nprint(\"\\nChilds\")\nprint(\"=================================================\")\nfor i in range(len(cross)):\n chromosome.describe(cross[i])\n</code></pre>\n\n<p>Wrapping this in a <code>if __name__ == '__main__':</code> guard is a good idea. Having a main guard clause in a module allows you to both run code in the module directly and also use procedures and classes in the module from other modules. Without the main guard clause, the code to start your script would get run when the module is imported. <a href=\"https://stackoverflow.com/a/19578335/8968906\">[source]</a></p>\n\n<p>So your new code should look like this:</p>\n\n<pre><code>if __name__ == '__main__':\n\n CROSS = cycle_crossover(1)\n print(\"\\nChildren\")\n print(\"=================================================\")\n for index, _ in enumerate(CROSS):\n Chromosome.describe(CROSS[index])\n</code></pre>\n\n<p><em>Notice how I use <code>enumerate()</code> vs <code>range(len())</code>. I explain this change later.</em></p>\n\n<h1>Boolean Comparison</h1>\n\n<pre><code>if swap==True:\n ...\nelif swap==False:\n ...\n</code></pre>\n\n<p>This is unnecessary. You can use the variable <code>swap</code> as the value itself. You can check the value of <code>swap</code> itself to see if it's <code>True</code> or <code>False</code>, instead of comparing it to the boolean, like so:</p>\n\n<pre><code>if swap:\n ...\nelse:\n ...\n</code></pre>\n\n<p>Also, the second <code>swap==False</code> check is unnecessary. If it doesn't pass the first check of being <code>True</code>, then it has to be <code>False</code>. So only an <code>else</code> is necessary here.</p>\n\n<h1>String Formatting f\"\"</h1>\n\n<p>This one is my opinion. I like to use <code>f\"...\"</code> to format my strings. It allows me to directly implement the variables into the string, without having to call the <code>format</code> method on it. I left both versions in the updated code, just comment out the one you don't like.</p>\n\n<h1>Meaningful Method Naming</h1>\n\n<p><code>CX</code>. What do you think of when you first see this? To someone reading your code for the first time, they would have no idea what this method is supposed to do. Methods should have meaningful names, so someone can get the general idea about that method by just looking at the name.</p>\n\n<h1>Variable Naming</h1>\n\n<p>You have variables like <code>p1</code>, <code>p2</code>, <code>c1</code>, <code>c2</code>, etc. My initial thoughts were that <code>p1</code> and <code>p2</code> were population one and two, since the parameters in the method were <code>pop</code> and <code>pop_size</code>. It wasn't until I saw the comment that was <code>c1</code> and <code>c2</code> were <em>children</em> that I realized <code>p1</code> and <code>p2</code> were <em>parents</em>. You should provide more meaningful variable names to avoid this confusion. Also, variable names should be <code>snake_case</code>.</p>\n\n<h1>enumerate() vs range(len())</h1>\n\n<p>Consider using <code>enumerate</code> vs <code>range(len(...))</code>. I would use <code>enumerate</code> as it's more generic - eg it will work on iterables and sequences, and the overhead for just returning a reference to an object isn't that big a deal - while range(len(...)) although (to me) more easily readable as your intent - will break on objects with no support for <code>len</code>.</p>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring:\nA description of your program goes here\n\"\"\"\n\nfrom copy import deepcopy\nimport numpy as np\n\nclass Chromosome():\n \"\"\"\n Description of class `Chromosome` goes here\n \"\"\"\n def __init__(self, genes, id_=None, fitness=-1):\n self.id_ = id_\n self.genes = genes\n self.fitness = fitness\n\n def describe(self):\n \"\"\"\n Prints the ID, fitness, and genes\n \"\"\"\n #print('ID=#{}, fitenss={}, \\ngenes=\\n{}'.format(self.id, self.fitness, self.genes))\n print(f\"ID=#{self.id_}, Fitness={self.fitness}, \\nGenes=\\n{self.genes}\")\n\n def get_chrom_length(self):\n \"\"\"\n Returns the length of `self.genes`\n \"\"\"\n return len(self.genes)\n\ndef cycle_crossover(pc):\n \"\"\"\n This function takes two parents, and performs Cycle crossover on them. \n pc: The probability of crossover (control parameter)\n \"\"\"\n parent_one = Chromosome(genes=np.array([8, 4, 7, 3, 6, 2, 5, 1, 9, 0]), id_=0, fitness=125.2)\n parent_two = Chromosome(genes=np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), id_=1, fitness=125.2)\n chrom_length = Chromosome.get_chrom_length(parent_one)\n print(\"\\nParents\")\n print(\"=================================================\")\n Chromosome.describe(parent_one)\n Chromosome.describe(parent_two)\n child_one = Chromosome(genes=np.array([-1] * chrom_length), id_=0, fitness=125.2)\n child_two = Chromosome(genes=np.array([-1] * chrom_length), id_=1, fitness=125.2)\n\n if np.random.random() &lt; pc: # if pc is greater than random number\n p1_copy = parent_one.genes.tolist()\n p2_copy = parent_two.genes.tolist()\n swap = True\n count = 0\n pos = 0\n\n while True:\n if count &gt; chrom_length:\n break\n for i in range(chrom_length):\n if child_one.genes[i] == -1:\n pos = i\n break\n\n if swap:\n while True:\n child_one.genes[pos] = parent_one.genes[pos]\n count += 1\n pos = parent_two.genes.tolist().index(parent_one.genes[pos])\n if p1_copy[pos] == -1:\n swap = False\n break\n p1_copy[pos] = -1\n else:\n while True:\n child_one.genes[pos] = parent_two.genes[pos]\n count += 1\n pos = parent_one.genes.tolist().index(parent_two.genes[pos])\n if p2_copy[pos] == -1:\n swap = True\n break\n p2_copy[pos] = -1\n\n for i in range(chrom_length): #for the second child\n if child_one.genes[i] == parent_one.genes[i]:\n child_two.genes[i] = parent_two.genes[i]\n else:\n child_two.genes[i] = parent_one.genes[i]\n\n for i in range(chrom_length): #Special mode\n if child_one.genes[i] == -1:\n if p1_copy[i] == -1: #it means that the ith gene from p1 has been already transfered\n child_one.genes[i] = parent_two.genes[i]\n else:\n child_one.genes[i] = parent_one.genes[i]\n\n else: # if pc is less than random number then don't make any change\n child_one = deepcopy(parent_one)\n child_two = deepcopy(parent_two)\n return child_one, child_two\n\nif __name__ == '__main__':\n\n CROSS = cycle_crossover(1)\n print(\"\\nChildren\")\n print(\"=================================================\")\n for index, _ in enumerate(CROSS):\n Chromosome.describe(CROSS[index])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T18:38:11.937", "Id": "226388", "ParentId": "226179", "Score": "3" } }, { "body": "<p>The main part of CX can be simplified quite a bit. <code>cycles[pos]</code> is the cycle number of that position, or -1 it hasn't been determined yet. <code>cyclestart</code> is a generator that returns the next place for a cycle to start. </p>\n\n<pre><code>parent1 = [8, 4, 7, 3, 6, 2, 5, 1, 9, 0]\nparent2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\nif np.random.random() &lt; pc: # if pc is greater than random number\n\n cycles = [-1]*len(parent1)\n cycle_no = 1\n cyclestart = (i for i,v in enumerate(cycles) if v &lt; 0)\n\n for pos in cyclestart:\n\n while cycles[pos] &lt; 0:\n cycles[pos] = cycle_no\n pos = parent1.index(parent2[pos])\n\n cycle_no += 1\n\n child1 = [parent1[i] if n%2 else parent2[i] for i,n in enumerate(cycles)]\n child2 = [parent2[i] if n%2 else parent1[i] for i,n in enumerate(cycles)]\n\nelse:\n ...\n\nprint(\"parent1:\", parent1)\nprint(\"parent2:\", parent2)\nprint(\"cycles:\", cycles)\nprint(\"child1:\", child1)\nprint(\"child2:\", child2)\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>parent1: [8, 4, 7, 3, 6, 2, 5, 1, 9, 0]\nparent2: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\ncycles: [1, 2, 2, 3, 2, 2, 2, 2, 1, 1]\nchild1: [8, 1, 2, 3, 4, 5, 6, 7, 9, 0]\nchild2: [0, 4, 7, 3, 6, 2, 5, 1, 8, 9]\n</code></pre>\n\n<p>If the chromosomes are really long, it might be worth building a dict as a lookup table instead of using <code>parent1.index()</code>. Also changed it so cycle_no comes from enumerating cyclestart (the enumeration starts at 1, so child1 and child2 aren't swapped from the previous answer).</p>\n\n<pre><code>lookup = {v:i for i,v in enumerate(parent1)}\n\ncycles = [-1]*len(parent1)\ncyclestart = (i for i,v in enumerate(cycles) if v &lt; 0)\n\nfor cycle_no, pos in enumerate(cyclestart, 1):\n\n while cycles[pos] &lt; 0:\n cycles[pos] = cycle_no\n pos = lookup[parent2[pos]]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T18:39:29.787", "Id": "226389", "ParentId": "226179", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T14:37:58.150", "Id": "226179", "Score": "4", "Tags": [ "python" ], "Title": "Easiest way to implement cycle crossover" }
226179
<p>I am a self taught python beginner for about 3 months and recently I finished my own snake game project. As seen from the code, it is not very efficient nor tidy to look at so I want to know if there are any suggestions that can improve the reading of the code.</p> <p>I posted a similar topic on stackoverflow asking how to tidy it and I was answered with adding functions with parameters and return values, but I am currently struggling to do that as I lack the understanding of connecting them into my main function.</p> <p>But overall what do you think of the code? Because when I run it I thought it runs pretty well and it accomplishes exactly the way I want it to be.</p> <pre><code>from graphics import * from threading import Timer import keyboard, random, time # configurations width = 400 gridHeight = width height = 470 timer = False game = True score = 0 bonus = 0 x = 70 y = 30 radius = 10 length = radius * 2 playerLength = 3 poisonLength = playerLength i = 0 k = 0 pointRadius = 5 points = False cherryPoints = False key = "Right" countDown = 0 # set coordinations cX = 90 cY = 30 coordX = [10] coordY = [10] while coordX[len(coordX)-1] != width-10: cX+=20 coordX.append(cX) while coordY[len(coordY)-1] != 390: cY+=20 coordY.append(cY) randomX = random.choice(coordX) randomY = random.choice(coordY) cherryRandomX = random.choice(coordX) cherryRandomY = random.choice(coordY) poisonRandomX = random.choice(coordX) poisonRandomY = random.choice(coordY) # window set up win = GraphWin("SNAKE", width, height, autoflush = False) win.setBackground(color_rgb(15,15,15)) # grid lineX = 20 while lineX &lt; width: gridX = Line(Point(lineX,0),Point(lineX,gridHeight)) gridX.setOutline(color_rgb(25,25,25)) gridX.draw(win) lineX += 20 lineY = 20 while lineY &lt;= gridHeight: gridX = Line(Point(0,lineY),Point(width,lineY)) gridX.setOutline(color_rgb(25,25,25)) gridX.draw(win) lineY += 20 # snake banner UI = Rectangle(Point(0,400),Point(width,height)) UI.setFill(color_rgb(102,51,0)) UI.setOutline(color_rgb(102,51,0)) UI.draw(win) snakeTitle = Text(Point(width/2,420),"SNAKE") snakeTitle.setTextColor("green") snakeTitle.setSize(20) snakeTitle.draw(win) scoreTitle = Text(Point(320,424),"SCORE") scoreTitle.setTextColor("white") scoreTitle.setSize(10) scoreTitle.draw(win) scoreUI = Text(Point(320,435),score) scoreUI.setTextColor("white") scoreUI.setSize(10) scoreUI.draw(win) # make player player = {} player[0] = Rectangle(Point(x-20-radius,y-radius), Point(x-20+radius, y+radius)) player[1] = Rectangle(Point(x-40-radius,y-radius), Point(x-40+radius, y+radius)) player[2] = Rectangle(Point(x-60-radius,y-radius), Point(x-60+radius, y+radius)) # make poison poison = {} def main(): global timer, scoreUI, score, bonus, playerLength, poisonLength, x, y, points, cherryPoints, randomX, randomY, cherryRandomX, cherryRandomY, poisonRandomX, poisonRandomY, key, countDown, k, game while(game==True): # score update scoreUI.undraw() scoreUI = Text(Point(320,435),score) scoreUI.setTextColor("white") scoreUI.setSize(10) scoreUI.draw(win) # generating new body blocks if len(player) &lt; playerLength: i+=1 player[i] = player[i-1].clone() # body following player player[0].undraw() for i in range(1,len(player)): player[len(player)-i].undraw() player[len(player)-i] = player[len(player)-i-1].clone() player[len(player)-i].draw(win) # update player's head coordinate player[0] = Rectangle(Point(x-radius,y-radius), Point(x+radius,y+radius)) player[0].setFill("green") player[0].setWidth(2) player[0].draw(win) # player movement if keyboard.is_pressed("Up") and key != "Down": key = "Up" elif keyboard.is_pressed("Left") and key != "Right": key = "Left" elif keyboard.is_pressed("Down") and key != "Up": key = "Down" elif keyboard.is_pressed("Right") and key != "Left": key = "Right" if key == "Up": y -= length elif key == "Left": x -= length elif key == "Down": y += length elif key == "Right": x += length # point if points == False: # generates new point when eaten point = Rectangle(Point(randomX-pointRadius,randomY-pointRadius),Point(randomX+pointRadius,randomY+pointRadius)) point.setFill("white") point.setWidth(2) point.draw(win) points = True if player[0].getCenter().getX() == point.getCenter().getX() and player[0].getCenter().getY() == point.getCenter().getY(): # when player eats the point point.undraw() playerLength += 1 poisonLength += 1 score += 200+bonus randomX = random.choice(coordX) randomY = random.choice(coordY) for i in range(len(player)): if (point.getCenter().getX() == player[i].getCenter().getX() and point.getCenter().getY() == player[i].getCenter().getY()) or (cherryPoints == True and cherryPoint.getCenter().getX() == point.getCenter().getX() and cherryPoint.getCenter().getY() == point.getCenter().getY()): # regenerate x and y coordinate if they share the same coordinate as player and cherry randomX = random.choice(coordX) randomY = random.choice(coordY) for i in range(len(poison)): # regenerate x and y coordinate if point shares the same coordinate to other array of poisons if point.getCenter().getX() == poison[i].getCenter().getX() and point.getCenter().getY() == poison[i].getCenter().getY(): cherryRandomX = random.choice(coordX) cherryRandomY = random.choice(coordY) points = False # cherry if countDown == 150: countDown = 0 if cherryPoints == False: # generates new cherry from countdown cherryPoint = Rectangle(Point(cherryRandomX-pointRadius,cherryRandomY-pointRadius),Point(cherryRandomX+pointRadius,cherryRandomY+pointRadius)) cherryPoint.setFill(color_rgb(213,0,50)) cherryPoint.setWidth(2) cherryPoint.draw(win) cherryPoints = True if cherryPoints == True: for i in range(2, 6): # cherry blinks between countdown 40 to 100 if countDown == 20*i: cherryPoint.undraw() elif countDown == 10+(20*i): cherryPoint.draw(win) if countDown &gt;= 100: # when countdown becomes 100, remove cherry and reset count down cherryPoints = False countDown = 0 cherryRandomX = random.choice(coordX) cherryRandomY = random.choice(coordY) if cherryPoints==True and player[0].getCenter().getX() == cherryPoint.getCenter().getX() and player[0].getCenter().getY() == cherryPoint.getCenter().getY(): # when player eats the cherry cherryPoint.undraw() score += 500 cherryRandomX = random.choice(coordX) cherryRandomY = random.choice(coordY) for i in range(len(player)): if (cherryPoint.getCenter().getX() == player[i].getCenter().getX() and cherryPoint.getCenter().getY() == player[i].getCenter().getY()) or (cherryPoint.getCenter().getX() == point.getCenter().getX() and cherryPoint.getCenter().getY() == point.getCenter().getY()): # regenerate x and y coordinate if they share the same coordinate as player and point cherryRandomX = random.choice(coordX) cherryRandomY = random.choice(coordY) for i in range(len(poison)): # regenerate x and y coordinate if cherry shares the same coordinate to other array of poisons if cherryPoint.getCenter().getX() == poison[i].getCenter().getX() and cherryPoint.getCenter().getY() == poison[i].getCenter().getY(): cherryRandomX = random.choice(coordX) cherryRandomY = random.choice(coordY) cherryPoints = False # poison if poisonLength % 5 == 0: # generates a poison block each time the player size reaches the multiple of 5 poison[k] = Rectangle(Point(poisonRandomX-pointRadius,poisonRandomY-pointRadius),Point(poisonRandomX+pointRadius,poisonRandomY+pointRadius)) poison[k].setFill("green") poison[k].setWidth(2) poison[k].draw(win) poisonRandomX = random.choice(coordX) poisonRandomY = random.choice(coordY) for i in range(len(player)): if (poison[k].getCenter().getX() == player[i].getCenter().getX() and poison[k].getCenter().getY() == player[i].getCenter().getY()) or (poison[k].getCenter().getX() == point.getCenter().getX() and poison[k].getCenter().getY() == point.getCenter().getY()) or (cherryPoints==True and poison[k].getCenter().getX() == cherryPoint.getCenter().getX() and poison[k].getCenter().getY() == cherryPoint.getCenter().getY()): # regenerate x and y coordinate if they share the same coordinate as player and point and cherry poisonRandomX = random.choice(coordX) poisonRandomY = random.choice(coordY) for i in range(len(poison)): if poison[k].getCenter().getX() == poison[i].getCenter().getX() and poison[k].getCenter().getY() == poison[i].getCenter().getY(): # regenerate x and y coordinate if new poison shares the same coordinate to other array of poisons poisonRandomX = random.choice(coordX) poisonRandomY = random.choice(coordY) bonus+=50 k+=1 poisonLength+=1 # game over requirements for i in range(len(poison)): # if player touches poison if player[0].getCenter().getX() == poison[i].getCenter().getX() and player[0].getCenter().getY() == poison[i].getCenter().getY(): game = False for i in range(2, len(player)): # if player touches its own body or reach out of window if (player[0].getCenter().getX() == player[i].getCenter().getX() and player[0].getCenter().getY() == player[i].getCenter().getY()) or x &lt; 0 or x &gt; width or y &lt; 0 or y &gt; gridHeight: game = False # FPS update(10) countDown += 1 # GAME OVER gameOver = Text(Point(width/2,200), "GAME OVER") gameOver.setTextColor("red") gameOver.setSize(30) gameOver.draw(win) update() time.sleep(2) win.close() main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T15:58:38.517", "Id": "439435", "Score": "0", "body": "I'd suggest formatting your text so it's not just \"big\" paragraphs. Maybe split it with \"What the code does\" then \"What you think could be improved\", it'll be easier to read :)" } ]
[ { "body": "<ul>\n<li><strong>Docstrings</strong>: You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>docstring</code></a> at the beginning of every method, class and module you write. This will allow documentation to identify what your program is supposed to accomplish.</li>\n<li><strong>Wildcard Import Statements</strong>: <code>from ... import *</code> should be avoided. You can end up importing something that you don't use/need, which can cause name collisions and other issues. You should refer to <a href=\"https://stackoverflow.com/a/3615206/8968906\">this StackOverflow answer</a> for more information. Figure out what you need and what you don't need from <code>graphics</code>.</li>\n<li><strong>Unused Imports</strong>: You don't use <code>from threading import Timer</code>. This creates a dependency that does not need to exist and makes the code more difficult to read.</li>\n<li><strong>Multiple Imports on one line</strong>: You have <code>import keyboard, random, time</code>. This does not comply with <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">PEP-8s section on Imports</a>. You should put each import on it's own line, with the exception of importing multiple specific things from a module, like so: <code>from ... import ..., ...</code>.</li>\n<li><strong>Ordering Imports</strong>: You should order your imports like so: \n\n<ol>\n<li><blockquote>\n <p>Standard library imports</p>\n</blockquote></li>\n<li><blockquote>\n <p>Related third party imports</p>\n</blockquote></li>\n<li><blockquote>\n <p>Local application/library specific imports</p>\n</blockquote></li>\n</ol></li>\n<li><strong>Variable/Operator Spacing</strong>: You should have a space before and after the <code>=</code>/<code>+=</code>/<code>-=</code>, etc, for variable assignment or other operators. <strong>Yes</strong>: <code>i += 1</code> <strong>NO</strong>: <code>i+=1</code>.</li>\n<li><strong>Constant Variable Naming</strong>: Any variables that are constants in your program should be UPPERCASE.</li>\n<li><strong>Split code into methods</strong>: You have a lot of code that can be grouped into methods/classes. I don't have the time to do it for you, so I'll leave it up to you :).</li>\n<li><strong>Boolean Comparison (game==True)</strong>: Having <code>while game==True:</code> is unnecessary. You can use the variable itself as the boolean expression. Instead, do <code>while game:</code>, which is easier to read and <a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">PEP-8 Compliant</a>.</li>\n<li><strong>Global Variables</strong>: <a href=\"http://wiki.c2.com/?GlobalVariablesAreBad\" rel=\"nofollow noreferrer\">Global Variables are Bad!</a> You'll have to implement this into your program without using globals on your own, again I don't have the time to rewrite everything.</li>\n<li><strong>Enumerate vs range(len(...))</strong>: Multiple times you have <code>for i in range(len(...)):</code>. You should use <code>for index, value in enumerate(...)</code> instead. <a href=\"https://stackoverflow.com/a/24150815/8968906\">This StackOverflow answer</a> goes into detail about why you should make this change.</li>\n<li><strong>Use _ for unused loop variables</strong>: When you use <code>enumerate</code>, and don't need the value but only the index, use <code>for index, _ in enumerate(...)</code>. The <code>_</code> makes it clear that that variable should be ignored, and isn't useful.</li>\n<li><strong>Parameter '=' Spacing</strong>: When inserting variables like <code>parameter_name=variable</code>, there shouldn't be a space. Same when you have default parameters in method declarations.</li>\n<li><strong>Variable Naming snake_case</strong>: Variables should be <code>snake_case</code>, not <code>camelCase</code>.</li>\n</ul>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Docstring\nA description of your program goes here\n\"\"\"\n\nimport random\nimport time\nimport keyboard\n\nfrom graphics import *\n\n# configurations\nWIDTH = 400\nGRID_HEIGHT = WIDTH\nHEIGHT = 470\nTIMER = False\nGAME = True\nSCORE = 0\nBONUS = 0\nX = 70\nY = 30\nRADIUS = 10\nLENGTH = RADIUS * 2\nPLAYER_LENGTH = 3\nPOISON_LENGTH = PLAYER_LENGTH\ni = 0\nk = 0\nPOINT_RADIUS = 5\nPOINTS = False\nCHERRY_POINTS = False\nKEY = \"Right\"\nCOUNTDOWN = 0\n\n# set coordinations\nC_X = 90\nC_Y = 30\nCOORD_X = [10]\nCOORD_Y = [10]\n\nwhile COORD_X[len(COORD_X) - 1] != (WIDTH - 10):\n C_X += 20\n COORD_X.append(C_X)\n\nwhile COORD_Y[len(COORD_Y) - 1] != 390:\n C_Y += 20\n COORD_Y.append(C_Y)\n\nRANDOM_X = random.choice(COORD_X)\nRANDOM_Y = random.choice(COORD_Y)\nCHERRY_RANDOM_X = random.choice(COORD_X)\nCHERRY_RANDOM_Y = random.choice(COORD_Y)\nPOISON_RANDOM_X = random.choice(COORD_X)\nPOISON_RANDOM_Y = random.choice(COORD_Y)\n\n#window setup\nWINDOW = GraphWin(\"SNAKE\", WIDTH, HEIGHT, autoflush=False)\nWINDOW.setBackground(color_rgb(15, 15, 15))\n\n# grid\nLINE_X = 20\nwhile LINE_X &lt; WIDTH:\n GRID_X = Line(Point(LINE_X, 0), Point(LINE_X, GRID_HEIGHT))\n GRID_X.setOutline(color_rgb(25, 25, 25))\n GRID_X.draw(WINDOW)\n LINE_X += 20\nLINE_Y = 20\nwhile LINE_Y &lt;= GRID_HEIGHT:\n GRID_X = Line(Point(0, LINE_Y), Point(WIDTH, LINE_Y))\n GRID_X.setOutline(color_rgb(25, 25, 25))\n GRID_X.draw(WINDOW)\n LINE_Y += 20\n\n# snake banner\nUI = Rectangle(Point(0, 400), Point(WIDTH, HEIGHT))\nUI.setFill(color_rgb(102, 51, 0))\nUI.setOutline(color_rgb(102, 51, 0))\nUI.draw(WINDOW)\nSNAKE_TITLE = Text(Point(WIDTH / 2, 420), \"SNAKE\")\nSNAKE_TITLE.setTextColor(\"green\")\nSNAKE_TITLE.setSize(20)\nSNAKE_TITLE.draw(WINDOW)\nSCORE_TITLE = Text(Point(320, 424), \"SCORE\")\nSCORE_TITLE.setTextColor(\"white\")\nSCORE_TITLE.setSize(10)\nSCORE_TITLE.draw(WINDOW)\nSCORE_UI = Text(Point(320, 435), SCORE)\nSCORE_UI.setTextColor(\"white\")\nSCORE_UI.setSize(10)\nSCORE_UI.draw(WINDOW)\n\n# make player\nPLAYER = {}\nPLAYER[0] = Rectangle(Point(X - 20 - RADIUS, Y - RADIUS), Point(X - 20 + RADIUS, Y + RADIUS))\nPLAYER[1] = Rectangle(Point(X - 40 - RADIUS, Y - RADIUS), Point(X - 40 + RADIUS, Y + RADIUS))\nPLAYER[2] = Rectangle(Point(X - 60 - RADIUS, Y - RADIUS), Point(X - 60 + RADIUS, Y + RADIUS))\n\n# make poison\nPOISON = {}\n\ndef main(): \n\n global TIMER, SCORE_UI, SCORE, BONUS, PLAYER_LENGTH, POISON_LENGTH, X, Y, POINTS, CHERRY_POINTS, RANDOM_X, RANDOM_Y, CHERRY_RANDOM_X, CHERRY_RANDOM_Y, POISON_RANDOM_X, POISON_RANDOM_Y, KEY, COUNTDOWN, k, GAME\n\n while GAME:\n # score update\n SCORE_UI.undraw()\n SCORE_UI = Text(Point(320, 435), SCORE)\n SCORE_UI.setTextColor(\"white\")\n SCORE_UI.setSize(10)\n SCORE_UI.draw(WINDOW)\n\n # generating new body blocks\n if len(PLAYER) &lt; PLAYER_LENGTH:\n i += 1\n PLAYER[i] = PLAYER[i - 1].clone()\n\n # body following player\n PLAYER[0].undraw()\n for i in range(1, len(PLAYER)):\n PLAYER[len(PLAYER) - i].undraw()\n PLAYER[len(PLAYER) - i] = PLAYER[len(PLAYER) - i - 1].clone()\n PLAYER[len(PLAYER) - i].draw(WINDOW)\n\n # update player's head coordinate\n PLAYER[0] = Rectangle(Point(X - RADIUS, Y - RADIUS), Point(X + RADIUS, Y + RADIUS))\n PLAYER[0].setFill(\"green\")\n PLAYER[0].setWidth(2)\n PLAYER[0].draw(WINDOW)\n\n # player movement\n if keyboard.is_pressed(\"Up\") and KEY != \"Down\":\n KEY = \"Up\"\n elif keyboard.is_pressed(\"Left\") and KEY != \"Right\":\n KEY = \"Left\"\n elif keyboard.is_pressed(\"Down\") and KEY != \"Up\":\n KEY = \"Down\"\n elif keyboard.is_pressed(\"Right\") and KEY != \"Left\":\n KEY = \"Right\"\n if KEY == \"Up\":\n Y -= LENGTH\n elif KEY == \"Left\":\n X -= LENGTH\n elif KEY == \"Down\":\n Y += LENGTH\n elif KEY == \"Right\":\n X += LENGTH\n\n # point\n if not points: # generates new point when eaten\n point = Rectangle(Point(RANDOM_X - POINT_RADIUS, RANDOM_Y - POINT_RADIUS), Point(RANDOM_X + POINT_RADIUS, RANDOM_Y + POINT_RADIUS))\n point.setFill(\"white\")\n point.setWidth(2)\n point.draw(WINDOW)\n points = True\n if PLAYER[0].getCenter().getX() == point.getCenter().getX() and PLAYER[0].getCenter().getY() == point.getCenter().getY(): # when player eats the point\n point.undraw()\n PLAYER_LENGTH += 1\n POISON_LENGTH += 1\n SCORE += 200 + BONUS\n RANDOM_X = random.choice(COORD_X)\n RANDOM_Y = random.choice(COORD_Y)\n for i, _ in enumerate(PLAYER):\n if (point.getCenter().getX() == PLAYER[i].getCenter().getX() and point.getCenter().getY() == PLAYER[i].getCenter().getY()) or (CHERRY_POINTS and cherry_point.getCenter().getX() == point.getCenter().getX() and cherry_point.getCenter().getY() == point.getCenter().getY()): # regenerate x and y coordinate if they share the same coordinate as player and cherry\n RANDOM_X = random.choice(COORD_X)\n RANDOM_Y = random.choice(COORD_Y)\n for i, _ in enumerate(POISON): # regenerate x and y coordinate if point shares the same coordinate to other array of poisons\n if point.getCenter().getX() == POISON[i].getCenter().getX() and point.getCenter().getY() == POISON[i].getCenter().getY():\n CHERRY_RANDOM_X = random.choice(COORD_X)\n CHERRY_RANDOM_Y = random.choice(COORD_Y)\n points = False\n\n # cherry\n if COUNTDOWN == 150:\n COUNTDOWN = 0\n if not CHERRY_POINTS: # generates new cherry from countdown\n cherry_point = Rectangle(Point(CHERRY_RANDOM_X - POINT_RADIUS, CHERRY_RANDOM_Y - POINT_RADIUS), Point(CHERRY_RANDOM_X + POINT_RADIUS, CHERRY_RANDOM_Y + POINT_RADIUS))\n cherry_point.setFill(color_rgb(213, 0, 50))\n cherry_point.setWidth(2)\n cherry_point.draw(WINDOW)\n CHERRY_POINTS = True\n if CHERRY_POINTS:\n for i in range(2, 6): # cherry blinks between countdown 40 to 100\n if COUNTDOWN == 20 * i:\n cherry_point.undraw()\n elif COUNTDOWN == 10 + (20 * i):\n cherry_point.draw(WINDOW)\n if COUNTDOWN &gt;= 100: # when countdown becomes 100, remove cherry and reset count down\n CHERRY_POINTS = False\n COUNTDOWN = 0\n CHERRY_RANDOM_X = random.choice(COORD_X)\n CHERRY_RANDOM_Y = random.choice(COORD_Y)\n if CHERRY_POINTS and PLAYER[0].getCenter().getX() == cherry_point.getCenter().getX() and PLAYER[0].getCenter().getY() == cherry_point.getCenter().getY(): # when player eats the cherry\n cherry_point.undraw()\n SCORE += 500\n CHERRY_RANDOM_X = random.choice(COORD_X)\n CHERRY_RANDOM_Y = random.choice(COORD_Y)\n for i, _ in enumerate(PLAYER):\n if (cherry_point.getCenter().getX() == PLAYER[i].getCenter().getX() and cherry_point.getCenter().getY() == PLAYER[i].getCenter().getY()) or (cherry_point.getCenter().getX() == point.getCenter().getX() and cherry_point.getCenter().getY() == point.getCenter().getY()): # regenerate x and y coordinate if they share the same coordinate as player and point\n CHERRY_RANDOM_X = random.choice(COORD_X)\n CHERRY_RANDOM_Y = random.choice(COORD_Y)\n for i, _ in enumerate(POISON): # regenerate x and y coordinate if cherry shares the same coordinate to other array of poisons\n if cherry_point.getCenter().getX() == POISON[i].getCenter().getX() and cherry_point.getCenter().getY() == POISON[i].getCenter().getY():\n CHERRY_RANDOM_X = random.choice(COORD_X)\n CHERRY_RANDOM_Y = random.choice(COORD_Y)\n CHERRY_POINTS = False\n\n # poison\n if POISON_LENGTH % 5 == 0: # generates a poison block each time the player size reaches the multiple of 5\n POISON[k] = Rectangle(Point(POISON_RANDOM_X - POINT_RADIUS, POISON_RANDOM_Y - POINT_RADIUS), Point(POISON_RANDOM_X + POINT_RADIUS, POISON_RANDOM_Y + POINT_RADIUS))\n POISON[k].setFill(\"green\")\n POISON[k].setWidth(2)\n POISON[k].draw(WINDOW)\n POISON_RANDOM_X = random.choice(COORD_X)\n POISON_RANDOM_Y = random.choice(COORD_Y)\n for i, _ in enumerate(PLAYER):\n if POISON[k].getCenter().getX() == PLAYER[i].getCenter().getX() and POISON[k].getCenter().getY() == PLAYER[i].getCenter().getY() or (POISON[k].getCenter().getX() == point.getCenter().getX() and POISON[k].getCenter().getY() == point.getCenter().getY()) or (CHERRY_POINTS and POISON[k].getCenter().getX() == cherry_point.getCenter().getX() and POISON[k].getCenter().getY() == cherry_point.getCenter().getY()): # regenerate x and y coordinate if they share the same coordinate as player and point and cherry\n POISON_RANDOM_X = random.choice(COORD_X)\n POISON_RANDOM_Y = random.choice(COORD_Y)\n for i, _ in enumerate(POISON):\n if POISON[k].getCenter().getX() == POISON[i].getCenter().getX() and POISON[k].getCenter().getY() == POISON[i].getCenter().getY(): # regenerate x and y coordinate if new poison shares the same coordinate to other array of poisons\n POISON_RANDOM_X = random.choice(COORD_X)\n POISON_RANDOM_Y = random.choice(COORD_Y)\n BONUS += 50\n k += 1\n POISON_LENGTH += 1\n\n # game over requirements\n for i, _ in enumerate(POISON): # if player touches poison\n if PLAYER[0].getCenter().getX() == POISON[i].getCenter().getX() and PLAYER[0].getCenter().getY() == POISON[i].getCenter().getY():\n GAME = False\n for i in range(2, len(PLAYER)): # if player touches its own body or reach out of window\n if PLAYER[0].getCenter().getX() == PLAYER[i].getCenter().getX() and PLAYER[0].getCenter().getY() == PLAYER[i].getCenter().getY() or X &lt; 0 or X &gt; WIDTH or Y &lt; 0 or Y &gt; GRID_HEIGHT:\n GAME = False\n\n # FPS\n update(10)\n COUNTDOWN += 1\n\n\n # GAME OVER\n game_over = Text(Point(WIDTH / 2, 200), \"GAME OVER\")\n game_over.setTextColor(\"red\")\n game_over.setSize(30)\n game_over.draw(WINDOW)\n update()\n time.sleep(2)\n WINDOW.close()\n\nmain()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T23:39:17.977", "Id": "226351", "ParentId": "226180", "Score": "1" } }, { "body": "<h3><code>random.randrange()</code></h3>\n\n<p>It looks like these are just used as an argument to <code>random.choice()</code> for picking random coordinates. <code>random.randrange(start, stop, step)</code> would work. This also might be a good place to create a function that returns a random coordinate.</p>\n\n<pre><code>X_START = 10\nX_STEP = 90\nX_LIMIT = width - 10\n\nY_START = 10\nY_STEP = 30\nY_LIMIT = 390\n\ndef random_coordinate():\n \"\"\"return a random coordinate on the game grid.\"\"\"\n\n x = random.rangrange(X_START, X_LIMIT, X_STEP)\n y = random.rangrange(Y_START, Y_LIMIT, Y_STEP)\n\n return x, y\n</code></pre>\n\n<p>Then when a random coordinate is needed in the program, call the function:</p>\n\n<pre><code>point_xy = random_coordinate()\ncherry_xy = random_coordinate()\npoison_xy = random_coordinate()\n</code></pre>\n\n<h3>using <code>range()</code> to count down</h3>\n\n<p>Instead of using:</p>\n\n<pre><code>for i in range(1,len(player)):\n player[len(player)-i].undraw()\n ...\n</code></pre>\n\n<p>use:</p>\n\n<pre><code>for i in range(len(player)-1, 0, -1):\n player[i].undraw()\n ... \n</code></pre>\n\n<h3>functions</h3>\n\n<p>On stack overflow, they recommended using functions, because they can make your code easier to read, understand, debug, etc. The general rule of thumb (or guideline) it a unit of code should fit on one screen. That way it can be seen all at once without needing to scroll up and down. Your code has several comments that say what the next part of the code does. That may be a good hint that that chunk of code could be a separate function. ( comments starting with # &lt;- are explanations for you, I wouldn't normally put them in )</p>\n\n<pre><code>LINEX_START = 20\nLINEX_STEP = 20\nLINEY_START = 20\nLINEY_STEP = 20\n\n\ndef main_window():\n win = GraphWin(\"SNAKE\", width, height, autoflush = False)\n win.setBackground(color_rgb(15,15,15))\n\n return win # &lt;- other functions will need win, so return it\n\n\ndef draw_grid(win): # &lt;- need 'win' to draw the lines so it gets passed in\n\n for lineX in range(LINEX_START, WIDTH, LINEX_STEP)\n gridX = Line(Point(lineX,0),Point(lineX, GRID_HEIGHT))\n gridX.setOutline(color_rgb(25,25,25))\n gridX.draw(win)\n\n for lineY &lt;= GRIDHEIGHT:\n gridY = Line(Point(0,lineY),Point(WIDTH, lineY))\n gridY.setOutline(color_rgb(25,25,25))\n gridY.draw(win)\n\ndef draw_banner(win):\n UI = Rectangle(Point(0,400),Point(width,height))\n UI.setFill(color_rgb(102,51,0))\n UI.setOutline(color_rgb(102,51,0))\n UI.draw(win)\n\n snakeTitle = Text(Point(width/2,420),\"SNAKE\")\n snakeTitle.setTextColor(\"green\")\n snakeTitle.setSize(20)\n snakeTitle.draw(win)\n\n scoreTitle = Text(Point(320,424),\"SCORE\")\n scoreTitle.setTextColor(\"white\")\n scoreTitle.setSize(10)\n scoreTitle.draw(win)\n\ndef init_score(win):\n scoreUI = Text(Point(320,435),score)\n scoreUI.setTextColor(\"white\")\n scoreUI.setSize(10)\n scoreUI.draw(win)\n\n return scoreUI\n\ndef make_player()\n player = [\n Rectangle(Point(x-20-radius,y-radius), Point(x-20+radius, y+radius)),\n Rectangle(Point(x-40-radius,y-radius), Point(x-40+radius, y+radius)),\n Rectangle(Point(x-60-radius,y-radius), Point(x-60+radius, y+radius)),\n ]\n\n return player\n</code></pre>\n\n<p>The same applies to <code>main()</code>. Chunks of related code can be put into their own function. This isn't tested, and doesn't include everything, but I hope it gives you some ideas.</p>\n\n<pre><code>def update_score(score_UI, score):\n scoreUI.undraw()\n scoreUI = Text(Point(320,435),score)\n scoreUI.setTextColor(\"white\")\n scoreUI.setSize(10)\n scoreUI.draw(win)\n\n\ndef update_player(player, win):\n \"\"\"\n Grows the length of the player's body by 1 square and moves the\n snake forward one space. All the trailing parts of the body follow\n the part ahead of them.\n \"\"\"\n\n # generating new body blocks\n if len(player) &lt; MAXPLAYERLENGTH:\n player.append(player[-1].clone())\n\n # body following player\n player[0].undraw()\n for i in range(len(player)-1, 0, -1):\n player[i].undraw()\n player[i] = player[i-1].clone()\n player[i].draw(win)\n\n # update player's head coordinate\n player[0] = Rectangle(Point(x-radius,y-radius), Point(x+radius,y+radius))\n player[0].setFill(\"green\")\n player[0].setWidth(2)\n player[0].draw(win)\n\n\ndef main():\n global timer\n score = 0\n bonus = 0\n ...\n\n point = random_coordinate()\n cherry = random_coordinate()\n poison = random_coordinate()\n\n win = main_window() # &lt;- save return value\n make_grid(win) # &lt;- to use it here\n show_banner(win) # &lt;- and here\n\n player = make_player()\n score_UI = init_score()\n\n game = True\n while game:\n update_score(score_UI, score)\n\n update_player(player)\n move_player(player)\n\n handle_points(points, player)\n handle_cherries(cherries, player)\n handle_poison(poison, player)\n\netcetera\n</code></pre>\n\n<p>good luck.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T04:04:56.620", "Id": "226361", "ParentId": "226180", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T14:49:35.013", "Id": "226180", "Score": "3", "Tags": [ "python", "beginner", "graphics", "snake-game" ], "Title": "Snake game using graphics.py" }
226180
<p>In an effort to explore how the default calendar app works and to experiment with container view controllers, I created the following mock app. See this <a href="https://stackoverflow.com/questions/57041469/iphone-calendar-navigation-controller">post</a> for more info about my motivation for this app. This app only explores basic calendar navigation and orientation changes.</p> <p>I've chosen a design that uses a <code>UINavigationController</code> in which a container view controller is embedded as the main view in the root view controller. This embed view controller would be the actual calendar for the app. The plan is to use JTAppleCalendar to implement the calendar functionality. Because it seems I only need one calendar controller and I can toggle between different calendar layouts (day view, 3 day view, 5 day view, month view), the main role of the navigation controller is to toggle between these different layouts. I've also added a right bar button and a tool bar that would push new VCs like a standard navigation controller.</p> <p>With this app, I am most concerned about the left bar button item and the title view's segmented control and how both work in portrait and landscape and how it controls the calendar layout.</p> <p>Like the iOS Calendar app, the left bar button item can either be a pseudo 'back' button or a label. When the orientation changes to landscape, a segmented control is added to the title view of the nav bar. In landscape, the left bar button item will always be a label as the layout is controlled by the segmented control. I say 'pseudo because the back button and the segmented control do not actually push/pop calendar view controllers. It only toggles the calendar layout.</p> <p>In portrait, only day view and month view are the layouts available and the segmented control is hidden. In month view, if the user selects a 'day cell' (not implemented), the calendar layout is changed to the day layout. In day layout and in portrait, the left bar button item changes to a back button. Tapping the back button, the layout is toggled back to month view and the left bar button item is then changed to a label.</p> <p>In landscape, layout control is passed to the segmented control.</p> <p>For this review, I am looking for feedback about my overall strategy and how it is currently implemented. I'm also concerned that I'm mis-using UINavigationController and that the container view controller, the calendar, could become overly complicated. Also, am I properly using enums and protocols here?</p> <p>As a side note, for the 'add' view controller, I'm using 'Show Detail (e.g. Replace)' segue that presents the VC modally. In that view, I've added a back button that dismisses the view. Is this standard if I want the 'add' view to be full screen with the nav bar hidden?</p> <p><a href="https://i.stack.imgur.com/H4FUQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H4FUQ.png" alt="storyboard"></a> <a href="https://i.stack.imgur.com/eTmN8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eTmN8.png" alt="month view portrait"></a> <a href="https://i.stack.imgur.com/4rUYl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4rUYl.png" alt="month view landscape"></a> <a href="https://i.stack.imgur.com/GPiBv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GPiBv.png" alt="day view portrait"></a> <a href="https://i.stack.imgur.com/KqUSV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KqUSV.png" alt="day view landscape"></a> <a href="https://i.stack.imgur.com/1yX94.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1yX94.png" alt="5 day view landscape"></a></p> <p>ViewController.swift</p> <pre><code>// Root view controller import UIKit enum CalendarType: CaseIterable { case day, threeDay, fiveDay, month } protocol CalendarLayoutDelegate { func layoutCalendar(layout: CalendarType) } class ViewController: UIViewController { // When set, the class the must implement the CalendarLayoutDelegate protocol var calendarLayoutDelegate: CalendarLayoutDelegate? // Reference needed to set CalendarViewController instance to the CalendarLayoutDelegate and, // to be able to call the protocal method when currentCalendarLayout changes. var calendarViewController: CalendarViewController? // Navbar components @IBOutlet var leftBackButton: UIButton! var leftTitleLabel = UILabel() @IBOutlet weak var segmentedControl: UISegmentedControl! var currentCalendarLayout: CalendarType? { didSet { updateLeftBarButtonItem() calendarViewController?.layoutCalendar(layout: currentCalendarLayout!) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "CalendarViewSegue" { if let calendarVC = segue.destination as? CalendarViewController { calendarViewController = calendarVC calendarViewController!.dateDelegate = self calendarLayoutDelegate = calendarViewController } } if segue.identifier == "AddSegue" { print("Prepare segue AddVC") } } override func viewDidLoad() { super.viewDidLoad() leftTitleLabel.textColor = UIColor.black currentCalendarLayout = .month updateLeftBarButtonItem() layoutNavBar() } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { updateLeftBarButtonItem() layoutNavBar() } func layoutNavBar() { switch UIDevice.current.orientation { case .landscapeLeft, .landscapeRight: segmentedControl.isHidden = false // Set selected segment, either gonna be .day or .month if transitioning from portrait segmentedControl.selectedSegmentIndex = CalendarType.allCases.firstIndex(of: currentCalendarLayout!)! case .portrait: segmentedControl.isHidden = true // In portrait, only .month and .day are allowed. if currentCalendarLayout != .month { currentCalendarLayout = .day } default: break } } @IBAction func changeCalendarLayout(_ sender: Any) { switch segmentedControl.selectedSegmentIndex { case 0: currentCalendarLayout = .day case 1: currentCalendarLayout = .threeDay case 2: currentCalendarLayout = .fiveDay case 3: currentCalendarLayout = .month default: break } } @IBAction func backButtonMonthTapped(_ sender: Any) { currentCalendarLayout = .month } func updateLeftBarButtonItem() { // if portrait and not .month show back button if UIDevice.current.orientation == .portrait &amp;&amp; currentCalendarLayout != .month { self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftBackButton) } else { self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: leftTitleLabel) } } } extension ViewController: DateDelegate { // TODO: Update the UI with the current date selected. func setDate(date: Date) { let formatter = DateFormatter() formatter.dateFormat = "MMMM yyyy" let monthYearString = formatter.string(from: date) leftTitleLabel.text = monthYearString // If back button, just show month and not the year leftBackButton.setTitle(monthYearString.components(separatedBy: " ").first, for: .normal) } } </code></pre> <p>CalendarViewController.swift</p> <pre><code>import UIKit protocol DateDelegate { func setDate(date: Date) } class CalendarViewController: UIViewController { // When set, the class the must implement the DateDelegate protocol var dateDelegate: DateDelegate? @IBOutlet weak var tempLayoutLabel: UILabel! var tempText = "" override func viewDidLoad() { super.viewDidLoad() self.dateDelegate?.setDate(date: Date()) tempLayoutLabel.text = tempText } } extension CalendarViewController: CalendarLayoutDelegate { func layoutCalendar(layout: CalendarType) { tempText = "\(String(describing: layout)) Calendar" if tempLayoutLabel != nil { tempLayoutLabel.text = tempText } } } </code></pre> <p>AddViewController.swift</p> <pre><code>import UIKit class AddViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func dismissAddViewController(_ sender: Any) { self.dismiss(animated: true, completion: nil) } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T15:21:17.330", "Id": "226184", "Score": "1", "Tags": [ "swift", "ios" ], "Title": "iOS Calendar Navigation and Layout" }
226184
<p>Following the book "Structure and interpretation of computer programs" I have tried to implement a functional solution to the problem of N-queens (implemented by the function <code>nQueens</code>). However, I am not satisfied by the reliance on for loops and the general readability of the code. Could I get your opinion the code?</p> <pre><code>import functools as fn def safe(positions, k): """ Given a list of positions, returns if the queen on the k column is safe. """ enumeratedPos = tuple(enumerate(positions)); menacesK = fn.partial(menaces, enumeratedPos[k]); return not any(map(menacesK, filter(lambda pair: pair[0] != k, enumeratedPos))); def addNewColumn(positions, n): """ Given an array of k-length positions maps each position to n new k+1-length positions by appending numbers from 0 to n-1 Example: ((),) -&gt; ((0), (2) ... (n-1)) ((a),(b)) -&gt; ((a, 0), (a,2) ... (a,n-1), (b,0) ... (b,n-1)) """ for position in positions: for i in range(0, n): yield position + (i,); def menaces(pair1, pair2): colK, rowK = pair1; col, row = pair2; return abs(rowK - row) == abs(colK - col) or rowK == row; def nQueens(boardSize): """ Given a dimension boardSize, returns a filter with all the solutions to n-queens problem where n is boardSize""" def recur(i): if (i == 0): return ((),); safeK = lambda x: safe(x, i-1); return filter(safeK, addNewColumn(recur(i-1), boardSize)); return recur(boardSize); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T02:45:26.563", "Id": "439516", "Score": "0", "body": "On the part about for loops, they're basically in every Python program. It's bad to have too many, but don't be shy to show them off." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T06:59:56.657", "Id": "439538", "Score": "0", "body": "shouldn't `menaces` also check whether the queens are in the same column?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T12:31:25.953", "Id": "439607", "Score": "0", "body": "@MaartenFabré Columns are generated by enumerate, so they are necessarily different" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T02:17:42.007", "Id": "439696", "Score": "0", "body": "I have no idea how this code works, but it works so :P. I didn't add any optimizations or such as I was slightly scared it was going to `break` '~'" } ]
[ { "body": "<p>Looks like some pretty spicy (nicely formatted) code :)</p>\n\n<p>I'll explain my steps to make it look better and show you the end result. You can follow along and change them while they pop up.</p>\n\n<ol>\n<li><p>Remove the semicolons :P This is Python, not Javascript or C++ or (insert another language). Though they are optional and are perfectly fine to put in, they can cause clutter and reduce readability.</p></li>\n<li><p>All functions and variables should be <code>lower_case_with_underscores</code>, classes as <code>UpperCase</code>, and constants as <code>UPPER_CASE_WITH_UNDERSCORES</code>. We'll replace them with the correct convention.</p></li>\n<li><p>Replace <code>map</code> and <code>filter</code> with generator expressions. They may be a bit slower, but it'll be more readable as it resembles normal Python syntax such as the <code>for</code> loop and the <code>if</code> statement.</p></li>\n<li><p>That recursive function at the bottom can be changed so that it doesn't need that <code>lambda</code>. It can make it look nicer without the hidden extra arguments.</p></li>\n<li><p>The top function looks pretty complicated... Here's how to change it so that it doesn't need any variables. The first argument to <code>menaces</code> will always be the same, so it can be typed out manually. It's the <code>k</code>th item of <code>enumerate(positions)</code>, so the argument is <code>(k, positions[k])</code>. Note: we can remove the <code>import functools as fn</code> line.</p></li>\n<li><p>The second function is a generator function, meaning it returns an iterator. This one is just combining results from two <code>for</code> loops. Nested <code>for</code> loops are discouraged, so let's replace it with <code>itertools.product(positions, range(n))</code>. We'll have to import itertools too. Note: <code>range(0, n)</code> is the same as <code>range(n)</code>.</p></li>\n<li><p>I've changed the expression of <code>position + (i,)</code> to <code>(*position, i)</code>. I'm not sure which looks better, but personally the second one resembles the tuple that it yields better than the first.</p></li>\n<li><p>The third function could do with a little makeover. The new variables aren't really needed. I've replaced them with <code>col_diff</code> and <code>row_diff</code> which store <code>abs(pair1[n] - pair2[n])</code> where <code>n</code> is <code>1</code> for the rows and <code>0</code> for the columns. I've also made it explicitly return <code>True</code> or <code>False</code> and it looks better :)</p></li>\n<li><p>The doc strings also have a convention (for some reason). Single line doc strings can have the triple quotes (<code>\"\"\"</code>) at the start and end of the line, but multiline doc strings have them on their own lines. Note: I edited the example in <code>add_new_column</code> to look like an interactive session that shows how the function works.</p></li>\n</ol>\n\n<p>Here is the final result:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\n\n\ndef safe(positions, k):\n \"\"\"Given a list of positions, return True if the queen on the `k` column is safe.\"\"\"\n return not any(\n menaces((k, positions[k]), pair)\n for pair in enumerate(positions)\n if pair[0] != k\n )\n\n\ndef add_new_column(positions, n):\n \"\"\"\n Given an array of k-length `positions`, map each position to `n` new\n k+1-length positions by appending numbers from 0 to `n` - 1.\n\n &gt;&gt;&gt; list(add_new_column(((),), 3))\n [(0,), (1,), (2,)]\n &gt;&gt;&gt; list(add_new_column(((1,), (2,)), 3))\n [(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]\n \"\"\"\n for position, i in itertools.product(positions, range(n)):\n yield (*position, i)\n\n\ndef menaces(pair1, pair2):\n row_diff = abs(pair1[1] - pair2[1])\n col_diff = abs(pair1[0] - pair2[0])\n if row_diff == col_diff:\n return True\n elif pair1[1] == pair2[1]:\n return True\n else:\n return False\n\n\ndef n_queens(board_size):\n \"\"\"\n Given a dimension `board_size`, return an iterator with all the solutions\n to n-queens problem where n is `board_size`.\n \"\"\"\n def _recur(i):\n if not i:\n return ((),)\n else:\n return (\n row\n for row in add_new_column(_recur(i - 1), board_size)\n if safe(row, i - 1)\n )\n return _recur(board_size)\n</code></pre>\n\n<p>An extra change I would make is to the <code>add_new_column</code> function. It receives the <code>positions</code> first which mean that it has to be in a tuple. By moving the <code>n</code> parameter to the front and using variable length parameters (<code>*positions</code>), the call can look less repetitive.</p>\n\n<p>Here's the new function signature: (You can change the other calls if you like)</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def add_new_column(n, *positions):\n \"\"\"\n Given an array of k-length `positions`, map each position to `n` new\n k+1-length positions by appending numbers from 0 to `n` - 1.\n\n &gt;&gt;&gt; list(add_new_column(3, ()))\n [(0,), (1,), (2,)]\n &gt;&gt;&gt; list(add_new_column(3, (1,), (2,)))\n [(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]\n \"\"\"\n # Here's the code\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T07:01:41.983", "Id": "439539", "Score": "1", "body": "you can save 1 level of indentation by removing the `else` in `_recur`. Due to the early `return` in the if-case, this is not needed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T02:14:33.853", "Id": "439695", "Score": "0", "body": "@MaartenFabré I could do that, but I chose not to as it would look weird with all the `return`s in a staircase shape. I added it to make it pop out that it was a choice between the `((),)` and the other thing. I have a little rule set thing: if the `if` leads to an exception being `raise`d, an `else` is not needed; if there are multiple `elif`s, keep the `else`; if there is an early `return` without a value, an else isn't needed. All other cases should have the `else`. +1 for the suggestion tho :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T02:43:09.663", "Id": "226226", "ParentId": "226189", "Score": "2" } } ]
{ "AcceptedAnswerId": "226226", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T16:10:40.957", "Id": "226189", "Score": "2", "Tags": [ "python", "python-3.x", "functional-programming", "chess", "n-queens" ], "Title": "Functional n-queens" }
226189
<p>I use prepared statements often even when I only need to execute the statement once (for security), so I implemented a function to abstract away all the function calls on the mysqli_stmt object, as well as <code>bind_param()</code>'s first argument since as far as my tests show it works identically even when int parameters are marked as strings.</p> <pre><code>&lt;?php $conn = new mysqli('localhost', 'name', 'password', 'db'); if ($conn-&gt;connect_error) die('Connection to database failed: ' . $conn-&gt;connect_error); function stmt($query, $params){ array_unshift($params, str_repeat('s', sizeof($params))); for($i = 1; $i &lt; sizeof($params); $i++){ $params[$i] = &amp;$params[$i]; } $stmt = $GLOBALS['conn']-&gt;stmt_init(); $stmt-&gt;prepare($query); $method = new ReflectionMethod('mysqli_stmt', 'bind_param'); $method-&gt;invokeArgs($stmt, $params); $stmt-&gt;execute(); if($stmt-&gt;error){ $result = ['error' =&gt; $stmt-&gt;error]; } else { $result = $stmt-&gt;get_result(); } $stmt-&gt;close(); return $result; } ?&gt; </code></pre> <h2>Usage example:</h2> <pre><code>&lt;?php $result = stmt('SELECT * FROM table_name WHERE id IN(?,?,?)', [1,2,3]); ?&gt; </code></pre>
[]
[ { "body": "<p>I tested your code and it does work, so far, so good. This type of code has been written many times, so by searching online you can find a lot of good examples.</p>\n\n<p>The main problem I have with your code is that it is rather difficult to understand. I can work it out, but it is not obvious. Starting with prepending the <code>$params</code> with something, then the very weird: <code>$params[$i] = &amp;$params[$i]</code> loop, followed by the usage of <code>ReflectionMethod</code> normally used for <code>reverse-engineering</code> code.</p>\n\n<p>I prefer more down to earth code for a simple function like this. Something like:</p>\n\n<pre><code>function executeQuery($mysqli, $query, $parameters)\n{\n $stmt = $mysqli-&gt;stmt_init();\n if ($stmt-&gt;prepare($query)) {\n $types = str_repeat(\"s\", count($parameters));\n if ($stmt-&gt;bind_param($types, ...$parameters)) {\n if ($stmt-&gt;execute()) {\n return $stmt-&gt;get_result();\n }\n }\n }\n return ['error' =&gt; $stmt-&gt;error];\n}\n</code></pre>\n\n<p>Short and sweet. Some notes:</p>\n\n<ul>\n<li>I try to use a function name that actually reflects what the function does.</li>\n<li>I supply the database connection as an argument, for more flexibility. You can use multiple database connections and they don't need to be in the global scope.</li>\n<li>I check whether the query could be properly prepared.</li>\n<li>My code differs quite a bit from your code when it comes to binding the parameters. As you can see this is quite straightforward. <a href=\"https://www.php.net/manual/en/functions.arguments.php#functions.variable-arg-list.new\" rel=\"noreferrer\">Using ... to access variable arguments</a> has been available since PHP 5.6 which came out in 2014.</li>\n<li>By directly returning the results when the execution was successful I know that an error must have occurred when the last line of the function is executed. This therefore also catches other problems.</li>\n</ul>\n\n<p>Personally I would not have expected to get a MySQLi result object out of this function. Because it will always have to be processed. Why not do this processing inside this function? Like this:</p>\n\n<pre><code>function executeQuery($database, $query, $parameters)\n{\n $stmt = $database-&gt;stmt_init();\n if ($stmt-&gt;prepare($query)) {\n $types = str_repeat(\"s\", count($parameters));\n if ($stmt-&gt;bind_param($types, ...$parameters)) {\n if ($stmt-&gt;execute()) {\n if ($result = $stmt-&gt;get_result()) {\n $rows = [];\n while ($row = $result-&gt;fetch_assoc()) {\n $rows[] = $row;\n }\n return $rows;\n }\n }\n }\n }\n return ['error' =&gt; $stmt-&gt;error];\n}\n</code></pre>\n\n<p>Now you simply get an array back. I agree that is not much different from returning a MySQLi result, but I am thinking ahead. Suppose you decide to change over from MySQLi to PDO in the future. You can easily recode the function above to work with PDO, but recoding the handling of MySQLi results everywhere in your code will be a lot harder. So I am using the function to abstract away from a particular database interface.</p>\n\n<p>Some people don't like the deep nesting of <code>if () {}</code> blocks. To prevent this you could instead write something, like the code below, for all these blocks:</p>\n\n<pre><code> if (!$stmt-&gt;prepare($query)) {\n return ['error' =&gt; $stmt-&gt;error];\n }\n</code></pre>\n\n<p>I have to repeat that there are lots of ways of doing this. The answer I gave is based on the code you presented. It is, for instance, not hard to find out the type of the parameters, and adjust the <code>$types</code> string accordingly. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T22:33:40.750", "Id": "439496", "Score": "0", "body": "Assuming it is available, I'd be generating the returned result set in a loopless manner. Something like: https://stackoverflow.com/a/51385583/2943403 This will reduce 5 lines to 1. (...and I don't bother with `init()`.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T03:24:45.657", "Id": "439517", "Score": "0", "body": "Returning an array in case of error is absolutely unacceptable. Trying to fetch the data from a DML query will cause an error. There is a fetch_all()." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T19:00:32.153", "Id": "226201", "ParentId": "226191", "Score": "5" } }, { "body": "<p>First of all, that's a very good idea to create such a function. It says you are a programmer in your heart. Sadly, but most PHP users never come to the idea of such an automation, writing thousands of repeated lines of code over and over again.</p>\n\n<p>What could be criticized about your code is already pretty much covered in the other answer. However, the solution offered there is still far from being optimal.</p>\n\n<p>First of all, the <strong>error reporting</strong> is absolutely <strong>flawed</strong> in both cases. Returning an array with error information instead of the actual query result is absolutely unacceptable. It will lead to numerous errors and confusions in your code. Errors must be <em>thrown</em>, not returned. For mysqli it's especially simple because it can throw exceptions by itself. Check out my article on <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"noreferrer\">PHP error reporting principles</a></p>\n\n<p>Next, returning the mysqli result may cause an error if you are running a DML query. So the only proper return value would be a mysqli statement. </p>\n\n<p>Using \"s\" for all data types is a very smart move, it will serve you 999 times out of 1000. However, adding a possibility to set the types explicitly is a good idea anyway.</p>\n\n<p>Taking all the above into consideration, I wrote such a function myself, a <a href=\"https://phpdelusions.net/mysqli/simple\" rel=\"noreferrer\">Mysqli helper function</a>:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function prepared_query($mysqli, $sql, $params, $types = \"\")\n{\n $types = $types ?: str_repeat(\"s\", count($params));\n $stmt = $mysqli-&gt;prepare($sql);\n $stmt-&gt;bind_param($types, ...$params);\n $stmt-&gt;execute();\n return $stmt;\n}\n</code></pre>\n\n<p>As you can see, it is not only much simpler but also much more flexible.\nNote the examples section in the article linked above. As you can see, I tested this function with many query types and return values.</p>\n\n<p>On a side note, <a href=\"https://phpdelusions.net/mysqli/mysqli_connect\" rel=\"noreferrer\">the <strong>proper</strong> mysqli connection</a> is a bit more complex than just a single line of code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T14:53:38.667", "Id": "439632", "Score": "0", "body": "Thanks, very useful articles! About the potential for error when returning result of DML queries: I think it would be better to return either the result or nothing, since you'd expect a result from statements such as `SELECT`, and in other cases you need nothing returned. You might want to get data such as number of affected rows, but it can be done with `$mysqli`. I'm not aware of other reasons to want `$stmt` besides getting the result." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T03:51:07.707", "Id": "226229", "ParentId": "226191", "Score": "5" } }, { "body": "<h2>My code after improvement based on the reviews</h2>\n\n<p>And another improvement: if no query parameters are passed, run a simple query instead of a prepared statement.</p>\n\n<p><strong>Note:</strong> one thing I didn't implement from the reviews is the idea of returning an array instead of the mysqli_result object - because of performance and memory considerations.</p>\n\n<pre><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\ntry {\n $conn = new mysqli('localhost', 'username', 'password', 'db');\n $conn-&gt;set_charset('utf8mb4');\n} catch (Exception $e) { // catch and re-throw to avoid exposing database credentials\n throw new Exception($e-&gt;getMessage(), $e-&gt;getCode());\n}\n\nfunction query($mysqli, $sql, $params = [], $types = '')\n{\n if(!$params){\n return $mysqli-&gt;query($sql);\n }\n $types = $types ?: str_repeat('s', count($params));\n $stmt = $mysqli-&gt;prepare($sql);\n $stmt-&gt;bind_param($types, ...$params);\n $stmt-&gt;execute();\n try{\n $result = $stmt-&gt;get_result();\n } catch (Exception $e) {\n $result = false;\n }\n $stmt-&gt;close();\n return $result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T12:41:27.907", "Id": "439726", "Score": "0", "body": "If all of your incoming `$param` values are appropriately typed, you can read their types, avoid passing in a `$types` argument, and apply the most appropriate type character for each param. Something like this: https://3v4l.org/alenU p.s. `close` is not necessary -- php is going to do this for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T13:58:20.300", "Id": "439731", "Score": "0", "body": "Numeric types are processed by MySQL just fine when passed as strings, but `b` for blobs is indeed useful and can be automated, I'll look into it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T14:02:47.473", "Id": "439734", "Score": "0", "body": "Just a suggestion if you wanted to reduce passed in arguments. Also, I'd probably go for `$params = []` instead of null for data type consistency." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:12:39.093", "Id": "439743", "Score": "0", "body": "After looking into the use case of blob type I concluded that it is currently not needed for my project (and unlikely to ever be needed) so I won't bother implementing it. It is only useful for big values (exceeding `max_allowed_packet`) that should be sent in multiple smaller packets via `mysqli_stmt::send_long_data()`. So right now I'm left wondering if I should just use `s` for everything and remove the option to set it to anything else for a lack of usefulness, or is it any good for optimization? (numeric types take less space, so it's slightly less bytes to send, but just slightly)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T03:41:51.213", "Id": "439843", "Score": "0", "body": "@mickmackusa it would be a very bad idea. least it any useful as in any case when a particular type is needed you can define explicitly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T03:42:59.600", "Id": "439844", "Score": "1", "body": "@potato there are few [edge cases](https://phpdelusions.net/pdo#methods)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T04:20:01.610", "Id": "439846", "Score": "0", "body": "I honestly haven't researched or tested my suggestion. The idea behind it is merely that the responsibility of setting the appropriate data type is not issued to the function as an extra parameter; rather the data that is being passed in must be appropriately typed in advance and the function just translates the type into the right character for the types declaration." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T15:43:06.543", "Id": "226270", "ParentId": "226191", "Score": "1" } } ]
{ "AcceptedAnswerId": "226201", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T16:19:57.230", "Id": "226191", "Score": "5", "Tags": [ "php", "mysqli" ], "Title": "php one-time prepared statement execution function" }
226191
<p>After solving <a href="https://www.hackerrank.com/challenges/crush/problem" rel="nofollow noreferrer">a problem</a>, I came to this conclusion. </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>let n = 10; let array = [ [1, 5, 3], [4, 8, 7], [6, 9, 1] ]; let answer = array.map((val) =&gt; new Float32Array(n).fill(val[2], val[0] - 1, val[1])); console.log(Math.max(...answer.reduce((r, a) =&gt; a.map((b, i) =&gt; (r[i] || 0) + b), [])))</code></pre> </div> </div> </p> <p>Okay, so what this does is it creates an array of <code>n</code> elements with the value of the third element from the index from the range of the first value to the second value.</p> <p>Indexes start from 1 here.</p> <p>Like for <code>[1, 5, 3]</code>, (n = 10), it creates an array of 10 elements with the value 3 from the index 1 to the index 5 and else everything is just blank or 0.</p> <p>Then for <code>[4, 8, 7]</code>, (n = 10), it creates an array of 10 elements with the value 7 from the index 4 to the index 8 and else, everything is just blank or 0.</p> <p>Then for <code>[6, 9, 1]</code>, (n = 10), it creates an array of 10 elements with the value 1 from the index 6 to the index 9 and else, everything is just blank or 0.</p> <p>Now we have to sum all the matching columns and return the maximum value, which I do by</p> <pre><code>Math.max(...answer.reduce((r, a) =&gt; a.map((b, i) =&gt; (r[i] || 0) + b), [])) </code></pre> <p>Everything works fine and the test cases work but the program is not at all efficent, with refrence to <a href="https://www.hackerrank.com/challenges/crush/problem" rel="nofollow noreferrer">this problem</a>, my code just timeouts. </p> <p>I think the problem is when I sum the values. That is what is taking the most memory. </p> <p>What can be an alternate method to sum the same index array values? Being it the most efficient</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T17:01:47.857", "Id": "439440", "Score": "0", "body": "Style Comment: You're missing variables, and as such it makes it harder to tell what your code does without reading your explanation." } ]
[ { "body": "<p>The problem is, that you create an array of length <code>n</code> for each operation (in the input array), and then sum them by calling <code>reduce</code> on the result and after that you finally find the maximum of that resulting array. But you only need one initial array to sum up in, and you can find the maximum in the same operation - here in a rather verbose form:</p>\n\n<pre><code>function arrayManipulation(n, arr) {\n var res = [];\n var max = 0;\n\n for (var i = 0; i &lt; arr.length; i++) {\n for (var j = 0; j &lt; n; j++) {\n if (i === 0) {\n res.push(j &gt;= arr[i][0] - 1 &amp;&amp; j &lt;= arr[i][1] - 1 ? arr[i][2] : 0);\n }\n else {\n res[j] += j &gt;= arr[i][0] &amp;&amp; j &lt;= arr[i][1] ? arr[i][2] : 0;\n }\n max = Math.max(max, res[j]);\n }\n }\n return max;\n}\n</code></pre>\n\n<p>which can be narrowed down to this more succinct form:</p>\n\n<pre><code>function arrayManipulation(n, arr) {\n var res = [];\n var max = Number.MIN_VALUE;\n\n for (var i = 0; i &lt; arr.length; i++) {\n for (var j = arr[i][0]; j &lt;= arr[i][1]; j++) {\n res[j] = (res[j] || 0) + arr[i][2];\n max = Math.max(max, res[j]);\n }\n }\n return max;\n}\n</code></pre>\n\n<p>Here is used, that it is only needed to loop through the intervals of the array that is actually manipulated by each operation in the input array. So for instance in the example operations, it is for the first operation only necessary to add <code>3</code> to the values in places from <code>1</code> to <code>5</code> inclusive. </p>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>Building on the idea from the comment by weegee a modification of my solution above could handle that:</p>\n\n<pre><code>function arrayManipulation(n, arr) {\n arr = arr.sort((a, b) =&gt; a[0] &lt; b[0] ? -1 : a[0] === b[0] ? 0 : 1);\n var max = Number.MIN_VALUE;\n\n for (var i = 0; i &lt; arr.length; i++) {\n var sum = arr[i][2];\n for (var j = i + 1; j &lt; arr.length; j++) {\n if (arr[j][0] &lt;= arr[i][1])\n sum += arr[j][2];\n else\n break;\n }\n max = Math.max(sum, max);\n }\n\n return max;\n}\n</code></pre>\n\n<p>First the operations are sorted according to their start position (first element in the sub array), and then the operations are iterated and summed up as long as there is an overlap from operation to operation. Finally the current sum is compared to the existing maximum sum in <code>max</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T16:51:26.753", "Id": "439645", "Score": "0", "body": "This is again getting timed out. I had an idea. We can do this without array. We can find the intersections for every array values and check the intersections. If they exist then we can just add the values" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T15:40:57.843", "Id": "226269", "ParentId": "226192", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T16:21:04.777", "Id": "226192", "Score": "4", "Tags": [ "javascript", "array" ], "Title": "Summing same index values in 2D arrays in javascript" }
226192
<blockquote> <p>Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. (<a href="https://leetcode.com/problems/max-area-of-island/" rel="nofollow noreferrer">LeetCode</a>)</p> </blockquote> <p>This is my code</p> <pre><code>int maxAreaOfIsland(vector&lt;vector&lt;int&gt;&gt;&amp; grid) { int max_area = 0; int rows = grid.size(); int columns = grid[0].size(); vector&lt;vector&lt;bool&gt;&gt; visited(rows, vector&lt;bool&gt;(columns,false)); for(int i=0 ; i &lt; rows ; ++i){ for(int j=0; j &lt; columns ; ++j){ max_area = max(max_area, area(i,j,grid,visited)); } } return max_area; } int area(int row, int col, vector&lt;vector&lt;int&gt;&gt;&amp; grid, vector&lt;vector&lt;bool&gt;&gt;&amp; visited){ if(row &lt; 0 || row &gt;= grid.size() || col &lt; 0 || col &gt;= grid[row].size() || visited[row][col]==true || grid[row][col] == 0) return 0; visited[row][col] = true; return (1 + area(row-1,col,grid,visited) + area(row,col-1,grid,visited) + area(row+1,col,grid,visited) + area(row,col+1,grid,visited)); } </code></pre> <p>It was accepted on LeetCode and worked for all test cases. As you can see, the readability of the code is not good, so I am looking for a Code Review:</p> <ol> <li><p>How can I improve readability in <code>if()</code> construct and <code>return</code> in <code>area</code> function?</p></li> <li><p>Is there a better way to initialize 2D Vector in C++? </p></li> <li><p>Is there a better way to maintain the <code>visited</code> array? I had to pass that array in every function call. If this data member is declared as as a static data member of the class then can its passing in every recursive call be avoided?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T21:17:08.400", "Id": "439950", "Score": "0", "body": "Can you not just store the island in a 1D array, and use [count](http://www.cplusplus.com/reference/algorithm/count/) to count the number of 1s?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T17:36:26.660", "Id": "226194", "Score": "2", "Tags": [ "c++", "programming-challenge", "recursion", "vectors" ], "Title": "Leetcode Finding Maximum Area of Island Solution" }
226194
<p>This is dijkstras shortest path algorithm implementation in c++ using priority_queue STL.</p> <p>Looking for two things: a) Correctness of algorithm itself and b) Any improvement suggestions. </p> <pre><code>/* 3 -----&gt; b -----------&gt;d 10/ -1-- ^ | 1 ^/ | / / | | ------// 1| x v 2|11| / /-1-- | \ | v / v V \-----&gt; c -----------&gt; e 1 8 */ class EdgeNode { public: char label; int weight; EdgeNode(char l = 0, int w = 0) : label(l), weight(w) {} }; using EdgeNodes = vector&lt;EdgeNode *&gt;; class Graph { public: unordered_map&lt;char, EdgeNodes *&gt; adj; void addNode(char node) { if(adj.find(node) == adj.end()) { adj[node] = new EdgeNodes(); } } void addEdge(char start, char end, int weight) { if(adj.find(start) != adj.end()) { for(auto node : *adj[start]) { if(node-&gt;label == end) { node-&gt;weight = weight; return; } } } else { adj[start] = new EdgeNodes(); } if(end) { adj[start]-&gt;push_back(new EdgeNode(end, weight)); } } void get_parent(unordered_map&lt;char, char&gt;&amp; parent, char c) { cout &lt;&lt; "Parent chain of \'" &lt;&lt; c &lt;&lt; "\' ="; while((parent.find(c) != parent.end()) &amp;&amp; parent[c]) { cout &lt;&lt; parent[c] &lt;&lt; ", "; c = parent[c]; } cout &lt;&lt; endl; } void get_distance(unordered_map&lt;char, int&gt;&amp; dist) { cout &lt;&lt; "distances =&gt; "; for(auto a : dist) { cout &lt;&lt; "(" &lt;&lt; a.first &lt;&lt; "=" &lt;&lt; a.second &lt;&lt; ") "; } cout &lt;&lt; endl; } void djikstras() { unordered_set&lt;char&gt; visited; unordered_map&lt;char, int&gt; dist; unordered_map&lt;char, char&gt; parent; using Pair = pair&lt;char, int&gt;; priority_queue&lt;Pair, vector&lt;Pair&gt;, greater&lt;Pair&gt;&gt; pq; char snode = 'x'; visited.insert(snode); dist[snode] = 0; parent[snode] = 0; pq.push(make_pair(snode, 0)); while(!pq.empty()) { Pair front = pq.top(); pq.pop(); for(EdgeNode *edge : *adj[front.first]) { if(visited.find(edge-&gt;label) == visited.end()) { dist[edge-&gt;label] = dist[front.first] + edge-&gt;weight; visited.insert(edge-&gt;label); parent[edge-&gt;label] = front.first; pq.push(make_pair(edge-&gt;label, dist[edge-&gt;label])); } else { /* //Parent comparison not needed in directed graph for djikstras //Its anyways useless because distance back to parent will always be larger if(parent[front.first] == edge-&gt;label) { cout &lt;&lt; "Parent " &lt;&lt; front.first &lt;&lt; " = " &lt;&lt; parent[front.first] &lt;&lt; endl; continue; }*/ if(dist[edge-&gt;label] &gt; (dist[front.first] + edge-&gt;weight)) { dist[edge-&gt;label] = dist[front.first] + edge-&gt;weight; parent[edge-&gt;label] = front.first; pq.push(make_pair(edge-&gt;label, dist[edge-&gt;label])); } } } } get_distance(dist); get_parent(parent, 'e'); } }; int main(void) { Graph g; g.addEdge('x', 'c', 1); g.addEdge('x', 'b', 10); g.addEdge('b', 'x', 1); g.addEdge('b', 'c', 11); g.addEdge('b', 'd', 3); g.addEdge('c', 'b', 2); g.addEdge('c', 'd', 1); g.addEdge('c', 'e', 8); g.addEdge('d', 'c', 1); g.addEdge('d', 'e', 1); g.addNode('e'); g.djikstras(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T19:51:57.760", "Id": "439467", "Score": "1", "body": "https://stackoverflow.com/a/3448361/14065" } ]
[ { "body": "<p>Ohhh. Don't do this:</p>\n\n<pre><code>using EdgeNodes = vector&lt;EdgeNode *&gt;;\nunordered_map&lt;char, EdgeNodes *&gt; adj;\n</code></pre>\n\n<p>Now you need to manage the memory of the <code>EdgeNodes</code>. Simply declare it as a value type:</p>\n\n<pre><code>using EdgeNodes = vector&lt;EdgeNode&gt;; // Remove the star\nunordered_map&lt;char, EdgeNodes&gt; adj; // Remove the star.\n</code></pre>\n\n<p>To make the rest of your code simpler I would define a way to compare the EdgeNodes.</p>\n\n<pre><code>class EdgeNode\n{\n public:\n char label;\n int weight;\n EdgeNode(char l = 0, int w = 0) : label(l), weight(w) {}\n\n // Compare a Node against a label\n bool operator==(char l) {return label == l;}\n};\n</code></pre>\n\n<p>This makes your add functions simpler:</p>\n\n<pre><code> void addNode(char node)\n {\n adj.insert({node, EdgeNodes{}});\n }\n void addEdge(char start, char end, int weight)\n {\n auto&amp; dest = adj[node].second;\n\n // See if there is already a link to the destination.\n // This uses the `operator==` we defined above to compare\n // each node against `end`.\n auto find = std::find(std::begin(dest), std::end(dest), end);\n\n if (find != std::end(dest)) {\n // If we already have it update the weight. \n find-&gt;weight = weight;\n }\n else {\n // otherwise add it to the end.\n dest.emplace_back(end, weight);\n }\n }\n</code></pre>\n\n<p>Don't be lazy:</p>\n\n<pre><code> Pair front = pq.top(); pq.pop();\n</code></pre>\n\n<p>Split it over two lines. Its easy to write new code. Its hard to read other people's code. Don't make it difficult for them.</p>\n\n<pre><code> Pair front = pq.top(); // Get the top item\n pq.pop(); // Pop it from the queue.\n</code></pre>\n\n<p>The dijkstras algorithm looks ok.</p>\n\n<p>Things to look at:</p>\n\n<ul>\n<li>I find it a bit dense to read and it took me a while to understand it but nothing technically wrong with it.</li>\n<li>I might have used a single map for <code>parent/distance</code> calculations rather than two distinct structures.</li>\n<li>Checking inclusion in the visited list is usually done on the node as it is popped of the <code>dq</code> not when pushing it onto the list. This may be a bug.</li>\n<li>Normall you pass <code>start</code> and <code>end</code> as parameters to <code>djikstras</code></li>\n</ul>\n\n<p>Let me re-try a refactor:</p>\n\n<pre><code>void djikstras(char snode, char end)\n{\n using ParentEdge = std::pair&lt;char, EdgeNode&gt;;\n auto comp = [](ParentEdge const&amp; l, ParentEdge const&amp; r){return l.second.weight &lt; r.second.weight;};\n\n unordered_map&lt;char, EdgeNode&gt; retrace; \n priority_queue&lt;ParentEdge, vector&lt;ParentEdge&gt;, comp&gt; pq; \n\n // special case the snode is its own parent.\n retrace[snode] = EdgeNode(snode, 0);\n pq.push(ParentEdge(snode, EdgeNode(snode, 0)));\n\n while(!pq.empty()) {\n // Get details of next node.\n ParentEdge front = pq.top();\n char&amp; parent = front.first;\n char&amp; current = front.second.label;\n int&amp; weight = front.second.weight;\n pq.pop();\n\n if (current === end) {\n // Did we find the destination.\n printRoute(retrace, end);\n return;\n }\n\n if (retrace.find(current) != retrace.end()) {\n // Already found cheapest route to here.\n continue;\n }\n\n // Found cheapest route to this point. Add info to the structures.\n retrace[current] = EdgeNode(parent, retrace[parent].weight + weight);\n\n // Add children to the frontier list\n for(EdgeNode edge : adj[current]) {\n pq.push(ParentEdge(current, edge));\n }\n } \n std::cout &lt;&lt; \"Failed to find route from start to finish\\n\"; \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T22:34:37.547", "Id": "439497", "Score": "0", "body": "Forgot why I did pointer thingy, but agree with you. About the splitting on two lines, I with we had pq.pop_and_assign() function.\nAny comments on dijkstra's algo itself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T00:09:47.777", "Id": "439506", "Score": "0", "body": "@PnotNP The algorithm I find to hard to read (way to dense). I provided a comment on the answer to a simpler implementation I wrote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T01:21:47.617", "Id": "439510", "Score": "0", "body": "@PnotNP Tried to refactor your djikstras. Have not compiled it so it may need some work." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T20:02:20.763", "Id": "226207", "ParentId": "226195", "Score": "2" } } ]
{ "AcceptedAnswerId": "226207", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T17:40:53.653", "Id": "226195", "Score": "1", "Tags": [ "c++", "algorithm", "object-oriented", "graph" ], "Title": "Dijkstra's implementation in c++ with STL priority_queue" }
226195
<p>I solved a problem where it was told to sort an array of numbers such that the even numbers are kept first and the odd numbers should follow. Moreover, the even numbers must be sorted in ascending order among them and the odd numbers as well. <strong>Only arrays can be used.</strong> My code is as follows , which works fine but it seems <strong>bit long</strong> to me. I wanted to know if there is anything I can do to shorten it and make it more readable.</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { int n,i,k,p,j,temp; scanf("%d",&amp;n); int arr[n],arr_even[n],arr_odd[n]; k=0,p=0; for(i=0;i&lt;n;i++){ scanf("%d",&amp;arr[i]); if(arr[i]%2==0) arr_even[k++]=arr[i]; else arr_odd[p++]=arr[i]; } for(i=0;i&lt;k;i++){ for(j=0;j&lt;=i;j++){ if(arr_even[j]&gt;arr_even[i]){ temp=arr_even[i],arr_even[i]=arr_even[j],arr_even[j]=temp; } } } for(i=0;i&lt;p;i++){ for(j=0;j&lt;=i;j++){ if(arr_odd[j]&gt;arr_odd[i]){ temp=arr_odd[i],arr_odd[i]=arr_odd[j],arr_odd[j]=temp; } } } p=0; for(i=0;i&lt;n;i++) { if(k) arr[i]=arr_even[i],k--; else arr[i]=arr_odd[p++]; } for(i=0;i&lt;n;i++) { printf("%d ",arr[i]); } return 0; } </code></pre> <h2>Input:</h2> <pre class="lang-none prettyprint-override"><code>10 0 5 1 2 3 4 6 12 10 9 </code></pre> <h2>Output:</h2> <pre class="lang-none prettyprint-override"><code>0 2 4 6 10 12 1 3 5 9 </code></pre>
[]
[ { "body": "<p>Firstly, we should separate the sorting from the reading of inputs and writing of outputs. We can create a function <code>sort_evens_first()</code> - that's the foundation of writing re-usable code. An advantage (even in this small program) is that a separable function can more easily be tested - no need for an external script to run many instances of the program with different inputs, making tests run much faster; also it makes it easier to distinguish bugs in the I/O from bugs in the algorithm</p>\n<p>Secondly, the Standard Library provides us with <code>qsort()</code> to save us having to re-implement sort every time (and it's usually more efficient than the bubble sort implemented here). We need to give it a comparator function as follows:</p>\n<ul>\n<li>if one element is even and the other is odd, the even number sorts before the odd one,</li>\n<li>else, the numerically smaller one is lower.</li>\n</ul>\n<p>That looks like:</p>\n<pre><code>int compare_evens_first(const void *va, const void *vb)\n{\n const int *a = va;\n const int *b = vb;\n\n if (*a % 2 != *b % 2)\n return (*a % 2) - (*b % 2);\n\n // else both odd, or both even\n // return *a - *b might overflow, so avoid that\n return (*a &gt; *b) - (*a &lt; *b);\n}\n</code></pre>\n<p>Then we can simply use it:</p>\n<pre><code>#include &lt;stdlib.h&gt;\n\nvoid sort_evens_first(int *array, size_t count)\n{\n qsort(array, count, sizeof *array, compare_evens_first);\n}\n</code></pre>\n<p>N.B. I've not had time to test this code; bugs may be lurking.</p>\n<hr />\n<h2>Additional problems with the supporting code</h2>\n<p>When reading input with <code>scanf()</code> and family, it is <strong>essential</strong> to confirm the return value before using any of the results.</p>\n<p>It's less important to check the result of <code>printf()</code> as failure there is less likely to lead to bad outcomes, but it's still worth considering so that we can return <code>EXIT_FAILURE</code> if the output wasn't successfully written (it might not be obvious to the user if directed to a file or pipeline, for example).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T08:59:32.080", "Id": "439571", "Score": "1", "body": "I'd tend to write `int const * const a = va;` (note the *two* `const`s). I'd also be tempted to write `const int parity = (*a % 2) - (*b % 2); if (parity != 0) return parity;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T09:01:24.330", "Id": "439572", "Score": "0", "body": "The answer from Roland actually extracts the int from the void pointer once, and then uses that - I prefer that too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T09:21:50.290", "Id": "439574", "Score": "3", "body": "@Martin - I feel that the conversion by assignment is slightly safer than casting the pointers, so that one is just two different preferences. There's arguments for both, and they could even be combined if you don't mind two more temporaries." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T18:33:27.613", "Id": "226199", "ParentId": "226196", "Score": "7" } }, { "body": "<p>Your code is quite complicated. The C standard library provides all the ingredients you need to sort an array. You just need to define a comparison function. All the rest is done by the <code>qsort</code> function from <code>stdlib.h</code>.</p>\n\n<p>The comparison function should look like:</p>\n\n<pre><code>static int even_first(const void *a, const void *b) {\n int left = *(const int *)a;\n int right = *(const int *)b;\n\n int res = (left % 2 != 0) - (right % 2 != 0);\n if (res == 0)\n res = (left &gt; right) - (left &lt; right);\n return res;\n}\n</code></pre>\n\n<p>The expressions of the form <code>cond1 - cond2</code> may look strange at first, but they are commonly used in C code in comparison functions like this one.</p>\n\n<p>The benefit over a naïve <code>left - right</code> is that no integer overflow can happen. Integer overflow is a common source of undefined behavior.</p>\n\n<p>To make the code more readable, it's also possible to extract the basic integer comparison into a separate function:</p>\n\n<pre><code>static int compare(int a, int b) {\n return a &lt; b ? -1 : a &gt; b ? +1 : 0;\n // alternatively: return (a &gt; b) - (a &lt; b);\n // alternatively: return a &lt; b ? -1 : a &gt; b;\n}\n</code></pre>\n\n<p>Then, the comparison function becomes:</p>\n\n<pre><code>static int even_first(const void *a, const void *b) {\n int left = *(const int *)a;\n int right = *(const int *)b;\n\n int res = compare(left % 2 != 0, right % 2 != 0);\n if (res == 0)\n res = compare(left, right);\n return res;\n}\n</code></pre>\n\n<p>This form is much less of a brain twister than the above variant.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T20:32:01.280", "Id": "226210", "ParentId": "226196", "Score": "8" } } ]
{ "AcceptedAnswerId": "226210", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T17:45:30.227", "Id": "226196", "Score": "5", "Tags": [ "c", "array", "sorting" ], "Title": "Partitioning and sorting even and odd numbers within an array" }
226196
<p>I tried to solve <a href="https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem" rel="nofollow noreferrer">the following challenge</a> and optimize the solution but my code still times out. My code is below.</p> <h1>Problem statement</h1> <blockquote> <h2>Climbing the Leaderbord</h2> <p>Alice is playing an arcade game and wants to climb to the top of the leaderboard and wants to track her ranking. The game uses <a href="https://en.wikipedia.org/wiki/Ranking#Dense_ranking_.28.221223.22_ranking.29" rel="nofollow noreferrer">Dense Ranking</a>, so its leaderboard works like this:</p> <ul> <li>The player with the highest score is ranked number 1 on the leaderboard.</li> <li>Players who have equal scores receive the same ranking number, and the next player(s) receive the immediately following ranking number.</li> </ul> <p>For example, the four players on the leaderboard have high scores of 100, 90, 90, and 80. Those players will have ranks 1, 2, 2, and 3, respectively. If Alice's scores are 70, 80 and 105, her rankings after each game are 4th, 3rd and 1st.</p> <h3>Function Description</h3> <p>Complete the <code>climbingLeaderboard</code> function in the editor below. It should return an integer array where each element <span class="math-container">\$res[j]\$</span> represents Alice's rank after the <span class="math-container">\$j^{th}\$</span> game.</p> <p><code>climbingLeaderboard</code> has the following parameter(s):</p> <ul> <li><code>scores</code>: an array of integers that represent leaderboard scores</li> <li><code>alice</code>: an array of integers that represent Alice's scores</li> </ul> <h3>Input Format</h3> <p>The first line contains an integer <span class="math-container">\$n\$</span>, the number of players on the leaderboard. The next line contains <span class="math-container">\$n\$</span> space-separated integers <span class="math-container">\$scores[i]\$</span>, the leaderboard scores in decreasing order. The next line contains an integer, <span class="math-container">\$m\$</span>, denoting the number games Alice plays. The last line contains <span class="math-container">\$m\$</span> space-separated integers <span class="math-container">\$alice[j]\$</span>, the game scores.</p> <h3>Constraints</h3> <ul> <li><span class="math-container">\$1 \le n \le 2 \times 10^5\$</span></li> <li><span class="math-container">\$1 \le m \le 2 \times 10^5\$</span></li> <li><span class="math-container">\$0 \le scores[i] \le 10^9\$</span> for <span class="math-container">\$0 \le i \lt n\$</span></li> <li><span class="math-container">\$0 \le alice[j] \le 10^9\$</span> for <span class="math-container">\$0 \le j \lt m\$</span></li> <li>The existing leaderboard, <span class="math-container">\$scores\$</span>, is in descending order.</li> <li>Alice's scores, <span class="math-container">\$alice\$</span>, are in ascending order.</li> </ul> <h3>Subtask</h3> <p>For 60% of the maximum score:</p> <ul> <li><span class="math-container">\$1 \le n \le 200\$</span></li> <li><span class="math-container">\$1 \le m \le 200\$</span></li> </ul> <h3>Output Format</h3> <p>Print <span class="math-container">\$m\$</span> integers. The <span class="math-container">\$j^{th}\$</span> integer should indicate Alice's rank after playing the <span class="math-container">\$j^{th}\$</span> game.</p> <p><sup>From <a href="https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem" rel="nofollow noreferrer"><em>Climbing the Leaderboard</em></a> on HackerRank.com</sup>.</p> </blockquote> <h1>My code</h1> <p>The code simply starts with <code>climbingLeaderboard</code> method below which delete all similar values in the scores array, after that it start with Alice score and using binary search it return the correct position.</p> <pre><code>int getPosition(vector&lt;int&gt; scores,int value,int start,int end){ int middle = (start+end)/2; if(scores[start]&lt;value){ return start; }else if(scores[end]&gt;value){ return end+1; } else if(scores[middle]==value){ return middle; } else if(start==end){ if(scores[start]&gt;value){ return start+1; }else{ return start; } } else if(scores[middle]&gt;value){ return getPosition(scores,value,middle+1,end); }else{ return getPosition(scores,value,start,middle-1); } } ///// ///// vector&lt;int&gt; climbingLeaderboard(vector&lt;int&gt; scores, vector&lt;int&gt; alice) { int i=1; while(1){ if(i == scores.size()){ break; } if(scores[i]==scores[i-1]){ scores.erase(scores.begin() + i); continue; } i++; } vector&lt;int&gt; results; int endValue = scores.size()-1; for(int j=0;j&lt;alice.size();j++){ endValue = getPosition(scores,alice[j],0,endValue); results.insert(results.end(),endValue+1); } return results; } </code></pre> <p>Any ideas? How can I make it not time out?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T21:16:20.080", "Id": "439665", "Score": "0", "body": "Also, it would be nice if the code can compile on its own, which requires the necessary `#include`s and other things (which I prefer not to guess)." } ]
[ { "body": "<p><span class=\"math-container\">\\$\\DeclareMathOperator{\\Oh}{O}\\$</span>Frankly, the code in the HackerRank editor is a large mess. It is promoting crap like <code>#include &lt;bits/stdc++.h&gt;</code> and <code>using namespace std;</code>, and the code contains many problems: <code>int</code> for traversing a <code>std::vector</code>, copying containers around, etc. Not to mention bad practices like <code>i++</code>, explicitly calling <code>fout.close()</code>, not using standard algorithm, etc. It really shouldn't be like that.</p>\n\n<p>In your code, the whole <code>getPosition</code> function is redundant. Use <code>std::lower_bound</code> instead. And since <code>std::vector::erase</code> is <span class=\"math-container\">\\$\\Oh(n)\\$</span>, the code is <span class=\"math-container\">\\$\\Oh(n^2)\\$</span>, which is unnecessary inefficient.</p>\n\n<p>The problem is very simple and can be finished in several lines without sacrificing readability:</p>\n\n<pre><code>using score_t = long;\nusing rank_t = long;\n\n// scores is passed by value to take advantage of possible optimization.\nrank_t get_rank(std::vector&lt;score_t&gt; scores, score_t alice_score)\n{\n scores.erase(std::unique(scores.begin(), scores.end()), scores.end());\n\n auto it = std::lower_bound(scores.begin(), scores.end(), alice_score, std::greater&lt;&gt;{});\n return it - scores.begin() + 1;\n}\n</code></pre>\n\n<p>The code is <span class=\"math-container\">\\$\\Oh(n)\\$</span> and I don't think you can do better. Note that each score of Alice's is independent, so it makes no sense to process them together in a function. I used <code>long</code> because the problem seems to require numbers as large as <span class=\"math-container\">\\$10^9\\$</span>. <code>scores</code> will be modified in the function, so instead of making a copy manually, we let the compiler do so for us in the parameter list. This enables possible optimization opportunities.</p>\n\n<p>Here, we used two standard algorithms:</p>\n\n<ul>\n<li><p><code>std::unique</code>, which \"removes\" adjacent equal elements. Standard algorithms cannot change the size of <code>scores</code> via iterators, so <code>std::unique</code> makes sure that the first <span class=\"math-container\">\\$N\\$</span> elements are the result, where <span class=\"math-container\">\\$N\\$</span> is the number of elements in the result. The rest of the elements are placed in a valid but otherwise unspecified state. Then, we call <code>erase</code> to erase these garbage elements. This is also known as the <a href=\"https://stackoverflow.com/q/799314\">remove-erase idiom</a>.</p></li>\n<li><p><code>std::lower_bound</code>, which performs a binary search and returns the first element that compares not \"less\" than the provided value. By default, \"less\" is defined by <code>&lt;</code>, thus operating on an ascending sequence. In this case, we use <code>std::greater&lt;&gt;</code> to define \"less\" by <code>&gt;</code>, so that <code>std::lower_bound</code> is adapted to work on a descending sequence.</p></li>\n</ul>\n\n<hr>\n\n<p>Now let's go through your code: (regardless of whether the code is what hackerrank gives you)</p>\n\n<pre><code>int getPosition(vector&lt;int&gt; scores,int value,int start,int end){\n</code></pre>\n\n<p>As I said, this function is provided by the standard library and you shouldn't be reinventing your own without a good reason. If you want to see how the standard version looks like, there is an example implementation at <a href=\"https://en.cppreference.com/w/cpp/algorithm/lower_bound\" rel=\"nofollow noreferrer\">cppreference</a>.</p>\n\n<hr>\n\n<pre><code>vector&lt;int&gt; climbingLeaderboard(vector&lt;int&gt; scores, vector&lt;int&gt; alice) {\n</code></pre>\n\n<p>As I said before, this function is illogical. It should handle one Alice-score at a time. Also, <code>climbingLeaderboard</code> isn't really a good function name.</p>\n\n<p>Passing <code>scores</code> by value is justified because you modify it in the functions, but passing <code>alice</code> by value introduces an unnecessary copy. It should be passed by const reference instead. And <code>int</code> is not only a magic type, but also a type that is not sufficiently large here.</p>\n\n<hr>\n\n<pre><code>int i=1;\nwhile(1){\n if(i == scores.size()){\n break;\n }\n if(scores[i]==scores[i-1]){\n scores.erase(scores.begin() + i);\n continue;\n }\n i++;\n}\n</code></pre>\n\n<p><strong>Space.</strong> Also, I am not sure what you are trying to achieve with the <code>while (1)</code> loop here: you are obfuscating the code by refusing to place the condition in the proper place. And <code>int</code> isn't the correct type to use here. Use <code>size_type</code> (or at least a named type). <code>++i</code> should be used instead of <code>i++</code> in a discarded value expression.</p>\n\n<p>And you are essentially reimplementing the <span class=\"math-container\">\\$\\Oh(n)\\$</span> <code>std::unique</code> in a <span class=\"math-container\">\\$\\Oh(n^2)\\$</span> way. Just use the standard algorithm and avoid reinventing the wheel.</p>\n\n<hr>\n\n<pre><code>vector&lt;int&gt; results;\nint endValue = scores.size()-1;\n</code></pre>\n\n<p>In this particular case, we know that <code>!scores.empty()</code>, but storing the result in a <code>int</code> is still inadvisable. Use <code>auto</code> or <code>std::vector&lt;int&gt;::size_type</code>.</p>\n\n<hr>\n\n<pre><code>for(int j=0;j&lt;alice.size();j++){\n endValue = getPosition(scores,alice[j],0,endValue);\n results.insert(results.end(),endValue+1);\n}\n</code></pre>\n\n<p>Again, space. And <code>++j</code> not <code>j++</code>. And the third line is just</p>\n\n<pre><code>results.push_back(endValue + 1);\n</code></pre>\n\n<p>There is no reason to use <code>insert</code> + iterator here.</p>\n\n<hr>\n\n<pre><code> return results;\n\n }\n</code></pre>\n\n<p>Is the weird indentation a copy-paste problem?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T14:01:41.483", "Id": "439732", "Score": "0", "body": "Why Would i++ be Bad Practice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T03:46:26.143", "Id": "439845", "Score": "0", "body": "Since the vector given is sorted in descending order, `lower_bound` doesn't seem to work right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T08:33:17.920", "Id": "439867", "Score": "0", "body": "@tinstaafl that's exactly when the generality and flexibility of STL comes to play -- in this case, you use `greater`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T11:24:31.460", "Id": "439878", "Score": "1", "body": "@RyanStone Unless you need the pre-increment value, the copy involved is useless. And while that is harmless at least for small trivial types if the operation is inlined, it's a bad habit to have due to the compiler not being able to fix it for you in more complex cases, with less optimisation, or with insufficient information." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T10:17:19.543", "Id": "226309", "ParentId": "226205", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T19:57:04.590", "Id": "226205", "Score": "2", "Tags": [ "c++", "algorithm", "programming-challenge", "time-limit-exceeded" ], "Title": "How can I make my solution to \"Climbing the Leaderboard\" not time out?" }
226205
<p>Below is some code for a basic command line utility to convert image formats of photos. I'm wondering how any part of it might be written with better style, i.e. how it could be neater, clearer and generally "better".</p> <pre><code>import os import argparse from PIL import Image def get_arguments(): ''' Get command line arguments ''' parser = argparse.ArgumentParser( description='A command line tool to convert images to different formats') parser.add_argument( 'input', help='full path to the input file or folder') parser.add_argument( 'outext', choices=Image.registered_extensions().keys(), help='output extension for file') parser.add_argument( '-n', '--new-name', help='give the output file a new name') parser.add_argument( '-d', '--destination', help='set new destination directory') parser.add_argument( '-R', '--remove-input', action='store_true', help='also remove the input file') args = parser.parse_args() if not (os.path.isfile(args.input) or os.path.isdir(args.input)): # easier to check file validiy here and keep infile as str, # rather than use type checking in parser.add_argument() raise parser.error('Unrecognised input type - input must be a file or folder') else: return args def convert_image(infile, outext, outname=None, outdir=None, remove_infile=False): ''' Convert an image to a new format and optionally: * Change the filename * Put the file in a new directory * Remove the input file ''' indir, inname = os.path.split(infile) inname = os.path.splitext(inname)[0] if outname is None: outname = inname if outdir is None: outdir = indir outfile = os.path.join(outdir, '{}{}'.format(outname, outext)) if not os.path.isdir(outdir) and outdir != '': os.makedirs(outdir) Image.open(infile).save(outfile) if remove_infile: os.remove(infile) def convert_images(im_dir, outext, outname=None, outdir=None, remove_infile=False): ''' run convert_image() for all files in a folder ''' for item in os.listdir(im_dir): if os.path.splitext(item)[1] in Image.registered_extensions().keys(): convert_image( os.path.join(im_dir, item), outext, outname=outname, outdir=outdir, remove_infile=remove_infile) def main(): args = get_arguments() if os.path.isdir(args.input): convert_images( args.input, args.outext, outname=args.new_name, outdir=args.destination, remove_infile=args.remove_input) elif os.path.splitext(args.input)[1] in Image.registered_extensions().keys(): convert_image( args.input, args.outext, outname=args.new_name, outdir=args.destination, remove_infile=args.remove_input) else: raise ValueError('Unsupported file format') if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>Specific suggestions:</p>\n\n<ol>\n<li>I generally find that ordering functions by their importance is helpful. Moving <code>get_arguments</code> just above or below <code>main</code> would allow readers to get into the functionality immediately. Others prefer to write methods in call order, but this feels a bit arbitrary (should <code>main</code> be first or last?) and not always achievable, because with branching it's possible to have a cycle of callers.</li>\n<li>*nix tools usually support any number of paths as their last arguments, operating on each of them. This would certainly be useful here, and means you could even avoid the whole <code>if</code>/<code>else</code> in <code>main</code> because all inputs should be file paths.</li>\n<li><a href=\"https://docs.python.org/3/library/argparse.html#filetype-objects\" rel=\"nofollow noreferrer\"><code>argparse</code> has a file type</a> which you can use.</li>\n<li>Don't rely on file extensions to correspond to file formats. I would instead rely on PIL to detect the file type and to throw an exception if it doesn't know it.</li>\n<li>Abbreviations like <code>inname</code> make the code harder to read. One way to avoid the urge to shorten everything is to use an IDE, because it'll help you auto-complete everything which is in scope.</li>\n<li>In the end this script is a small convenience wrapper around PIL. This is one of those rare occasions when I would suggest replacing it with a small shell script.</li>\n</ol>\n\n<p>General suggestions:</p>\n\n<ol>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><a href=\"https://github.com/timothycrosley/isort\" rel=\"nofollow noreferrer\"><code>isort</code></a> can group and sort your imports automatically.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> everywhere and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T19:45:24.183", "Id": "440079", "Score": "0", "body": "Re point 6, I understand that this could be written as a bash (or similar) script, but is is there a tangible advantage of doing so, or is this just something one might do as there is no need to use Python?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T07:15:31.437", "Id": "440131", "Score": "1", "body": "Well, a Bash script doing basically the same thing might be 10 lines. It won't win a beauty contest, but this isn't the sort of software which would be distributed to lots of people, so there's a trade-off of \"getting stuff done\" vs. \"doing it right.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-25T01:59:41.923", "Id": "440953", "Score": "0", "body": "You don’t even need a Bash script. Just download ImageMagick if you don’t have it already, it has a `convert` program that’s really easy to use. @Robert" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T03:42:03.353", "Id": "226228", "ParentId": "226209", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T20:22:46.400", "Id": "226209", "Score": "5", "Tags": [ "python", "python-3.x", "image", "console" ], "Title": "Command line utility to convert image formats of photos" }
226209
<p>Please review my code and help on How can I make it better calculation in method and class definition with SOLID ruby principles??</p> <p>The application has a static JSON file which contains:</p> <pre><code>{ "homes": { "person_a": "windows+tables", "person_b": "lights+tables", "person_c": "doors+curtains" } } </code></pre> <p>The application should, for each user request, calculate quotes for the 3 insurers. The business requirement is as follows:</p> <p>The quote is a 10% of the rate if 2 covers are matched or 20% if just 1 cover is matched and that is the biggest requested, 25% if it is the second biggest or 30% if is the third.</p> <p>the request from user is as follow</p> <pre><code>{:curtains=&gt;20, :tables=&gt;30, :windows=&gt;50} </code></pre> <p>The system should not return a quote if the value is zero(0)</p> <p>For eg: the application will return the result for the above user request</p> <pre><code>{ person_a: 8 (10% of 80 (two matches on windows and tables)) person_b: 7.5 (25% of 30 (one match on tables, the 2nd biggest cover)) insurer_c: 6 (30% of 20 (one match on curtains, the 3rd biggest cover) } </code></pre> <p>This is my solution:</p> <pre><code> require_relative './rules' module Coverage class CalculateQuotes def initialize(quotes) @quotes = quotes end def calculate_rates result = [] @insurer = Coverage::Rules.parse_file ## which will give { #"insurer_rates": { #"person_a": "windows+tables", # "person_b": "lights+tables", #"person_c": "doors+curtains" # }} @insurer[:insurer_rates].each do |k, v| @match_covers = match_cover(v.split("+")) result &lt;&lt; [k, calculate_rate ] end end def match_cover(covers) covers = covers.map { |x| x.to_sym } @quotes.select { |k,v| covers.include?(k) } end def calculate_rate premium = 0.0 persentage = get_percentage_by_match_covers @match_covers.values.each do |v| premium += v * persentage end premium == 0 ? nil : premium end def get_percentage_by_match_covers if @match_covers.size == 2 0.1 elsif @match_covers.size == 1 only_1_match_covers else 0 end end def only_1_match_covers index = position_of_customer_request case index when 0 0.2 when 1 0.25 when 2 0.3 else raise StandardError end end def position_of_customer_request (@quotes.to_a.reverse).index(@match_covers.to_a.flatten) end end end request = {:windows=&gt;50, :contents=&gt;30, :engine=&gt;20} Coverage::CalculateQuotes.new(request).calculate_rates <span class="math-container">````</span> </code></pre>
[]
[ { "body": "<h2>Ruby Hash</h2>\n\n<p>Rather than using a verbose case statement:</p>\n\n<blockquote>\n<pre><code> case index\n when 0\n 0.2\n when 1\n 0.25\n when 2\n 0.3\n</code></pre>\n</blockquote>\n\n<p>You could use a Hash:</p>\n\n<pre><code>rates = {0 =&gt; 0.2, 1 =&gt; 0.25, 2 =&gt; 0.3}\n</code></pre>\n\n<p>And the case can be replaced with:</p>\n\n<pre><code>rates[index]\n</code></pre>\n\n<hr>\n\n<h2>Rubocop Report</h2>\n\n<p>Use symbols as procs when possible.</p>\n\n<blockquote>\n<pre><code>covers = covers.map { |x| x.to_sym }\n</code></pre>\n</blockquote>\n\n<p>This is a compact alternative:</p>\n\n<pre><code>covers = covers.map(&amp;:to_sym)\n</code></pre>\n\n<hr>\n\n<p>Identify unused block arguments.</p>\n\n<blockquote>\n<pre><code>@quotes.select { |k,v| covers.include?(k) }\n</code></pre>\n</blockquote>\n\n<p>Use an underscore to identify unused block arguments:</p>\n\n<pre><code>@quotes.select { |k, _v| covers.include?(k) }\n</code></pre>\n\n<hr>\n\n<p>Numeric predicates should use predicate methods instead of comparison operators if possible</p>\n\n<blockquote>\n<pre><code>premium == 0 ? nil : premium\n</code></pre>\n</blockquote>\n\n<p>Use the predicate method <em>zero</em> instead:</p>\n\n<pre><code>premium.zero? ? nil : premium\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T21:58:24.613", "Id": "439492", "Score": "0", "body": "Thanks rubocop changes I will do finally when my code gets finalize. I am looking strong ruby code review which will calculate the percentage in a different way and some refactor to my class definition" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T21:49:22.160", "Id": "226214", "ParentId": "226213", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T21:28:38.003", "Id": "226213", "Score": "3", "Tags": [ "ruby" ], "Title": "Calculate the percentage of sum of hash values" }
226213
<p>I just "finished" a Udemy Java that involves building a banking application.</p> <p>Here is the problem definition:</p> <blockquote> <p>Scenario: You are a back-end developer and need to create an application to handle new customer bank requests.</p> <p>Your application should do the following:</p> <ul> <li>Read a .csv file of names, social security numbers, account type and initial deposit</li> <li>Use a proper data structure to hold all these accounts</li> <li>Both savings and checkings accounts share the following properties: <ul> <li>deposit()</li> <li>withdraw()</li> <li>transfer()</li> <li>showInfo()</li> </ul></li> <li><p>11-Digit Account Number (generated with the following process: 1 or 2 depending on Savings or Checking, last two digits of SSN, unique 5-digit number, and random 3-digit number)</p></li> <li><p>Savings Account holders are given a Safety Deposit Box, identified by a 3-digit number and accessed with a 4-digit code</p></li> <li>Checking Account holders are assigned a Debit Card with a 12-digit number and 4-digitPIN</li> <li><p>Both accounts will use an interface that determines the base interest rate.</p> <ul> <li>Savings accounts will use 0.25 points less than the base rate</li> <li>Checking accounts will use 15% of the base rate</li> </ul></li> <li><p>The show info method should reveal relevant account information as well as information specific to the Checking account or Savings account</p></li> </ul> </blockquote> <p>I'm trying to follow the SOLID Principles of Programming while creating new applications. I was hoping to get some feedback on my code, in categories such as things I did well, things I could improve on (such as a better way to implement something). For example, some feedback could be: "Don't do this method in this class, it should be done in a separate class because of this reason."</p> <p>I will attach my <code>Account</code> and <code>AccountTranscations</code> class in this post. But if you would like to see the other classes used in this project, go to my <a href="https://github.com/kingashy/bank" rel="nofollow noreferrer">repository</a>.</p> <p>Account Class:</p> <pre><code>package bank; import utilities.Generate; import utilities.Watch; public abstract class Account implements Rate { protected String name; protected int ssn; protected String dateOfCreation; protected long accountNum; protected double balance; protected double rate; protected int accountPin; public Account(String name, int ssn, double initialDeposit, int accountPin) { Watch watch = new Watch(); this.name = name; this.ssn = ssn; this.balance = initialDeposit; this.accountPin = accountPin; dateOfCreation = watch.getDateTime(); //System.out.println(dateOfCreation); rate = getRate(); } //get the rate //implementation will be dependent on the type of account public abstract double getRate(); //Getters public double getBalance() { return balance; } public long getAccountNum() { return accountNum; } public int getPin() { return accountPin; } public String getName() { return name; } //Setters //attempt to set a 4-digit pin to the specified account public void setPin(int accountPin) { if (!isValidPinWidth(accountPin)) return; this.accountPin = accountPin; System.out.println("New Pin Set"); } public void setBalance(double balance) { this.balance = balance; } //check if the pin entered is 4 digits public boolean isValidPinWidth(int accountPin) { if ((accountPin &gt; 9999) || (accountPin &lt; 0)) { System.out.println("Failure: Invalid pin."); return false; } else return true; } //check if the amount requested to withdrawn can be withdrawn from the specified account public boolean isValidWithdrawal(double amount) { if (balance - amount &lt; 0) { System.out.println("Failure: Account " + accountNum + " does not have sufficient funds."); return false; } else return true; } //check if the pin attempted is valid public boolean checkPinAttempt(int pinAttempt) { if (pinAttempt == accountPin) { //System.out.println("\nValid Pin Entry"); return true; } else { System.out.println("Invalid Pin Entry"); return false; } } //generate the 11-digit account number //1 or 2 depending on Savings or Checking, last two digits of SSN, unique 5-digit number //and random 3-digit number protected long generateAccountNum(int accountType) { Generate generate = new Generate(); long tempAccountNum = (long)(accountType * Math.pow(10, 10)); tempAccountNum += (ssn % 100) * Math.pow(10, 8); tempAccountNum += generate.random(5) * Math.pow(10, 3); tempAccountNum += generate.random(3); return tempAccountNum; } //generate a 4 digit pin public void generatePin() { accountPin = (int)(new Generate().random(4)); System.out.println("New Generated Pin: " + accountPin); } //attempt to unlock the specified account with the specified 4-digit pin public boolean unlock(int pinAttempt) { if (!checkPinAttempt(pinAttempt)) { //System.out.println("Account: Locked"); //System.out.println("Failure: Incorrect Pin"); return false; } else { System.out.println("Account " + getAccountNum() + ": Unlocked"); return true; } } //lock the account public void lock() { System.out.println("Account " + accountNum + ": Locked"); } //show everything about the account protected void showInfo() { StringBuilder sb = new StringBuilder(); sb.append("\nName: " + name); sb.append("\nSSN: " + ssn); sb.append("\nBalance: $" + balance); sb.append("\nRate: " + rate + "%"); sb.append("\nAccount Number: " + accountNum); sb.append("\nAccount Pin Number: " + accountPin); sb.append("\nDate of Account Creation: " + dateOfCreation); System.out.println(sb.toString()); } } </code></pre> <p>AccountTransactions Class:</p> <pre><code>package bank; import bank.Account; public class AccountTransactions { public AccountTransactions() { } //print the type of transaction being made private void printTranscation(Account account, double amount, String transaction) { System.out.println("Account Number: " + account.getAccountNum()); System.out.println(transaction + ": $" + amount); //System.out.println("New Balance: $" + account.getBalance()); } //print the type of request being made private void printRequest(String request) { System.out.println("\n" + request + " Request Recieved"); } //deposit the specified amount of money into the specified account public void deposit(Account targetAccount, double amount) { printRequest("Deposit"); targetAccount.setBalance(targetAccount.getBalance() + amount); printTranscation(targetAccount, amount, "Deposited"); } //attempt to withdraw the specified amount of money from the source account public void withdraw(Account sourceAccount, double amount) { printRequest("Withdraw"); if (!sourceAccount.isValidWithdrawal(amount)) return; sourceAccount.setBalance(sourceAccount.getBalance() - amount); printTranscation(sourceAccount, amount, "Withdrawn"); } //attempt to transfer the specified amount of money from the source account //to the target account public void transfer(Account sourceAccount, Account targetAccount, double amount) { printRequest("Transfer"); if (!sourceAccount.isValidWithdrawal(amount)) return; withdraw(sourceAccount, amount); deposit(targetAccount, amount); } //calculate the accrued interest and add it to the account's balance public void accrueInterest(Account targetAccount) { printRequest("Accrue Interest"); double accruedInterest = (targetAccount.getBalance() * (targetAccount.getRate()/100.0)); targetAccount.setBalance(targetAccount.getBalance() + accruedInterest); printTranscation(targetAccount, accruedInterest, "Accrued Interest"); } } </code></pre>
[]
[ { "body": "<h2>Interfaces, Contracts, APIs</h2>\n\n<p>Your code do not follow the interface specified. \nContracts/APIs may not be well-designed, and indeed usually are not; however they also usually are not modifiable. Therefore it is good practice put them in separate files such that you need not consult docs to see what you can change and what you cannot:</p>\n\n<pre><code>public interface Accout {\n void deposit(BigDecimal amount);\n void withdraw(BigDecimal amount);\n void transfer(Account destination, amount);\n String showInfo();\n}\n</code></pre>\n\n<p>If you want to share behaviors between subtypes then you may put those in a <code>BaseAccount</code> abstract class.</p>\n\n<h2>Data representation</h2>\n\n<p>Primitive types can be grouped in three: numbers, strings, and time.</p>\n\n<p>If you are not going to do arithmetic on it, it is not a number. Even if it is called a number. You may need to use numbers as keys IRL for efficiency reasons, this is not it.:</p>\n\n<pre><code>protected int ssn;\nprotected long accountNum;\nprotected int accountPin;\n</code></pre>\n\n<p>How you coud you have known this, without experience? Requirements like \"should start with ... , must be ... long\" these are operations on strings so they should be represented as string.</p>\n\n<p>Never use floating points for money or rates(tax, interest), floating point arithmetic is inexact, order-dependent, not reproducible :</p>\n\n<pre><code>protected double balance;\nprotected double rate;\n</code></pre>\n\n<p>Money and rates can be represented as <code>BigDecimal</code>s.</p>\n\n<p>Standard representation of date is <code>java.time.LocalDate</code>. Because no requirements exist for this field, it is best to delete it. If you had requirements like \"3 months after account creation ...\", a string representation is a ton of misery to deal with:</p>\n\n<pre><code>protected String dateOfCreation;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T23:56:42.700", "Id": "440464", "Score": "0", "body": "`public interface Account\n {\n void deposit(BigDecimal amount);\n void withdraw(BigDecimal amount);\n void transfer(Account destination, amount);\n String showInfo();\n}`\nSo why wouldn't I implement that interface into my AccountTranscation class? I understand the instructions said the subclass Checking and Savings need to share those functions but if I'm following the Single Responsibility rule, why would the Account Class take on those methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T23:58:23.533", "Id": "440465", "Score": "0", "body": "Thanks for your advice on Data representation! Will definitely make the necessary adjustments in my code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T07:26:35.813", "Id": "226407", "ParentId": "226216", "Score": "1" } }, { "body": "<p><strong>Single responsibility</strong></p>\n\n<p>The account class is responsible for maintaining the account balance, generting account numbers and PIN codes. Instead of using primitive long and int types for account numbers and PIN codes, you should declare classes for both types and have those classes implement the validation.</p>\n\n<p>Logically, the Account class contains information about the account. The account owner SSN should be a member of the class that holds account owner information.</p>\n\n<p>Account number generation, as implmented, does not fulfill the specification. The unique 5 digit part is only a random number which most likely will violate the uniqueness restriction long before the address space is exhausted. Account number generation should be moved to a class that manages accounts so that the uniqueness restriction can be efficiently maintained. The account locking and unlocking should be implemeted in a similar class that implements access management.</p>\n\n<p>The interest rate should be implemented as a reference to an instance of <code>AccountProduct</code>, which is a class that contains static information of a type of an account (e.g. account product name, interest rate, fees, etc).</p>\n\n<p>The purpose of <code>AccountTransactions</code> is not very clear. There are a set of methods that print the parameters they receive without changing the program state. The plural in the class name suggests that it implements a collection of transactions but that doesn't seem to be the case.</p>\n\n<p>And please, for the love of James Gosling, never use floating point types for representing money. They are not accurate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T23:27:34.233", "Id": "440457", "Score": "0", "body": "\"Instead of using primitive long and int types for account numbers and PIN codes, you should declare classes for both types and have those classes implement the validation\" Could you clarify what you mean by this? I'm just not sure why PIN codes and Account Number would need their own class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T23:30:31.567", "Id": "440458", "Score": "0", "body": "\"Account number generation, as implmented, does not fulfill the specification. The unique 5 digit part is only a random number which most likely will violate the uniqueness restriction long before the address space is exhausted.\" How does the current implementation not fulfill the specification? I was confused with that part of the problem description, how would that unique 5-digit code be generated?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T23:34:03.367", "Id": "440460", "Score": "0", "body": "\"The purpose of AccountTransactions is not very clear. There are a set of methods that print the parameters they receive without changing the program state.\" I'm working in the develop branch currently, and I use that class to perform transactions within a specific account or between multiple accounts. How could I make that clearer?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T07:27:39.847", "Id": "226408", "ParentId": "226216", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T22:26:10.673", "Id": "226216", "Score": "3", "Tags": [ "java", "object-oriented", "programming-challenge" ], "Title": "Banking application for Udemy Java course" }
226216
<h1>Goal</h1> <p>I want to extract HTML tags and its content from a string. The content (input) is queried from WordPress database.</p> <h3>Sample data (input)</h3> <p>I extract this dummy data from my WordPress database: <a href="https://www.phpliveregex.com/p/tan" rel="nofollow noreferrer">https://www.phpliveregex.com/p/tan</a><br> I believe this should cover all the needed tags to parse.</p> <h3>Expectation (output)</h3> <p>Accepting a HTML-format string as input. The output should be able to return a string which could be any of these:</p> <ol> <li>The HTML element string itself</li> <li>Attributes string of the HTML element</li> <li>Text nodes, child nodes string of the HTML element</li> </ol> <h3>My concern</h3> <ul> <li>Which solutions take less execution time?</li> <li>Which solutions save more server memory?</li> <li>Security vulnerable of each solutions.</li> </ul> <h1>Solutions</h1> <p>I've come up with a 2 solutions by myself. It works fine, but I don't know which one is good for my case.</p> <h3><a href="https://www.php.net/manual/en/function.preg-match.php" rel="nofollow noreferrer">Regex pattern</a></h3> <pre><code>$el = 'li'; // Ex $match = []; // Reserving for results /** * Regex - extract HTML tag and its content * Array map: * x[0] = everything * x[1] = open tag * x[2] = attributes * x[3] = content &amp; end tag * x[4] = content only * * Note for content: including text node + children node */ $reg = '/(&lt;'.$el.'(.*?)&gt;)((\n*?.*?\n*?)&lt;\/'.$el.'&gt;|)/'; if (preg_match($reg, $html_str, $match)) { echo 'Moving onward!';} </code></pre> <p><strong>Result</strong>: <a href="https://3v4l.org/BQtNX" rel="nofollow noreferrer">see demo of regex</a></p> <h3><a href="https://www.php.net/manual/en/class.domdocument.php" rel="nofollow noreferrer">DOM object</a></h3> <pre><code>$dom = new DomDocument(); $content = mb_convert_encoding( get_the_content(null, true), # WordPress func, it gives input str 'HTML-ENTITIES', 'UTF-8' ); $dom-&gt;loadHTML($content); $el = $doc-&gt;getElementsByTagName('li'); </code></pre> <p><strong>Result</strong>: returning a DOMNodeList and I have to do few more tasks to print it to a string which can be used.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T01:28:33.773", "Id": "439511", "Score": "2", "body": "They do different things, with different behavior in various cases of malformed or nested tags. It would be better to show us your real code, in context, with a clear statement of the task that your code accomplishes, so that we can advise you properly. See [ask]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T01:36:53.447", "Id": "439514", "Score": "1", "body": "Those are my real code, unless you want to see my repo. The context accepts WordPress content as input. A sample data were added as demo of regex. https://www.phpliveregex.com/p/tan" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T02:22:59.163", "Id": "439515", "Score": "5", "body": "As always, see [this answer](https://stackoverflow.com/a/1732454/3690024) for important information on parsing HTML with regex." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T14:26:58.030", "Id": "439626", "Score": "1", "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>Using regex to parse valid html will work (and you might call it <em>beautiful</em>) until it doesn't work... then you'll bend over backwards (over and over) each time you encounter an anomaly then try to write a patch for the pattern.</p>\n\n<p>Allow me to notify you of a simple, <a href=\"https://www.quackit.com/html_5/tags/\" rel=\"noreferrer\">valid html occurrence</a> that will break your sample pattern:</p>\n\n<p><a href=\"https://3v4l.org/qjFpO\" rel=\"noreferrer\">Demo</a></p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"/html_5/tags/html_link_tag_example.css\"&gt;\n</code></pre>\n\n<p>It would match because your <code>li</code> needle is not immediately followed by a word boundary character (<code>\\b</code>). Is this a simple thing to fix? Yes, but my point remains -- regex is an inappropriate tool for parsing valid html.</p>\n\n<p>I generally rely on DomDocument for most cases and when XPath makes life simpler, I use that to perform clean, readable queries on the document.</p>\n\n<p>This is one time when focussing on speed is a moot point -- speed is the least of your worries. What good is speed if the results are bogus? The goal should be to design a robust and reliable script using DOM-aware techniques.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T12:43:15.270", "Id": "439611", "Score": "0", "body": "Didn't see that comin'. But if I just use it in a very small scope of HTML then maybe it's ok right? Only makup tags, not meta tags." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T00:42:41.103", "Id": "439690", "Score": "0", "body": "Btw, I take advise about the speed. But what about memory consuming? (didn't got coffee last night untill this morning. Sorry)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T05:25:58.037", "Id": "439697", "Score": "0", "body": "Okay, one last example breakage: https://3v4l.org/0J5Wt. Now, to answer your comment about \"_Can I do it? What if I do it just a little bit? And only when it feels right? And I'll promise to stop as soon as I can._\" That right there, my friend, is how people wind up pregnant and battling horrid STDs. My advice: **abstain**. Draw a good thick line in the sand and bellow the mantra: \"Thou shall not parse valid html with regex.\" Can I stop you? No. I can only give advice about what I think is best. Is there a greater cost in speed and memory? Certainly. Is it worth it? Certainly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T11:04:24.967", "Id": "439711", "Score": "1", "body": "You are absolute right. I've just encountered a problem that it's ridiculous hard to solve by regex. It's querying a child node of an element. Because regex is just a fixed pattern, I couldn't get as much as I want in easy way. Now I really few sorry for changing to regex solution, it took another day good for nothing. Also like you say, yeah, regex is not a good choice when it comes to HTML. Thanks, I've been enlightened. Your example is so wonderful!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T12:09:29.587", "Id": "226257", "ParentId": "226220", "Score": "5" } } ]
{ "AcceptedAnswerId": "226257", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T22:54:53.537", "Id": "226220", "Score": "0", "Tags": [ "performance", "php", "comparative-review", "regex", "dom" ], "Title": "Extract HTML tags and its content from a string" }
226220
<p>I have different model in frontend and backend. When I submit form in frontend I need to transform that object to match backend model. Is there a better way than this one:</p> <pre><code>submit(confirmed: boolean) { this.transformCreditCardModel(confirmed); this.dialogRef.close({ success: confirmed, productAdjustment: confirmed === true ? this.exposuresForm.value : null }); } private transformCreditCardModel(confirmed: boolean) { const product = this.exposuresForm.value; if (confirmed &amp;&amp; product.hasOwnProperty(ExposuresFieldNamesEnum.creditCardProductIdentification)) { const prefix = product.creditCardProductIdentification.accountPrefix; const number = product.creditCardProductIdentification.accountNumber; delete product.creditCardProductIdentification.accountNumber; delete product.creditCardProductIdentification.accountPrefix; product.creditCardProductIdentification.cardNumber = prefix + this.CREDIT_CARD_MASK + number; } } </code></pre> <p>I don't like the part where I am asking whether the object contain some property if yes then creating new one and deleting old one. Is there a nicer way to do this ?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T04:44:19.520", "Id": "226230", "Score": "2", "Tags": [ "typescript", "angular-2+" ], "Title": "Submiting form and transform model to match backend" }
226230
<p>I took on a for-fun task of creating a memory allocator which uses process memory rather than making a bunch of system calls to the operating system. The task was: implement my own <code>malloc()</code> and <code>free()</code> functions which are limited to a pool (stack array) of 20000 bytes. I already had my own malloc and free implementations which used the <code>sbrk()</code> in unistd.h, but I realized the difference here would be that I need to re-create an sbrk that instead of getting memory from the OS, gets memory from my array. I had no experience doing this and was quite frankly pretty unfamiliar with how <code>sbrk()</code> worked internally. Even more, I still don't fully understand unistd's <code>sbrk()</code> integer pointer param. Nevertheless, I came up with a way to imitate the functionality below:</p> <pre><code>#define MEMORY_CAPACITY 20000 //NOTE: These are GLOBAL variables below char global_mem[MEMORY_CAPACITY] = {0}; void *p_break = &amp;global_mem; void* mov_sbrk(int increment) { void *final_address = (char*) global_mem + (MEMORY_CAPACITY-1); void *original = p_break; if(increment == 0) { return p_break; } if(((char*)p_break + increment) &lt; (char*)global_mem) { ERR("mov_sbrk: Cannot move to address prior to start of memory."); return (void*) -1; } if(((char*)p_break + increment) &gt; (char*)final_address) { ERR("You've run out of memory!"); return (void*) -1; } p_break = (void*) ((char*)p_break + increment); return original; } </code></pre> <p>Note that ERR is just a macro for <code>fprintf(stderr, msg)</code>. Please critique this implementation and let me know if I am missing anything. I've performed some tests with my allocator and so far, it performs as expected. The difference though is that I used a int because a int ptr like the "official" <code>sbrk()</code> uses as a parameter didn't make sense to me since it would force increments of the architecture's integer size rather than byte-by-byte.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T08:28:15.290", "Id": "439568", "Score": "2", "body": "Instead of explaining `ERR`, you should just include its definition in your program. Note that it then requires `<stdio.h>`, too, to declare `fprintf()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T12:59:30.140", "Id": "439614", "Score": "0", "body": "There's a lot of casts there. Not a good sign" } ]
[ { "body": "<p>Interface: consider accepting larger types than <code>int</code>. The Linux man page says:</p>\n<blockquote>\n<p>Various systems use various types for the argument of <code>sbrk()</code>. Common are <code>int</code>, <code>ssize_t</code>, <code>ptrdiff_t</code>, <code>intptr_t</code>.</p>\n</blockquote>\n<p><code>ptrdiff_t</code> seems like the most appropriate choice. Of course, it doesn't really matter with this implementation, as the capacity is less than 32768, and so even a minimal <code>INT_MAX</code> allocation will fail.</p>\n<hr />\n<blockquote>\n<pre><code>if(((char*)p_break + increment) &lt; (char*)global_mem)\n</code></pre>\n</blockquote>\n<p>Since we have no guarantee that <code>p_break + increment</code> won't overflow, we should re-write that as:</p>\n<pre><code>if (increment &lt; global_mem - (char*)p_break)\n</code></pre>\n<p>We know that <code>global_mem - p_break</code> can't overflow, as they are pointers into the same object.</p>\n<p>Similarly,</p>\n<blockquote>\n<pre><code>if(((char*)p_break + increment) &gt; (char*)final_address)\n</code></pre>\n</blockquote>\n<p>should be rewritten as</p>\n<pre><code>if (increment &gt; (char*)final_address - (char*)p_break)\n</code></pre>\n<hr />\n<p>We can avoid all the casts here by using <code>char*</code> pointers rather than <code>void*</code> - only the public interface needs the <code>void*</code>.</p>\n<hr />\n<p>I hope the <code>ERR</code> macro is compiled out in non-debug builds - users certainly won't want or expect output from <code>sbrk</code>.</p>\n<p>The error paths should set <code>errno</code> to <code>ENOMEM</code>.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include &lt;errno.h&gt;\n\n#define MEMORY_CAPACITY 20000\n\nvoid *mov_sbrk(int increment)\n{\n static char global_mem[MEMORY_CAPACITY] = {0};\n static char *p_break = global_mem;\n\n char *const limit = global_mem + MEMORY_CAPACITY;\n char *const original = p_break;\n\n if (increment &lt; global_mem - p_break || increment &gt;= limit - p_break)\n {\n errno = ENOMEM;\n return (void*)-1;\n }\n p_break += increment;\n\n return original;\n}\n</code></pre>\n<p>(I moved the global variables into the function to reduce their scope; that might not be appropriate if you also want to implement <code>brk()</code>, but I'm only reviewing the code I see!)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T16:51:31.427", "Id": "439646", "Score": "0", "body": "Question - Could there be any resulting bad effects of those 2 overflows occurring that you mentioned? As far as I knew, say that the math ends up overflowing, I'm never actually storing or accessing that overflowed address so was just curious if there was some other bad side effect of overflowing in the math even without an access or storage of the overflowed memory address?\n\nThank you for your thorough and helpful answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T20:34:13.750", "Id": "439660", "Score": "2", "body": "@the_endian The code inside the `if`s might or might not get executed when it shouldn't/should." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T08:24:11.843", "Id": "439992", "Score": "0", "body": "Pointer arithmetic overflow results in Undefined Behaviour, so absolutely anything is a possible outcome. Following the wrong branch of the conditional is the *least bad* outcome!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T14:03:18.853", "Id": "226265", "ParentId": "226231", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T06:06:13.963", "Id": "226231", "Score": "3", "Tags": [ "c", "memory-management" ], "Title": "Implementing sbrk for a custom allocator in C" }
226231
<p>Normally, when editing something, say when admin is approving a comment to a product, the <code>id</code> of the comment is stored in <code>&lt;input type="hidden"&gt;</code> to be included during form submission. But with this, just a change to the <code>id</code> may affect other pending comment, or those that are already approved.</p> <p>So instead I used <code>password_hash</code> to hash the <code>comment id</code>, and stores it with the original <code>comment id</code> in a session array. Then after submitting the form, I check the submitted hashed <code>comment id</code> to the session array, looking for a match, then getting the original <code>comment id</code>.</p> <p>Here's how I generate the hashed <code>comment id</code>:</p> <pre><code>foreach ($pendingComments as $comment) { $commentId = $comment['Id']; $hashed = password_hash($commentId, PASSWORD_DEFAULT); $_SESSION['COMMENT_IDS'][] = ['hash'=&gt;$hashed, 'id'=&gt;$commentId]; $customerName = $comment['GivenName'] . ' ' . $comment['Surname']; $message = $comment['Message']; $timestamp = $comment['Timestamp']; echo ' &lt;tr&gt; &lt;td&gt;' . $customerName . '&lt;/td&gt; &lt;td&gt;' . $message . '&lt;/td&gt; &lt;td&gt;' . $timestamp . '&lt;/td&gt; &lt;td&gt; &lt;form action="" method="POST"&gt; &lt;input type="hidden" value="'.$hashed.'" name="commentId"&gt; &lt;button type="submit" class="btn btn-outline-success btn-sm" name="changeCommentStatus" value="1"&gt;Approve&lt;/button&gt; &lt;button type="submit" class="btn btn-outline-danger btn-sm" name="changeCommentStatus" value="2"&gt;Reject&lt;/button&gt; &lt;/form&gt; &lt;/td&gt; &lt;/tr&gt; '; } </code></pre> <p>Here's how I check for a match after submission:</p> <pre><code>if (isset($_POST['changeCommentStatus'])) { $hashedId = $_POST['commentId']; $status = $_POST['changeCommentStatus']; $commentId = ''; foreach ($_SESSION['COMMENT_IDS'] as $data) { $hash = $data['hash']; $id = $data['id']; if ($hashedId === $hash) { $commentId = $id; break; } } if (empty($commentId)) { // this means that the $hashedId didn't matched anything, which also means that it has been altered // redirect back to the page and says that the id is invalid } echo $commentId;die; } $_SESSION['COMMENT_IDS'] = []; </code></pre> <p>As of now, it is working. But I'm not sure if there are any critical disadvantage /drawbacks or something, or if this is not recommended at all.</p> <p><strong>Note:</strong></p> <ul> <li>Some may say that an admin will not intentionally alter the source or something, but I'm planning to use this every time I need to use <code>&lt;input type="hidden" &gt;</code></li> <li>This may be more useful if while a user edits his comment, and somehow changed the <code>comment id</code> to another <code>comment id</code> that also belongs to the same user, instead the other comment has been edited</li> <li>I can somehow prevent the action if the replaced <code>comment id</code> belonged to another user, preventing the current user from indirectly editing other users' comments</li> <li>And of course, this is also to be used for other content that uses <code>&lt;input type="hidden"&gt;</code>, especially when editing, not just for comments</li> </ul>
[]
[ { "body": "<p>I would question the premise.</p>\n\n<blockquote>\n <p>But with this, just a change to the id may affect other pending comment, or those that are already approved.</p>\n</blockquote>\n\n<p>I don't see a problem here.</p>\n\n<p>Given the admin is allowed to approve any comment, and nobody else is authorized to access this page completely, I don't see how it's even a problem.</p>\n\n<p>To put it bluntly, nobody in the world is using such a clumsy approach as it's either useless or has a completely different solution (to ensure that a user cannot access other users' records there should be an ACL system in the database, not some HTML/Session ratatouille). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T07:08:09.230", "Id": "439542", "Score": "0", "body": "Although I agree about admin part, I was planning on using it for users also. Regardless, I'll research about the ACL system for other solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T06:50:18.037", "Id": "226235", "ParentId": "226232", "Score": "1" } } ]
{ "AcceptedAnswerId": "226235", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T06:33:56.993", "Id": "226232", "Score": "0", "Tags": [ "php" ], "Title": "Alternative for storing id in hidden input" }
226232
<p>There is a function that returns digits as vector of given number. Is it idiomatic way to solve this problem in Rust? Can you suggest more concise solution? </p> <pre><code>#[allow(dead_code)] fn num_digits(num: i32) -&gt; Vec&lt;i32&gt; { let mut x = num; let mut result: Vec&lt;i32&gt; = Vec::new(); loop { result.push(x % 10); x /= 10; if x == 0 {break} } result.reverse(); result } #[test] fn digits() { assert_eq!(num_digits(0), [0]); assert_eq!(num_digits(-1), [-1]); assert_eq!(num_digits(-123), [-1, -2, -3]); assert_eq!(num_digits(1), [1]); assert_eq!(num_digits(12), [1, 2]); assert_eq!(num_digits(456464), [4, 5, 6, 4, 6, 4]); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T08:25:39.720", "Id": "439567", "Score": "2", "body": "I have writtent a crate for that: https://crates.io/crates/digits_iterator" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T23:41:13.687", "Id": "439972", "Score": "0", "body": "Interesting @FrenchBoiethios. Your iterator impl looks very much like my unfold solution, but I don’t grok how you’re handling the `0` case." } ]
[ { "body": "<p>I would call this \"more idiomatic\" but I'm still not satisfied with it. Rust uses Iterators in a lot of ways, e.g. look at this implementation:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn num_digits(num: i32) -&gt; Vec&lt;i32&gt; {\n let mul = if num &lt; 0 { -1 } else { 1 };\n num.to_string()\n .chars()\n .filter_map(|x| x.to_digit(10))\n .map(|x| (x as i32) * mul)\n .collect()\n}\n</code></pre>\n\n<p>The <code>mul</code> variable is just for determining if you want negative or positive numbers.</p>\n\n<p>Because <code>i32</code> implements the <a href=\"https://doc.rust-lang.org/std/fmt/trait.Display.html\" rel=\"nofollow noreferrer\"><code>Display</code> trait</a> you can call <code>to_string</code> on it, which will give you a String representation of the <code>i32</code>.<br>\nNext is just iterating of the characters of the String and trying to convert them to a digit. <code>-</code> will be ignored, because it is not a digit and <code>filter_map</code> will filter all Results, that will return a <code>Err</code>. The next thing is to convert the numbers to a <code>i32</code> (because <code>to_digit</code> gives an <code>u32</code>) and either making them negative if the original number was negative or staying positive.</p>\n\n<p><code>collect</code> will put all the numbers into a collection, in this case a <code>Vec</code> because the type can be deduced by Rust (because of the return type)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T10:06:03.457", "Id": "439590", "Score": "1", "body": "I thought about something like this, but I don't want to store string representation of number in memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T03:00:25.003", "Id": "439839", "Score": "0", "body": "I'm upvoting for the use of iterators, but it doesn't feel great to turn it into a string." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T07:39:58.967", "Id": "226238", "ParentId": "226233", "Score": "1" } }, { "body": "<p>First thing's first, you probably don't want to leave the <code>#[allow(dead_code)]</code> option on. If the method is meant to be part of the public API, make it <code>pub</code>.</p>\n\n<p>It's also best to split your tests up into different test functions so that they all run every time. The way you've written it, when one fails, the tests stop and don't execute the other examples. In order to effectively refactor the code, I had to split them up.</p>\n\n<pre><code>#[test]\nfn zero() {\n assert_eq!(num_digits(0), [0]);\n}\n\n#[test]\nfn single_digit_negative() {\n assert_eq!(num_digits(-1), [-1]);\n}\n\n#[test]\nfn triple_digit_negative() {\n assert_eq!(num_digits(-123), [-1, -2, -3]);\n} \n\n#[test]\nfn single_digit_positive() { \n assert_eq!(num_digits(1), [1]);\n} \n\n#[test]\nfn double_digit_positive() {\n assert_eq!(num_digits(12), [1, 2]);\n}\n\n#[test] \nfn large_positive() {\n assert_eq!(num_digits(456464), [4, 5, 6, 4, 6, 4]);\n}\n</code></pre>\n\n<p>With that out of the way, let's talk about idiomatic Rust. In Rust, it is far more common to use functional style iterators rather than imperative loops. However, I've found that sometimes it's better to just write the imperative loop rather than jump through hoops to write the equivalent map/reduce. I would say that your loop is absolutely fine, suited to its purpose, and avoids converting the numbers to strings. Although it leaves me wishing that Rust had <code>do {} while cond</code> syntax. That's a failing of the language though, not one of yours. The <code>break</code> is the right call here and preferable to this \"trick\" you sometimes see.</p>\n\n<pre><code>while {\n result.push(x % 10);\n x /= 10;\n x != 0\n} { }\n</code></pre>\n\n<p>I prefer the break you used over abusing this quirk of the language.</p>\n\n<p>If you do wish to pursue an approach using iterators though, you can. You see the <code>fold</code> function takes a sequence and returns a single value via reduction. There is also an <code>unfold</code> function which does the opposite. It takes a seed value and produces a sequence from it, which is exactly what you're doing here. Rust doesn't have an <code>unfold</code> function, but it does have <a href=\"https://doc.rust-lang.org/std/iter/fn.from_fn.html\" rel=\"nofollow noreferrer\">std::iter::from_fn</a>, which is <em>very</em> close in functionality.</p>\n\n<pre><code>fn num_digits(num: i32) -&gt; Vec&lt;i32&gt; {\n /*\n * Zero is a special case because\n * it is the terminating value of the unfold below,\n * but given a 0 as input, [0] is expected as output.\n * w/out this check, the output is an empty vec.\n */\n if num == 0 {\n return vec![0];\n }\n\n let mut x = num;\n let mut result = std::iter::from_fn(move || {\n if x == 0 {\n None\n } else {\n let current = x % 10;\n x /= 10;\n Some(current)\n }\n })\n .collect::&lt;Vec&lt;i32&gt;&gt;();\n\n result.reverse();\n result\n}\n</code></pre>\n\n<p>Now, is that actually any better? I, personally, don't feel like it is.\nIt <em>could</em> be if we changed the method to return the iterator instead of the vector.\nIf we did that, then it could be lazily evaluated instead of calculating every item in the sequence up front.\nThat could make this alternative approach worthwhile <strong><em>if</em></strong> we were dealing with very large integers that would generate very large vectors, but that's a pretty big if.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T02:51:51.543", "Id": "226357", "ParentId": "226233", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T06:45:21.707", "Id": "226233", "Score": "4", "Tags": [ "rust" ], "Title": "Number to vector of its digits" }
226233
<p>An algorithm to reverse characters of each word in a sentence. What would be your concerns regarding the following solution?</p> <p>Example input: "I love New York" output: "I evol weN kroY"</p> <pre><code>public class Main { public static void main(String[] args) throws IOException { final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); final BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out)); final String words = bufferedReader.readLine().trim(); final char[] reversedWord = reverseWords(words.toCharArray()); bufferedWriter.write(reversedWord); bufferedReader.close(); bufferedWriter.close(); } private static char[] reverseWords(char[] input) { int startIndex = 0; int endIndex = 0; while (endIndex &lt; input.length) { final boolean isLastWord = endIndex == input.length - 1; if (input[endIndex] == ' ' || isLastWord) { if (isLastWord) { endIndex++; } reverseWord(input, startIndex, endIndex); startIndex = ++endIndex; } else { endIndex++; } } return input; } private static void reverseWord(char[] word, int startIndex, int endIndexExclusive) { final int wordLength = (endIndexExclusive - startIndex); for (int i = 0; i &lt; wordLength/2; i++) { final char temp = word[startIndex + i]; word[startIndex + i] = word[endIndexExclusive - i - 1]; word[endIndexExclusive - i - 1] = temp; } } } </code></pre> <p>Unit tests would be like:</p> <pre><code>public class QuestionOneTest { @Test public static should_reverse_chars() { // given final String input = "I love New York"; // when final char[] reversed = QuestionOne.reverseWords(input.toCharArray()); // then assert String.copyValueOf(reversed).equals("I evol weN kroY"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T07:35:13.513", "Id": "439556", "Score": "0", "body": "Could you include some unit tests to verify the results of the algorithm?" } ]
[ { "body": "<p>If you don't want to reinvent the wheel, you can implement a very short and simple solution using <code>java.util</code>:</p>\n\n<pre><code>public class Main {\n public static void main(final String[] args) throws IOException {\n final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));\n final BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));\n\n final String line = bufferedReader.readLine().trim();\n List&lt;String&gt; words = Arrays.asList(line.split(\"\\\\s+\"));\n\n String reversedWords = reverseWords(words);\n\n bufferedWriter.write(reversedWords.toCharArray());\n\n bufferedReader.close();\n bufferedWriter.close();\n }\n\n private static String reverseWords(final List&lt;String&gt; words) {\n return words.stream().map(word -&gt; reverseWord(word)).collect(Collectors.joining(\" \"));\n }\n\n private static String reverseWord(final String word) {\n return new StringBuilder(word).reverse().toString();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T12:50:56.900", "Id": "439883", "Score": "0", "body": "that is not code review" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T15:16:42.443", "Id": "439904", "Score": "3", "body": "Sure it is. “Don’t invent square wheels” is always a valid code review." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T11:57:15.407", "Id": "226256", "ParentId": "226236", "Score": "2" } }, { "body": "<h2><code>main()</code></h2>\n\n<ol>\n<li><p>it is considered bad practice for the <code>main()</code> method. at the very least, it is customary to catch all exceptions and print the stack trace to allow debugging. </p></li>\n<li><p>All IO resources (files, network sockets, DB connetions, etc) should be closed <em>before</em> the program exits. Java 7 has introduced the <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resources Statement</a> where the compiler ensures proper closure of resources in all control flows (including exceptions)</p></li>\n</ol>\n\n<h2><code>reverseWords()</code></h2>\n\n<p>I do not see any branch where <code>endIndex</code> is not advanced. so why is this performed separately for each branch? it can, and should, be done in one place.</p>\n\n<h2>Unit tests</h2>\n\n<p>the unit tests are missing cases of null input, empty string input, string with one word, string with multiple spaces between words: <code>\"multi space between words\"</code>, string with tab character instead of space between words.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T13:08:40.757", "Id": "226379", "ParentId": "226236", "Score": "2" } } ]
{ "AcceptedAnswerId": "226379", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T07:25:08.863", "Id": "226236", "Score": "3", "Tags": [ "java", "algorithm", "strings" ], "Title": "Reverse chars of each word in a string" }
226236
<p>The problem is the one explained in <a href="https://codereview.stackexchange.com/questions/149270/given-an-unsorted-integer-array-find-the-first-missing-positive-integer">Given an unsorted integer array, find the first missing positive integer</a></p> <blockquote> <p>Given an unsorted integer array, find the first missing positive integer.</p> <p>For example,<br> Given <code>[1,2,0]</code> return <code>3</code>,<br> and <code>[3,4,-1,1]</code> return <code>2</code>.</p> <p>Your algorithm should run in <span class="math-container">\$O(n)\$</span> time and use constant space.</p> </blockquote> <p>I am trying to learn Java 8+ and wrote the following code. Request any improvisations possible.</p> <pre><code>int firstPositive(int[] inputArray) { //Convert all negative numbers to 0. IntStream.range(0, inputArray.length).forEach(idx -&gt; { if (inputArray[idx] &lt; 0) inputArray[idx] = 0; }); IntStream.range(0, inputArray.length).forEach(idx -&gt; { if (Math.abs(inputArray[idx]) == 0) { inputArray[0] = -Math.abs(inputArray[0]); } else if (Math.abs(inputArray[idx]) - 1 &lt; inputArray.length &amp;&amp; inputArray[Math.abs(inputArray[idx]) - 1] &gt; 0) { inputArray[Math.abs(inputArray[idx]) - 1] *= -1; } }); OptionalInt res = IntStream.range(0, inputArray.length).filter(idx -&gt; inputArray[idx] &gt;= 0).findFirst(); if (res.isPresent()) { return res.getAsInt()+1; } return inputArray.length+1; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T07:41:45.933", "Id": "439558", "Score": "2", "body": "Links can rot or become broken. [I included a description of the challenge in your question.](https://codereview.meta.stackexchange.com/a/1994)" } ]
[ { "body": "<p>Instead of </p>\n\n<pre><code>if (res.isPresent()) {\n return res.getAsInt()+1;\n}\n\nreturn inputArray.length+1;\n</code></pre>\n\n<p>you could make use of the <code>orElse</code> method of <code>OptionalInt</code>:</p>\n\n<pre><code>return res.orElse(inputArray.length) + 1;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T14:10:21.847", "Id": "226266", "ParentId": "226237", "Score": "4" } }, { "body": "<p>Performance and readability are often a trade off. This <span class=\"math-container\">\\$O( n \\log n)\\$</span> solution just misses the <span class=\"math-container\">\\$O(n)\\$</span> target, because we must sort the pre-filtered array, but it’s much easier to reason about a map/reduce in my opinion. </p>\n\n<pre><code>Integer[] nums = {1,2,0};\n//Integer[] nums = {3,4,-1,1};\n//Integer[] nums = {1,2,4};\n//Integer[] nums = {1};\n//Integer[] nums = {0};\n\n Integer result = \n Arrays.stream(nums)\n .filter(x -&gt; x &gt; 0)\n .sorted()\n .reduce(1, (prev, curr) -&gt; (prev == curr) ? curr + 1 : prev );\n\nSystem.out.println(result);\n</code></pre>\n\n<p>I generally find it a bit strange that you’re using streams to generate what is essentially a loop (<code>forEach</code>) instead of turning the array into a stream and leveraging the power streams give you. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T20:06:53.630", "Id": "226339", "ParentId": "226237", "Score": "2" } }, { "body": "<p>There is a much easier solution which is strictly <span class=\"math-container\">\\$\\Theta(n)\\$</span>. Given <span class=\"math-container\">\\$\\ell\\$</span> the input list:</p>\n\n<ul>\n<li>Filter for just positive numbers: <span class=\"math-container\">\\$\\ell_{&gt;0} = \\{i \\in \\ell\\mid i &gt; 0\\}\\$</span></li>\n<li>Compute the maximum and the sum of the elements of <span class=\"math-container\">\\$\\ell_{&gt;0}\\$</span>. Namely, <span class=\"math-container\">\\$m = \\max \\ell_{&gt;0}\\$</span> and <span class=\"math-container\">\\$ s = \\sum _ {i \\in \\ell_{&gt;0}} i\\$</span></li>\n<li>Now there are two cases: whether it is missing a number in <span class=\"math-container\">\\$[1, m)\\$</span> or it is missing <span class=\"math-container\">\\$m+1\\$</span>.</li>\n<li>We know that <span class=\"math-container\">\\$1 + 2 + \\dots + m=m\\times(1+m)/2\\$</span>. Call this sum <span class=\"math-container\">\\$t\\$</span>. Compare <span class=\"math-container\">\\$t\\$</span> with <span class=\"math-container\">\\$s\\$</span>. If they are equal, it means that the sum is complete, so return the next integer, <span class=\"math-container\">\\$m+1\\$</span>. Otherwise, the difference will tell you which number is missing: <span class=\"math-container\">\\$t-s\\$</span>.</li>\n</ul>\n\n<p>You can achieve constant space by storing just three numbers: <span class=\"math-container\">\\$m\\$</span>, <span class=\"math-container\">\\$s\\$</span> and <span class=\"math-container\">\\$t\\$</span>. Where <span class=\"math-container\">\\$m\\$</span> and <span class=\"math-container\">\\$s\\$</span> will require <span class=\"math-container\">\\$|\\ell|\\$</span> steps to be computed. Consider this pseudocode.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>m = 0 # You can safely assume 0 here (or l[0] if you wish)\ns = 0\nfor i in l:\n if i &gt; 0:\n s += i\n if i &gt; m:\n m = i\n\nt = m*(m+1) /2\n</code></pre>\n\n<p>Of course, then computing <span class=\"math-container\">\\$t\\$</span> is <span class=\"math-container\">\\$\\Theta(1)\\$</span>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T11:26:28.530", "Id": "439879", "Score": "1", "body": "Clever solution, but it only works when exactly 0 or 1 positive integer is missing from the array. For example, it would fail with `[1,2,4,5,7]`. Also you stated that the computing time is `O(1)`, but it is `O(n)` where `n` is the input array length." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T10:52:31.100", "Id": "226374", "ParentId": "226237", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T07:36:45.410", "Id": "226237", "Score": "4", "Tags": [ "java", "beginner", "programming-challenge", "complexity" ], "Title": "Find the first missing positive integer in an array of integers" }
226237
<p>I have a general question regarding DRY. As you can see there are several parts such as <code>io.StringIO()</code>, <code>csv.writer</code>, <code>io.BytesIO</code> which are repeated. I now wonder if there is a better way, where I don't seem to <code>repeat</code> myself. Or is the way how I use it here a fair approach and not considered as DRY?</p> <p><strong>What does your code do?</strong></p> <p>With the code, I create two CSV-files in the buffer and directly upload them to an AWS S3 bucket. The data for these files are from my Postgres database. The framework I use is Django. That's why I am able to access the database with commands such as <code>Event.objects.filter</code></p> <p><strong>What does the rest of your program look like?</strong></p> <p>That's basically all of the program. After the CSV-files are available on my bucket an AWS Lambda function proceeds with the data and a machine learning model.</p> <p><strong>What Python version did you write this for?</strong></p> <p>I use Python 3.</p> <pre><code>class Forecast: @classmethod def export_data_for_forecast(cls): s3 = boto3.client( 's3', aws_access_key_id=settings.ML_AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.ML_AWS_SECRET_ACCESS_KEY, ) BUCKET_NAME = 'fbprophet' EVENT_DATA_OBJECT = 'event_data_test.csv' ORDER_DATA_OBJECT = 'orders_order_test.csv' events = Event.objects.filter(status=EventStatus.LIVE).prefetch_related( 'orders' ) # Prepare buffer for csv files event_data_buffer = io.StringIO() event_data_writer = csv.writer(event_data_buffer) event_data_writer.writerow(["Event PK", "Name", "Start date"]) order_data_buffer = io.StringIO() order_data_writer = csv.writer(order_data_buffer) order_data_writer.writerow(["Event PK", "Created", "Total Gross"]) active_events = filter(lambda event: not event.is_over, events) for event in active_events: event_data_writer.writerow([event.pk, event.name, event.start_date]) for order in event.orders.all(): order_data_writer.writerow( [order.event.pk, order.created, order.total_gross] ) # Prepare buffer and transform to binary event_data_buffer_to_binary = io.BytesIO( event_data_buffer.getvalue().encode('utf-8') ) order_data_buffer_to_binary = io.BytesIO( order_data_buffer.getvalue().encode('utf-8') ) # Upload to S3 s3.upload_fileobj(event_data_buffer_to_binary, BUCKET_NAME, EVENT_DATA_OBJECT) s3.upload_fileobj(order_data_buffer_to_binary, BUCKET_NAME, ORDER_DATA_OBJECT) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T08:13:49.180", "Id": "439562", "Score": "1", "body": "What does your code do? What does the rest of your program look like? What Python version did you write this for? We need more information and more context before being able to review this. Please take a look at the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T08:23:23.567", "Id": "439566", "Score": "2", "body": "I Mast thank you for your answer. I added the missing information. Hope that's better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T08:41:03.233", "Id": "439569", "Score": "3", "body": "Good, better already. Can you please change your title to reflect what your code does as well? Keep the concerns for the body of the question, not the title. The language doesn't have to be in the title either, we have tags for that :-)" } ]
[ { "body": "<p>The code's straightforward enough at a glance, I wouldn't have worried\ntoo much about the duplicate bits, especially since it's only double and\nnot multiple times for each part! Overdoing abstraction can hurt readability too. See below for some thoughts on how I'd approach this with that warning in mind.</p>\n\n<hr>\n\n<p>First of I'd try and move some of the functionality out of the function.\nThe constants ... should be constants and not right in the middle of the\nfunction body. Plus, some of them look like constants, while some are\ninline (<code>'orders'</code>). I can't tell why the distinction is made here,\nmaybe there was a reason.</p>\n\n<p>Also consider making all of this not a class method, but a regular one,\nthen you could for example start creating helper objects beforehand\n(like the <code>s3</code> client) and/or pass in preconstructed ones, e.g. for\ntesting purposes (like with mock objects).</p>\n\n<p>I'm not going to do these changes right here because you might have had\na reason for the <code>@classmethod</code>.</p>\n\n<hr>\n\n<p>Instead, let's do a few different changes to make the flow a little bit\neasier to comprehend for a reader not already familiar with the code\nbase:</p>\n\n<ul>\n<li><p>Moving construction and usage of an object closely together will let\nreaders just continue reading while not having to jump up the block\nagain to find out where a particular name was defined ... <em>unless</em>\nthere are pressing reasons like failing early if no connection could\nbe made (c.f. the <code>s3</code> client, though I'm guessing it doesn't actually\nestablish a connection until the <code>upload_fileobj</code> call is made).</p></li>\n<li><p>Breaking out functionality into more functions (or even local helper\nfunctions, no one's stoppiing you from creating more abstractions.\nAlternatively, and I think that's better suited for this case, create\na new class to wrap things together that belong together. The hint\nfor me here is <code>event_data_...</code> appearing with two suffixes and then\n<code>order_data_...</code> with the same suffixes. That begs to be an object\nwith two attributes.</p></li>\n</ul>\n\n<p>E.g. like this:</p>\n\n<pre><code>BUCKET_NAME = 'fbprophet'\nEVENT_DATA_OBJECT = 'event_data_test.csv'\nORDER_DATA_OBJECT = 'orders_order_test.csv'\n\n\nclass ForecastBuffer:\n def __init__(self, columns):\n # Prepare buffer for csv files\n self.buffer = io.StringIO()\n self.writer = csv.writer(self.buffer)\n self.writer.writerow(columns)\n\n def write_row(self, row):\n self.writer.writerow(row)\n\n def upload(self, s3, bucket_name, object_name):\n # Prepare buffer and transform to binary\n to_binary = io.BytesIO(self.buffer.getvalue().encode('utf-8'))\n s3.upload_fileobj(to_binary, bucket_name, object_name)\n\n\nclass Forecast:\n @classmethod\n def export_data_for_forecast(cls):\n event_data = ForecastBuffer([\"Event PK\", \"Name\", \"Start date\"])\n order_data = ForecastBuffer([\"Event PK\", \"Created\", \"Total Gross\"])\n\n events = Event.objects.filter(status=EventStatus.LIVE).prefetch_related(\n 'orders'\n )\n\n for event in filter(lambda event: not event.is_over, events):\n event_data.write_row([event.pk, event.name, event.start_date])\n\n for order in event.orders.all():\n order_data.write_row(\n [order.event.pk, order.created, order.total_gross]\n )\n\n # Upload to S3\n s3 = boto3.client(\n 's3',\n aws_access_key_id=settings.ML_AWS_ACCESS_KEY_ID,\n aws_secret_access_key=settings.ML_AWS_SECRET_ACCESS_KEY,\n )\n\n event_data.upload(s3, BUCKET_NAME, EVENT_DATA_OBJECT)\n order_data.upload(s3, BUCKET_NAME, ORDER_DATA_OBJECT)\n</code></pre>\n\n<p>Okay, so, the methods still a bit long in the middle.</p>\n\n<p>One thing that came to my mind was that <code>order.event.pk</code> is probably the\nsame as <code>event.pk</code> itself, right? Maybe check and simplify that.</p>\n\n<p>Then, the <code>filter</code> call with the <code>lambda</code> feels a bit weird to me, could\nthat perhaps already be filtered out in the <code>Event.objects.filter...</code>\nchain above it?</p>\n\n<p>You could also move one last bit to make things clearer: Don't expose\nthe \"raw\" <code>writerow</code> call, instead just feed objects to the buffers:</p>\n\n<pre><code> for event in filter(lambda event: not event.is_over, events):\n event_data.write(event)\n\n for order in event.orders.all():\n order_data.write(order)\n</code></pre>\n\n<p>However, that would require to have either a method on the object being\nwritten that specifies the serialisation output (well, which values to\nselect for the rows), or the same information on the <code>ForecastBuffer</code>\nobject (you could pass in a function that formats an object for CSV).\nDepends entirely on the rest of the code if that's worth it / feasible\nat all.</p>\n\n<hr>\n\n<p>Btw. I just saw that <code>itertools</code> has a complement to <code>filter</code> called\n<a href=\"https://docs.python.org/3/library/itertools.html#itertools.filterfalse\" rel=\"nofollow noreferrer\"><code>filterfalse</code></a> (arguably that could be a better name, <code>keep</code> comes to my\nmind):</p>\n\n<pre><code> # from itertools import filterfalse\n\n for event in filterfalse(Event.is_over, events):\n event_data.write(event)\n</code></pre>\n\n<p>Assuming that you can get the unbound method <code>Event.is_over</code> that way.</p>\n\n<hr>\n\n<p>Coming back to that <code>@classmethod</code>, the method here is difficult to test\ndue to the global variables. Depending on how it's called it might be\nworth to make <code>events</code> a parameter so that the functionality of <em>this\nmethod</em> is simply: format to CSV and upload. Same goes for <code>settings</code> -\nthe <code>s3</code> client most definitely should be passed in so this function\ndoesn't have to deal with configuration on top of formatting and\nuploading.</p>\n\n<p>Actually that's still two things, but it's short enough that that's\nprobably okay, splitting the formatting into another method might also\nbe worth it actually:</p>\n\n<pre><code>class Forecast:\n @classmethod\n def format_data_for_forecast(cls, events):\n event_data = ForecastBuffer([\"Event PK\", \"Name\", \"Start date\"])\n order_data = ForecastBuffer([\"Event PK\", \"Created\", \"Total Gross\"])\n\n for event in filterfalse(Event.is_over, events):\n event_data.write(event)\n\n for order in event.orders.all():\n order_data.write(order)\n\n return event_data, order_data\n\n @classmethod\n def export_data_for_forecast(cls):\n events = Event.objects.filter(status=EventStatus.LIVE).prefetch_related(\n 'orders'\n )\n\n event_data, order_data = cls.format_data_for_forecast(events)\n\n # Upload to S3\n s3 = boto3.client(\n 's3',\n aws_access_key_id=settings.ML_AWS_ACCESS_KEY_ID,\n aws_secret_access_key=settings.ML_AWS_SECRET_ACCESS_KEY,\n )\n\n event_data.upload(s3, BUCKET_NAME, EVENT_DATA_OBJECT)\n order_data.upload(s3, BUCKET_NAME, ORDER_DATA_OBJECT)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T08:07:20.737", "Id": "440479", "Score": "2", "body": "Great review and extremely helpful. Thank you @ferada" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T23:28:19.973", "Id": "226533", "ParentId": "226239", "Score": "1" } } ]
{ "AcceptedAnswerId": "226533", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T07:54:07.417", "Id": "226239", "Score": "3", "Tags": [ "python", "python-3.x", "csv", "django", "amazon-web-services" ], "Title": "Exporting data from PostgreSQL as CSV to S3 bucket" }
226239
<p>2 weeks ago I passed a technical test for the job of a frontend developer so they give me a screenshot of a typical form and I need to code it by HTML/CSS and they request a small animation with javascript the test was 6 hours I completed it in 40 min I thought it was ok, today I get a feedback that I was rejected because I need to ameliorate my coding skills, noting that I used code existing in many platforms like Codepen. I am looking for any feedback. Maybe I'm integrating in HTML in a wrong way.</p> <p></p> <pre><code> &lt;ul class="tab-group"&gt; &lt;li class="tab active"&gt;&lt;a href="#signup"&gt;Registro&lt;/a&gt;&lt;/li&gt; &lt;li class="tab"&gt;&lt;a href="#login"&gt;Acceso&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="tab-content"&gt; &lt;div id="signup"&gt; &lt;form action="/" method="post"&gt; &lt;div class="top-row"&gt; &lt;div class="field-wrap"&gt; &lt;label&gt; myHF ID&lt;span class="req"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;input type="text"required autocomplete="off"/&gt; &lt;/div&gt; &lt;div class="field-wrap"&gt; &lt;label&gt; Nombre&lt;span class="req"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;input type="text" required autocomplete="off" /&gt; &lt;/div&gt; &lt;div class="field-wrap"&gt; &lt;label&gt; Apellido&lt;span class="req"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;input type="text"required autocomplete="off"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="field-wrap"&gt; &lt;label&gt; Correo electrónico&lt;span class="req"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;input type="email"required autocomplete="off"/&gt; &lt;/div&gt; &lt;div class="field-wrap"&gt; &lt;label&gt; Teléfono&lt;span class="req"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;input type="text"required autocomplete="off"/&gt; &lt;/div&gt; &lt;div class="field-wrap"&gt; &lt;label&gt; País&lt;span class="req"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;input type="text"required autocomplete="off"/&gt; &lt;/div&gt; &lt;div class="field-wrap"&gt; &lt;label&gt; Patrocinador ID&lt;span class="req"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;input type="text"required autocomplete="off"/&gt; &lt;/div&gt; &lt;div class="field-wrap"&gt; &lt;label&gt; Contraseña&lt;span class="req"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;input type="password"required autocomplete="off"/&gt; &lt;/div&gt; &lt;button type="submit" class="button button-block"/&gt;Empecemos&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;div id="login"&gt; &lt;h1&gt;Bienvenido de vuelta&lt;/h1&gt; &lt;form action="/" method="post"&gt; &lt;div class="field-wrap"&gt; &lt;label&gt; myHF ID&lt;span class="req"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;input type="text"required autocomplete="off"/&gt; &lt;/div&gt; &lt;div class="field-wrap"&gt; &lt;label&gt; Contraseña&lt;span class="req"&gt;*&lt;/span&gt; &lt;/label&gt; &lt;input type="password"required autocomplete="off"/&gt; &lt;/div&gt; &lt;p class="forgot"&gt;&lt;a href="#"&gt;¿Olvidaste tu contraseña?&lt;/a&gt;&lt;/p&gt; &lt;button class="button button-block"/&gt;Ingresar&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- tab-content --&gt; &lt;/div&gt; &lt;!-- /form --&gt; @import "compass/css3"; $body-bg: #c1bdba; $form-bg: #13232f; $white: #ffffff; $main: #1ab188; $main-light: lighten($main,5%); $main-dark: darken($main,5%); $gray-light: #a0b3b0; $gray: #ddd; $thin: 300; $normal: 400; $bold: 600; $br: 4px; *, *:before, *:after { box-sizing: border-box; } html { overflow-y: scroll; } body { background:$body-bg; font-family: 'Titillium Web', sans-serif; } a { text-decoration:none; color:$main; transition:.5s ease; &amp;:hover { color:$main-dark; } } .form { background:rgba($form-bg,.9); padding: 40px; max-width:600px; margin:40px auto; border-radius:$br; box-shadow:0 4px 10px 4px rgba($form-bg,.3); } .tab-group { list-style:none; padding:0; margin:0 0 40px 0; &amp;:after { content: ""; display: table; clear: both; } li a { display:block; text-decoration:none; padding:15px; background:rgba($gray-light,.25); color:$gray-light; font-size:20px; float:left; width:50%; text-align:center; cursor:pointer; transition:.5s ease; &amp;:hover { background:$main-dark; color:$white; } } .active a { background:$main; color:$white; } } .tab-content &gt; div:last-child { display:none; } h1 { text-align:center; color:$white; font-weight:$thin; margin:0 0 40px; } label { position:absolute; transform:translateY(6px); left:13px; color:rgba($white,.5); transition:all 0.25s ease; -webkit-backface-visibility: hidden; pointer-events: none; font-size:22px; .req { margin:2px; color:$main; } } label.active { transform:translateY(50px); left:2px; font-size:14px; .req { opacity:0; } } label.highlight { color:$white; } input, textarea { font-size:22px; display:block; width:100%; height:100%; padding:5px 10px; background:none; background-image:none; border:1px solid $gray-light; color:$white; border-radius:0; transition:border-color .25s ease, box-shadow .25s ease; &amp;:focus { outline:0; border-color:$main; } } textarea { border:2px solid $gray-light; resize: vertical; } .field-wrap { position:relative; margin-bottom:40px; } .top-row { &amp;:after { content: ""; display: table; clear: both; } &gt; div { float:left; width:48%; margin-right:4%; &amp;:last-child { margin:0; } } } .button { border:0; outline:none; border-radius:0; padding:15px 0; font-size:2rem; font-weight:$bold; text-transform:uppercase; letter-spacing:.1em; background:$main; color:$white; transition:all.5s ease; -webkit-appearance: none; &amp;:hover, &amp;:focus { background:$main-dark; } } .button-block { display:block; width:100%; } .forgot { margin-top:-20px; text-align:right; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T09:26:28.713", "Id": "439576", "Score": "0", "body": "\"a technical test\" Please include more details about this test, so we can check whether you've implemented it right and look for obvious inefficiencies. Now we're missing a challenge description, which makes it a lot harder to write a decent review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T09:27:40.000", "Id": "439577", "Score": "0", "body": "this is the Link of the screenshot of the template: https://ibb.co/XJnKkZS\ni need just to know if there is a way to improve the code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T09:27:45.620", "Id": "439578", "Score": "1", "body": "\"noting that I used code existing in many platforms like Codepen\" Did they note this or do you note this? Did you write at least a decent amount of it yourself or is it a copy-paste pasta of other projects? Do you understand how and why it works?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T09:28:05.107", "Id": "439579", "Score": "0", "body": "No links please, embed all information in the question itself. Links can rot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T09:28:52.400", "Id": "439580", "Score": "0", "body": "[Cross-posted on Stack Overflow](https://stackoverflow.com/q/57515905/1014587)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T10:42:28.300", "Id": "439595", "Score": "0", "body": "of course, I understand what existing to the Code, I'm just confused from the feedback that I received" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T11:19:36.147", "Id": "439605", "Score": "0", "body": "Well, if you showed it to them exactly as you posted it here I can understand their hesitation. It looks shoddy. Improper indentation, odd whitespace usage and your CSS looks unordered." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T08:48:51.077", "Id": "226242", "Score": "0", "Tags": [ "html", "css" ], "Title": "HTML & Javascript form: Need feedback" }
226242
<p><a href="https://projecteuler.net/problem=50" rel="nofollow noreferrer">Problem</a>: Which prime, below one-million, can be written as the sum of the most consecutive primes?</p> <p>At the moment my code runs for over 200 seconds and was wondering how I can find a way to bring that down by a large amount. I have tried optimising it as much as I can and added an extra if statement, <code>if(subSum &lt; 1000000):</code> to reduce the need to see if <code>subSum</code> is a prime. Here is my code at the moment: </p> <pre class="lang-py prettyprint-override"><code>def sieve(num): primes = [] import math for i in range(num): primes.append(True) j = 1 while(j&lt;(math.sqrt(num)+1)): k = (j+1)*2 while(k&lt;(num+1)): primes[k-1] = False k+=(j+1) j+=1 primes[0] = False prime = [] for a in range(num): if(primes[a] == True): prime.append(a+1) return prime primes = sieve(1000000) count = 1 high = 0 length = len(primes) while count &lt;= length: i = 0 while(i&lt;(length-count)): sub = primes[i:i+count] subSum = sum(sub) if(subSum &lt; 1000000): if(subSum in primes): if(subSum&gt;high): high = subSum break else: i+=1 else: break count += 1 print(high) </code></pre> <p>Thanks for any help. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T11:16:52.043", "Id": "439604", "Score": "0", "body": "Did you check [these related questions](https://codereview.stackexchange.com/search?q=%5Bpython%5D+Consecutive+Prime+Sums) for more efficient methods?" } ]
[ { "body": "<p>I'll try to focus on the performance of the code provided, and what can be done to improve it. One key observation that I found is that it is more efficient to start searching for larger consecutive sums, and move towards shorter until we find a valid candidate. </p>\n\n<p>Then the obvious question is: where do we start? To find this, simply check the cumulative sums for the first n primes. As n increases, so does the sum. When the sum is above 1000000, it would not be possible to find a sum of n primes which is in the list of primes below 1000000. With this, it can be deduced that the sum can contain 546 elements at most. You should verify this on your own.</p>\n\n<p>Another observation is that 2 is the only even prime. With the knowledge that <code>odd + odd = even</code>, <code>even + odd = odd + even = odd</code>, and <code>even + even = even</code>, we can deduce that if and only if 2 is a part of the consecutive sum, the sum must contain an even number of elements. Thus, we must only check the very first consecutive sum (the one starting with 2) when the sum has an even number of elements. </p>\n\n<p>With all of this in place, the speed of the search is improved considerably.</p>\n\n<pre><code>n = 1000000\nfound = False\nprimes = sieve(n)\nprimes_set = set(primes)\n\nfor test_len in range(545, 1, -2):\n for i in range(0, len(primes)-test_len):\n s = sum(primes[i:i+test_len])\n if s in primes_set:\n print(\"found\", test_len, s)\n found = True\n break\n if found:\n break\n</code></pre>\n\n<p>This is of course only a small snippet, and not the full program. For example, this does not test for even length consecutive sums, but that should be trivial with the information provided above. However, the execution time for the loop is less than a second, with the majority of the runtime now being used by the prime sieve. However, optimizing that is outside the scope of this answer. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T11:48:05.250", "Id": "226255", "ParentId": "226250", "Score": "3" } }, { "body": "<p>** This is not a full review but I will try to tackle some important points.</p>\n<h1>Import statements</h1>\n<pre><code>def sieve(num):\n primes = []\n import math\n</code></pre>\n<p>According to pep8 <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> the official Python style guide: Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants, not inside a function like in the case of your sieve function.</p>\n<h1>Prime sieve</h1>\n<p>I'm not an expert of prime sieves however I guess your implementation is very inefficient therefore here's the common implementation:</p>\n<pre><code>def sieve(upper_bound):\n primes = [True] * upper_bound\n primes[0] = primes[1] = False\n\n for i, prime in enumerate(primes):\n if prime:\n yield i\n for n in range(i * i, upper_bound, i):\n primes[n] = False\n</code></pre>\n<p>You might try running your version of sieve and this one, they run in the following times when I ran the test on both on my i5 macbook pro for a 10 ** 7 input size:</p>\n<p>Time: 18.267110993 seconds. (your version)</p>\n<p>Time: 2.6265673870000015 seconds. (the other version)</p>\n<p>you might want to try running the test yourself and see the results.</p>\n<h1>Functions</h1>\n<p>You use functions in programming to bundle a set of instructions that you want to use repeatedly or that, because of their complexity, are better self-contained in a sub-program and called when needed. That means that a function is a piece of code written to carry out a specified task. To carry out that specific task, the function might or might not need multiple inputs. When the task is carried out, the function can or can not return one or more values. Therefore we can enclose the following piece of code inside a function.</p>\n<pre><code>primes = sieve(1000000)\ncount = 1\nhigh = 0\nlength = len(primes)\nwhile count &lt;= length: \n i = 0\n while(i&lt;(length-count)):\n sub = primes[i:i+count]\n subSum = sum(sub)\n if(subSum &lt; 1000000):\n if(subSum in primes):\n if(subSum&gt;high):\n high = subSum\n break\n else: \n i+=1\n else:\n break\n count += 1\nprint(high)\n</code></pre>\n<p>In the following way:</p>\n<pre><code>def get_longest_prime_sum(upper_bound):\n &quot;&quot;&quot;Return sum of the longest prime sequence in range upper_bound exclusive.&quot;&quot;&quot;\n primes = sieve(upper_bound)\n count = 1\n high = 0\n length = len(primes)\n while count &lt;= length: \n i = 0\n while(i&lt;(length-count)):\n sub = primes[i:i+count]\n subSum = sum(sub)\n if(subSum &lt; 1000000):\n if(subSum in primes):\n if(subSum&gt;high):\n high = subSum\n break\n else: \n i+=1\n else:\n break\n count += 1\n return high\n</code></pre>\n<h1>The rest of the code:</h1>\n<p>unfortunately, I couldn't get myself to have enough patience to wait for 200 seconds to examine what the code actually does however here's a link to my own implementation to the same problem:\n<a href=\"https://codereview.stackexchange.com/questions/224731/project-euler-50-consecutive-prime-sum-in-python\">Project Euler # 50 Consecutive prime sum in Python</a></p>\n<p>Note *** this is not the most optimal solution</p>\n<p>However it returns the right answer in almost 2 seconds, so you can examine how I implemented it and you will find a very useful review below my code, you might check it to give you some insights on other ways of solving the same problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T20:08:23.573", "Id": "226286", "ParentId": "226250", "Score": "1" } }, { "body": "<h2>PEP-008 Guidelines</h2>\n\n<p>Consult <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-008</a> for style guideline for writing idiomatic Python. You can use various checkers, such as PyLint or PyFlakes to verify compliance with the PEP-008 guidelines.</p>\n\n<p>Some highlight:</p>\n\n<ul>\n<li><code>if</code> and <code>while</code> loops do not need parenthesis <code>(...)</code> around the expression. Write <code>while k &lt; num + 1:</code>, instead of <code>while(k&lt;(num+1))</code>.</li>\n<li>Use one space around operators. Ie, write <code>j += 1</code> instead of <code>j+=1</code>.</li>\n<li>Testing if a value is <code>True</code> does not require comparison against the value <code>True</code>. Simply use the value itself. Ie, write <code>if primes[a]:</code> instead of <code>if(primes[a] == True):</code></li>\n<li>Avoid <code>mixedCase</code>. Instead of <code>subSum</code>, use <code>sub_sum</code>.</li>\n</ul>\n\n<h2>Multiplying a List</h2>\n\n<p>This code is very inefficient:</p>\n\n<pre><code>primes = []\nfor i in range(num):\n primes.append(True)\n</code></pre>\n\n<p>With 1 million candidates in your prime sieve, you will be growing the list by 1 value 1 million times. This may translate to 1 million reallocations, and 1 million copy operations, an <span class=\"math-container\">\\$O(N^2)\\$</span> operation since the number of elements to copy to the new list keeps increasing.</p>\n\n<p>Creating a list of 1 million <code>True</code> values is trivial:</p>\n\n<pre><code>primes = [True] * num\n</code></pre>\n\n<p>Pro tip: since all but one even candidate is prime, you actually want a list of 500 thousand pairs of <code>True</code>, <code>False</code> values.</p>\n\n<pre><code>primes = [True, False] * (num // 2)\nprimes[0] = False # One isn't prime\nprimes[1] = True # But two is\n</code></pre>\n\n<p>... and then you can only check odd candidates in your sieve for half the work.</p>\n\n<h2>Don't evaluate expensive constant values in a loop</h2>\n\n<p>This loop:</p>\n\n<pre><code>while(j&lt;(math.sqrt(num)+1)):\n # ...\n j += 1\n</code></pre>\n\n<p>will evaluate the square-root of <code>num</code> one thousand times!</p>\n\n<p>Since <code>num</code> is not changing in the loop, the resulting <span class=\"math-container\">\\$\\sqrt{n}\\$</span> value won't change either. And square-roots are expensive to calculate. So instead:</p>\n\n<pre><code>limit = math.sqrt(num) + 1\nwhile j &lt; limit:\n # ...\n j += 1\n</code></pre>\n\n<h2>Use <code>for</code> instead of <code>while</code>-with-increment</h2>\n\n<p>The loop:</p>\n\n<pre><code>j = 1\nwhile j &lt; limit:\n # ...\n j += 1\n</code></pre>\n\n<p>can easily be replaced by a <code>for</code> loop:</p>\n\n<pre><code>for j in range(1, limit):\n # ...\n</code></pre>\n\n<p>Pro-tip: Because we can initialize <code>primes</code> with <code>[False, True, False, True, False, True, ... ]</code> above, we can skip over the even candidates using a step-value in the <code>range()</code>:</p>\n\n<pre><code>for j in range(1, limit, 2):\n # ...\n</code></pre>\n\n<h2>List comprehension</h2>\n\n<p>We again encounter the inefficient <span class=\"math-container\">\\$O(N^2)\\$</span> <code>list.append()</code>-in-loop code:</p>\n\n<pre><code>prime = []\nfor a in range(num):\n if(primes[a] == True):\n prime.append(a+1)\n</code></pre>\n\n<p>Here, we can't use list-multiplication to create the desired list. Instead, we can use list-comprehension:</p>\n\n<pre><code>prime = [ a + 1 for a in range(num) if primes[a] ]\n</code></pre>\n\n<p>Why is this better? The Python interpreter can \"guess\" the resulting list is no longer than <code>num</code> entries, and allocate sufficient space. Then, it will loop through and populate the list with the successive <code>a + 1</code> values where <code>primes[a]</code> is true. At the end, it realizes the list is much shorter than it initially allocated, and can resize the list down to actual size.</p>\n\n<p>But wait. We are looking up in <code>primes[]</code> successive values, which involves 1 million indexing operations. Instead of looping over a <code>range(num)</code>, we should loop over the <code>primes</code> list itself. No indexing; just extracting each value from the list one after the other.</p>\n\n<pre><code>prime = [ a + 1 for a, prime in enumerate(primes) if prime ]\n</code></pre>\n\n<p>That <code>+1</code> is annoying; that is several thousand addition operations. It would be better if we counted elements of <code>primes</code> beginning with <code>1</code> for the <code>primes[0]</code> value:</p>\n\n<pre><code>prime = [ a for a, prime in enumerate(primes, 1) if prime ]\n</code></pre>\n\n<p>Easy peasy.</p>\n\n<h2>Zero-based indexing</h2>\n\n<p>Your indexing scheme, which stores the primality of <code>a</code> in <code>primes[a-1]</code> is confusing, and causes more headaches than it's worth. Yes, you've saved 1 list element, but that tiny savings in memory is not worth the confusion.</p>\n\n<p>Store the primality of <code>a</code> in <code>primes[a]</code>.</p>\n\n<h2>Realizing Slices</h2>\n\n<p>Consider the code:</p>\n\n<pre><code> sub = primes[i:i+count]\n subSum = sum(sub)\n</code></pre>\n\n<p>It takes the slice <code>primes[i:i+count]</code>, and then <strong>assigns it to a variable</strong>. At that moment, the Python interpreter <strong>MUST</strong> copy the slice into a real list. Then, you never use <code>sub</code> again, after the next statement.</p>\n\n<p>If you wrote:</p>\n\n<pre><code>subSum = sum(primes[i:i+count])\n</code></pre>\n\n<p>the Python interpreter <em>may</em> pass an iterator to the slice to the <code>sum()</code> function, and add up the numbers. The copy of the slice into a real list <em>may</em> be avoided.</p>\n\n<h2>x \"in\" list</h2>\n\n<p>To test <code>if subSum in primes:</code>, the interpreter checks the each element of the list to see if it matches the <code>subSum</code>, until either a match is found, or the end of the list is encountered. This is an <span class=\"math-container\">\\$O(N)\\$</span> operation. Not exactly slow, but it takes time.</p>\n\n<p>If you converted <code>primes</code> into a <code>set</code> beforehand, the values are hashed into bins, and the <code>in</code> operation drops to <span class=\"math-container\">\\$O(1)\\$</span>, which <strong>is</strong> fast.</p>\n\n<pre><code>primes = set(primes)\n</code></pre>\n\n<p>But ... creating the set is an <span class=\"math-container\">\\$O(N)\\$</span> operation and you already generated a list of primality flags in <code>sieve()</code>. If you returned that list of flags, in addition to your list of prime numbers, your prime test could be:</p>\n\n<pre><code>if primes_flags_from_sieve[subSum-1]:\n</code></pre>\n\n<p>which not only is <span class=\"math-container\">\\$O(1)\\$</span>, it is just a lookup! No hashing of the value to lookup. So this would be <strong><em>very fast</em></strong>.</p>\n\n<h2>Algorithmic Improvements</h2>\n\n<p>Repeatedly adding close to the same sequence of numbers together over and over again is a waste of time:</p>\n\n<pre><code>2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 + 29 + ...\n 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 + 29 + ...\n 5 + 7 + 11 + 13 + 17 + 19 + 23 + 29 + ...\n : : :\n2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 + 29\n 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 + 29\n 5 + 7 + 11 + 13 + 17 + 19 + 23 \n : : :\n2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 \n 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23\n 5 + 7 + 11 + 13 + 17 + 19 + 23\n : : :\n2 + 3 + 5 + 7 + 11 + 13 + 17 + 19\n 3 + 5 + 7 + 11 + 13 + 17 + 19 \n 5 + 7 + 11 + 13 + 17 + 19\n : : :\n2 + 3 + 5 + 7 + 11 + 13 + 17\n 3 + 5 + 7 + 11 + 13 + 17\n 5 + 7 + 11 + 13 + 17\n</code></pre>\n\n<p>If only there was a simple way of performing the addition once, and then getting the individual sums of subsequences out of that pre-processed data in <span class=\"math-container\">\\$O(1)\\$</span> time ...</p>\n\n<p>Left to student.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T02:31:19.780", "Id": "226356", "ParentId": "226250", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T10:21:20.113", "Id": "226250", "Score": "3", "Tags": [ "python", "programming-challenge", "primes" ], "Title": "Project Euler Problem #50 Consecutive Prime Sums" }
226250
<p>I'm using this <a href="https://github.com/SqliteModernCpp/sqlite_modern_cpp" rel="nofollow noreferrer">nice C++ wrapper</a> to work with SQLite3 in my project. I wanted to handle errors gracefully and automatically rollback if piece of code fails, so wrote this simple helper class:</p> <pre><code>class SqlTransaction { // RAII class to rollback on error public: SqlTransaction(std::shared_ptr&lt;sqlite::database&gt; db_): db(db_) { *db &lt;&lt; "begin;"; }; ~SqlTransaction() { if (!finished) rollback(); }; void commit() { if (!finished) { *db &lt;&lt; "commit;"; finished = true; } }; void rollback() { if (!finished) { *db &lt;&lt; "rollback;"; finished = true; } }; // Disable both copying and moving SqlTransaction(const SqlTransaction&amp;) = delete; SqlTransaction&amp; operator=(const SqlTransaction&amp;) = delete; SqlTransaction(SqlTransaction&amp;&amp;) = delete; private: std::shared_ptr&lt;sqlite::database&gt; db; bool finished = false; }; </code></pre> <p>It's to be used like this:</p> <pre><code>SqlTransaction trans(db); // work with db here, may throw if something goes wrong trans.commit(); </code></pre>
[]
[ { "body": "<p>There's not a lot of code here to be reviewed, but I'll have a go.</p>\n\n<ul>\n<li><p>A small efficiency gain is possible, by moving the <code>db_</code> argument in the initializer list, rather than copying it:</p>\n\n<pre><code>SqlTransaction(std::shared_ptr&lt;sqlite::database&gt; db_)\n : db{std::move(db_)}\n{ *db &lt;&lt; \"begin;\"; };\n</code></pre></li>\n<li><p>It's not necessary to delete the move constructor, as explicitly deleting the copy constructor prevents the move constructor being implicitly provided. However, if you feel that doing so improves clarity, you should probably delete move assignment, too.</p></li>\n<li><p>We should document that the class isn't thread-safe. It's quite reasonable that we should use it from only one thread, but we need to be clear to our users about that. Alternatively, we could make it thread-safe by making <code>finished</code> an <code>std::atomic&lt;bool&gt;</code> and using its test-and-set method, <code>exchange()</code>.</p></li>\n<li><p>Since <code>rollback()</code> tests <code>finished</code>, there's no need to duplicate that in the destructor - just call <code>rollback()</code> unconditionally. It may be worth taking steps to avoid it throwing when called there - destructors that throw need to be handled with extreme care.</p>\n\n<pre><code>~SqlTransaction() { try { rollback(); } catch (...) { /* ignore */ } };\n</code></pre></li>\n</ul>\n\n<p>I have nothing specific to SQLite, as I've not used that library myself (I'm surprised it has to parse string commands, rather than having methods for those operations, though).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T12:29:17.650", "Id": "226259", "ParentId": "226253", "Score": "4" } }, { "body": "<p>It's a good idea to encapsulate transaction-management.</p>\n\n<p>You don't go anywhere far enough though. Use <a href=\"https://en.cppreference.com/w/cpp/error/uncaught_exception\" rel=\"nofollow noreferrer\"><code>std::uncaught_exceptions()</code></a> to automate it more. (Before C++17, you have to use some non-standard ways to get that count.)</p>\n\n<p>Also, while rolling back must never fail, committing may. So, mark <code>noexcept</code> and <code>noexcept(false)</code> as appropriate.</p>\n\n<p>Last but not least, while copying a <code>std::shared_ptr</code> is not really expensive, moving it is much cheaper still.</p>\n\n<pre><code>class SqlTransaction {\npublic:\n SqlTransaction(std::shared_ptr&lt;sqlite::database&gt; db_)\n : db(std::move(db_))\n { *db &lt;&lt; \"begin;\"; }\n ~SqlTransaction() noexcept(false) {\n auto current = std::uncaught_exceptions();\n if (count == current)\n do_commit();\n else if (count &lt; current)\n do_rollback(); \n }\n void commit() {\n if (std::exchange(count, max_count) != max_count)\n do_commit();\n }\n void rollback() noexcept {\n if (std::exchange(count, max_count) != max_count)\n do_rollback();\n }\nprivate:\n void do_commit() {\n *db &lt;&lt; \"commit;\";\n }\n void do_rollback() noexcept {\n *db &lt;&lt; \"rollback;\";\n }\n\n SqlTransaction(const SqlTransaction&amp;) = delete;\n SqlTransaction&amp; operator=(const SqlTransaction&amp;) = delete;\n\n std::shared_ptr&lt;sqlite::database&gt; db;\n int count = std::uncaught_exceptions();\n static constexpr max_count = std::numeric_limits&lt;int&gt;::max();\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T16:53:48.960", "Id": "226273", "ParentId": "226253", "Score": "2" } }, { "body": "<h1>Throw an exception on invalid use</h1>\n\n<p>You have these two functions:</p>\n\n<pre><code>void commit() { if (!finished) { *db &lt;&lt; \"commit;\"; finished = true; } };\nvoid rollback() { if (!finished) { *db &lt;&lt; \"rollback;\"; finished = true; } };\n</code></pre>\n\n<p>These allow me to do write this code:</p>\n\n<pre><code>SqlTransaction tx(db);\ndb &lt;&lt; \"some query...\";\ntx.commit();\ntx.rollback();\n</code></pre>\n\n<p>Should the end result be committed or rolled back? The call to <code>rollback()</code> is not doing anything here, but if I wrote it in the code I probably really meant for the transaction to roll back. So this is without doubt a programming error. The same goes for calling <code>commit()</code> after a <code>rollback()</code>, and calling <code>commit()</code> or <code>rollback()</code> multiple times for the same transaction is probably also bad. So you should throw an exception in these cases, either a <code>std::logic_error</code> or a custom exception derived from it:</p>\n\n<pre><code>void commit() {\n if (finished)\n throw std::logic_error(\"commit() called on finished transaction\");\n *db &lt;&lt; \"commit;\";\n finished = true;\n}\n\nvoid rollback() {\n if (finished)\n throw std::logic_error(\"rollback() called on finished transaction\");\n *db &lt;&lt; \"rollback;\";\n finished = true;\n}\n</code></pre>\n\n<p>You might also consider throwing an exception in the destructor if there was no explicit <code>commit()</code> or <code>rollback()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T00:01:42.033", "Id": "439687", "Score": "0", "body": "Exceptions from the destructor are only under very limited circumstances not lethal." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T00:03:59.200", "Id": "439688", "Score": "0", "body": "You are right. But in this case I'd rather have the program terminate itself than silent database corruption." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T20:57:19.613", "Id": "226288", "ParentId": "226253", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T10:48:15.780", "Id": "226253", "Score": "3", "Tags": [ "c++", "sqlite", "raii" ], "Title": "RAII wrapper for SQLite transactions" }
226253
<p>Print the number of common factors of a and b.</p> <p>input > 10, 15</p> <p>Output > 2</p> <p>The common factors of 10, 15 are 1 and 5</p> <p>My code</p> <pre><code>def print_factors(x,y): l = [] for i in range(1, x + 1): if x % i == 0: l.append(i) m = [] for i in range(1, y + 1): if y % i == 0: m.append(i) print (list(set(l).intersection(m))) #len(print (list(set(l).intersection(m)))) num1 = int(input("Enter a number: ")) num2 = int(input("Enter a number: ")) print_factors(num1,num2) </code></pre> <p>Is there any better way to optimize, like list comprehension. or using zip module</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T13:12:50.817", "Id": "439618", "Score": "3", "body": "What is the intended output? The number `2` or the list `[1, 5]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T18:41:56.243", "Id": "439654", "Score": "0", "body": "@sim if you accept some answer, I guess you might want to upvote that answer as well using the ^ sign." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T22:27:04.803", "Id": "439673", "Score": "0", "body": "I am voting to close as off-topic because the code and specification do not agree, and so the code cannot be considered working." } ]
[ { "body": "<h1>Indentation &amp; style</h1>\n<p>One of the most distinctive features of Python is its use of indentation to mark blocks of code. Your code is not properly indented (each level of indentation should be equivalent to 4 spaces not like this:</p>\n<pre><code>def print_factors(x,y):\n l = []\n</code></pre>\n<p>like this:</p>\n<pre><code>def print_factors(x,y):\n l = []\n</code></pre>\n<p>Check pep8 <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> the official Python style guide, you'll find it helpful when learning the basics of Python code style and naming conventions.</p>\n<h1>Return</h1>\n<p>a function should not print anything, it should return</p>\n<pre><code>print (list(set(l).intersection(m)))\n#len(print (list(set(l).intersection(m))))\n</code></pre>\n<p>and print is a function in Python 3.x, so it's very obvious it has no length\nlen(the commented line).</p>\n<h1>len</h1>\n<p>len() is used to get the length of sequences:</p>\n<pre><code>my_list = [1, 2, 3, 4]\nprint(len(my_list))\n</code></pre>\n<p>output: 4</p>\n<h1>Docstrings</h1>\n<p>Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docsting is defined by including a string constant as the first statement in the object's definition.\nit is generally a good practice to use docstrings in your functions explaining what the function does that are usually enclosed within triple quotes:</p>\n<pre><code>def print_factors(number1, number2):\n &quot;&quot;&quot;Return factors of number1 and number2.&quot;&quot;&quot;\n # do things\n # return something\n</code></pre>\n<h1>Descriptive variable names</h1>\n<pre><code>l = []\nfor i in range(1, x + 1):\n if x % i == 0:\n l.append(i)\nm = []\nfor i in range(1, y + 1):\n if y % i == 0:\n m.append(i)\nprint (list(set(l).intersection(m)))\n</code></pre>\n<p>what is l, what is i what is x ... names should be descriptive to improve the readability of your code (whether people that are reading your code and trying to understand or you reading your own code in the future) and here's an example:</p>\n<pre><code>factors_1 = []\nfactors_2 = []\nfor divisor in range(1, number1):\n if number1 % divisor == 0:\n factors1.append(divisor)\nfor divisor in range(1, number2):\nif number2 % divisor == 0:\n factors2.append(divisor)\n</code></pre>\n<h1>The code</h1>\n<ol>\n<li>Your function is not even doing what it should be doing (returning\nthe number of common factors not the factors themselves.</li>\n<li>You don't have to iterate over the whole range of the number, you iterate up to the square root of the number is sufficient to find all factors.</li>\n</ol>\n<p>This is how the code might look like:</p>\n<pre><code>def get_factors(number):\n &quot;&quot;&quot;Generate factors of number.&quot;&quot;&quot;\n yield 1\n for divisor in range(2, int(number ** 0.5) + 1):\n if number % divisor == 0:\n if number // divisor != divisor:\n yield divisor\n yield number // divisor\n if number // divisor == divisor:\n yield divisor\n\n\nif __name__ == '__main__':\n number1 = int(input('Enter first number: '))\n number2 = int(input('Enter second number: '))\n number_1_factors = set(get_factors(number1))\n print(f'Factors of {number1}: {number_1_factors}')\n number_2_factors = set(get_factors(number2))\n print(f'Factors of {number2}: {number_2_factors}')\n common_factors = number_1_factors &amp; number_2_factors\n print(f'Number of common factors of {number1} and {number2}: {len(common_factors)} factors.')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T15:37:40.980", "Id": "226268", "ParentId": "226261", "Score": "0" } } ]
{ "AcceptedAnswerId": "226268", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T12:56:53.470", "Id": "226261", "Score": "0", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "How to find the common factors of 2 numbers" }
226261
<p>I am trying to achieve a getter/setter behaviour that will reduce code in C++. The interface I would like to achieve is for example: </p> <pre><code>MyClass a; a.velocity = 15; // Will dispatch a member function of MyClass responsible for setting "velocity". someFloatFunc( a.velocity ); // Will implicitly convert to the argument type of someFloatFunc if necessary </code></pre> <p>I have come up with the following. Suggestions, comments, gotchas, are welcomed.</p> <pre><code>#include &lt;iostream&gt; #include &lt;functional&gt; #include &lt;cassert&gt; using namespace std; template &lt;class T&gt; class encapsulate { public: typedef T value_type; typedef std::function&lt;void( const T&amp; )&gt; setter_type; // Disable things like auto b = a.v;. Access value like: int b = a.v; encapsulate( const encapsulate&amp; )=delete; encapsulate( T&amp;in, setter_type fin ): v( in ), f(fin) { } encapsulate &amp;operator= ( const T&amp;o ) { f( o ); return *this; } operator T() const { return v; } private: T &amp;v; setter_type f; }; #define GETSET( TYPE, VARPUBLIC, VARPRIVATE, CLASS, SETTER ) \ encapsulate&lt;TYPE&gt; VARPUBLIC {VARPRIVATE, std::bind(&amp;CLASS::SETTER,this,std::placeholders::_1 ) };\ private: \ TYPE VARPRIVATE; \ public: #define GETSETDEFAULT( TYPE, VARPUBLIC, VARPRIVATE, CLASS, SETTER, DEF ) \ encapsulate&lt;TYPE&gt; VARPUBLIC {VARPRIVATE, std::bind(&amp;CLASS::SETTER,this,std::placeholders::_1 ) };\ private: \ TYPE VARPRIVATE = DEF; \ public: template &lt;class T&gt; class A { public: GETSET( T, v, v_, A, setValue ) void setValue( const T &amp;other ) { cout &lt;&lt; "Setting value..." &lt;&lt; endl; v_ = other; } GETSETDEFAULT( double, g, g_, A, setGrayLevel, 0 ) void setGrayLevel( const double &amp;gl ) { if ( gl &lt; 0 ) { g_ = 0; return; } if ( gl &gt; 1 ) { g_ = 1; return; } g_ = gl; } }; const double testval = 215.33; //Implicit conversion test void printInt( const int &amp;c ) { std::cout &lt;&lt; "PrintInt: " &lt;&lt; c &lt;&lt; std::endl; assert( c == int(testval)); } int main() { A&lt;double&gt; a; a.v = testval; std::cout &lt;&lt; "a.v: " &lt;&lt; a.v &lt;&lt; std::endl; //auto b = a.v; // Disallowed double b = a.v; assert( a.v == b); b= testval-22; assert( a.v != b); printInt( a.v ); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T12:29:14.697", "Id": "439725", "Score": "0", "body": "Why do you want to disable `auto`? It’s generally recommend to prefer type inference these days?" } ]
[ { "body": "<p>A big issue with your solution is that you have to repeat yourself a lot, even when you have a macro to help you. I've come up with an alternative that doesn't use macros at all, and reduces the amount of repetition, although it still is more verbose that I would like. It uses the following class, which is similar to your <code>class encapsulate</code>, except that it doesn't store a pointer to a setter function, but instead has virtual getter and setter functions that can be overridden in a derived class:</p>\n\n<pre><code>template&lt;typename T&gt;\nclass property\n{\nprotected:\n T v;\n\n virtual const T &amp;get(void) const {\n return v;\n }\n\n virtual void set(const T &amp;o) {\n v = o;\n }\n\npublic:\n property() {}\n property(const T &amp;v_) { set(v_); }\n property &amp;operator=(const int &amp;o) { set(o); return *this; }\n operator T() const { return get(); }\n};\n</code></pre>\n\n<p>So now you can declare and use a property variable this way:</p>\n\n<pre><code>property&lt;int&gt; foo;\nfoo = 42;\n</code></pre>\n\n<p>When you assign a value to <code>foo</code>, it will call <code>operator=()</code>, which in turn will call the function <code>set()</code>. The trick is that since this is a virtual function, you can create a class or struct that inherits <code>property&lt;int&gt;</code>, and override the <code>set()</code> function. You can make use of the fact that you can declare a class or struct within another class or struct, and that you don't have to give them a name. It looks a bit weird at first, but it looks like this:</p>\n\n<pre><code>struct: property&lt;int&gt; { // declare a nameless struct that inherits from property&lt;&gt;\n void set(const int &amp;o) { // override the set() function\n ...;\n }\n} bar; // declare a variable named foo with this type\n</code></pre>\n\n<p>The main problem is that while a bare property variable works perfectly fine:</p>\n\n<pre><code>property&lt;int&gt; foo;\nfoo = 42;\n</code></pre>\n\n<p>The moment you inherit from it, the derived class has an implicitly defined assignment operator which hides the one in the base class. To get the one from the base class back, you have to add <code>using property::operator=;</code> to the body of the derived class. The same goes for the constructor that takes a value.</p>\n\n<p>Here is your <code>class A</code> converted to use <code>class property</code>:</p>\n\n<pre><code>template&lt;typename T&gt;\nclass A\n{\npublic:\n struct: property&lt;T&gt; {\n using property::operator=; // required for assigning\n\n void set(const T &amp;other) {\n std::cout &lt;&lt; \"Setting value...\" &lt;&lt; endl;\n property::set(other);\n }\n } v;\n\n struct: property&lt;double&gt; {\n using property::operator=; // required for assigning\n using property::property; // required for initialization to explicit value\n\n void set(const T &amp;gl) {\n if (gl &lt; 0)\n property::set(0);\n else if (gl &gt; 1)\n property::set(1);\n else\n property::set(gl);\n }\n } g = 0;\n};\n</code></pre>\n\n<p>Another option that avoids having to add the <code>using</code> statements is to make the derived property struct hidden, and add a base property reference to it that is public, like so:</p>\n\n<pre><code>class example {\n struct: property&lt;int&gt; {\n void set(const int &amp;o) { ... }\n } foo_;\n\npublic:\n property&lt;int&gt; &amp;foo = foo_;\n};\n</code></pre>\n\n<p>When assigning a value to <code>foo</code>, it doesn't know it's actually a derived class, so it will directly call <code>operator=</code> from the base class, which is what we want.</p>\n\n<p>Perhaps the above <code>class property</code> can be combined with a macro that hides the verbosity. For example:</p>\n\n<pre><code>#define PROPERTY(type, setter) \\\nstruct: property&lt;type&gt; { \\\n using property::property; \\\n using property::operator=; \\\n void set(const T &amp;value) { property::set(setter(value)); } \\\n}\n</code></pre>\n\n<p>This way, you can provide the name of a function that acts as the setter, or even a lambda. For example:</p>\n\n<pre><code>class B {\n static float invert(float x) {\n return -x;\n }\n\npublic:\n PROPERTY(float, invert) foo;\n PROPERTY(int, [](int v){ return v * v; }) bar = 0;\n};\n</code></pre>\n\n<p>The drawback of this macro is that you can't easily use non-static member functions as getters and setters.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T23:37:07.473", "Id": "226292", "ParentId": "226262", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T13:07:49.827", "Id": "226262", "Score": "5", "Tags": [ "c++", "properties" ], "Title": "C++ bare getter setter with dispatch" }
226262
<p>Currently I am trying to teach myself more about functions with parameters and return values that connects with one to another. </p> <p>In this code I created a square object with graphics.py that moves to a direction in loop whenever you press an arrow key.</p> <pre><code>from graphics import * import keyboard, time width = 200 height = 200 win = GraphWin("MOVEMENTS", width, height) win.setBackground(color_rgb(25,25,25)) key = "" def movement(key): if keyboard.is_pressed("Right"): key = "d" if keyboard.is_pressed("Left"): key = "a" if keyboard.is_pressed("Down"): key = "s" if keyboard.is_pressed("Up"): key = "w" return key def horizontal_movement(x): global key key = movement(key) if key == "d": x += 20 elif key == "a": x -= 20 return x def vertical_movement(y): global key key = movement(key) if key == "s": y += 20 elif key == "w": y -= 20 return y def main(): x = 0 y = 0 radius = 10 player = Rectangle(Point((width/2)-radius+x,(height/2)-radius+y), Point((width/2)+radius+x, (height/2)+radius+y)) while(True): player.undraw() player = Rectangle(Point((width/2)-radius+x,(height/2)-radius+y), Point((width/2)+radius+x,(height/2)+radius+y)) player.setFill("green") player.setWidth(2) player.draw(win) x = horizontal_movement(x) y = vertical_movement(y) update(10) main() </code></pre> <p>I want to know if there is a better code design that can move the movement(key) function into the horizontal_movement(x) and vertical_movement(y) function because right now I feel like I have typed some unecessary coding (the movement function and global key) into the script and I want it be as efficient as possible.</p> <p>If there is an alternative that makes the script more efficient or perform better, please let me know so I can improve further.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T14:43:09.397", "Id": "439628", "Score": "0", "body": "Did you use [this graphics.py](https://pypi.org/project/graphics.py/)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T21:18:01.873", "Id": "439666", "Score": "0", "body": "yes I am using the Zelle graphics.py" } ]
[ { "body": "<p>While you seem to be on a good way, your code still hast a <code>global</code> variable it does not need. You can simplify that code a lot by using something like this:</p>\n\n<pre><code>OFFSETS = {\"w\": (0, -1), \"Up\": (0, -1), # weird coordinate system...\n \"a\": (-1, 0), \"Left\": (-1, 0),\n \"s\": (0, 1), \"Down\": (0, 1),\n \"d\": (1, 0), \"Right\": (1, 0)}\n\ndef get_offsets():\n for key, offset in OFFSETS.items():\n if keyboard.is_pressed(key):\n return offset\n return 0, 0\n</code></pre>\n\n<p>This just returns a tuple of changes for each defined key, and zero otherwise.</p>\n\n<p>You should do as little as possible inside your loop (since that affects performance). You can set the graphic options once before the loop if you afterward continue modifying the object(s) in place. With the <code>Rectangle</code> that is easy, since you can just overwrite the <code>p1</code> and <code>p2</code> attributes. The two <code>Point</code> objects have an internal <code>_move</code> method that you can use (or you code it yourself):</p>\n\n<pre><code>class Point:\n ...\n def _move(self, dx, dy):\n self.x += dx\n self.y += dy\n</code></pre>\n\n<p>Another small performance optimization is to do nothing if the rectangle does not move. I would also add a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code></a> guard to allow importing from this module without running the game and follow Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommend adding spaces around operators. It also recommends putting imports from different modules on separate lines and not using unnecessary parenthesis.</p>\n\n<p>With these changes you get this for your <code>main</code>:</p>\n\n<pre><code>def main():\n x = 0\n y = 0\n radius = 10\n speed = 20\n lower_left = Point((width / 2) - radius, (height / 2) - radius)\n upper_right = Point((width / 2) + radius, (height / 2) + radius)\n player = Rectangle(lower_left, upper_right)\n player.setFill(\"green\")\n player.setWidth(2)\n player.draw(win)\n\n while True:\n dx, dy = get_offsets()\n if dx != 0 or dy != 0:\n player.undraw()\n dx, dy = dx * speed, dy * speed\n lower_left._move(dx, dy)\n upper_right._move(dx, dy)\n player.p1, player.p2 = lower_left, upper_right\n player.draw(win)\n update(10)\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>In addition, you might want to look for a different keyboard event handler, the <code>keyboard</code> module requires administrator rights (at least on UNIX). I know I certainly wouldn't just run a game that needs that. In other words, I would at least read the whole source code to make there is no exploit hidden in it (which was still possible with the code you have so far), but probably stay on the safe side and not play it at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T21:32:44.633", "Id": "439667", "Score": "1", "body": "Hello I just read your comment and I have been self teaching python/coding for almost 3 months so I am a bit overwhelmed by this, although I really appreciate the effort you put into this to help me out. Do you have any advice on improving coding for beginners? I know that the perfect solution is to practice everyday and don't give up, but I want to gather as much information as I continue to learn coding to give myself enough resources to improve. Although I am currently overwhelmed, I do believe that in future as I learn more I will be able to understand this and other challenges." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T22:31:43.680", "Id": "439678", "Score": "1", "body": "@ifsoMarcus We all started somewhere. One big improvement is knowing what is in the [standard library](https://docs.python.org/3/library/). The other thing that helped me getting better in algorithms, data structures and optimization is [Project Euler](https://projecteuler.net/). The first challenges can be solved with a one-liner in Python, but the later problems (20+) start to get more mathematically involved. If that is too much, any other coding challenge website will do. As you said, practice is everything. Answering questions here also helped me a lot :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T22:41:14.957", "Id": "439679", "Score": "1", "body": "Hello I am glad you replied to my comment. I had actually been doing online challenges including project euler before I started giving myself some projects to do, although I later dropped project euler because it began to become difficult to find answers without writing a smarter and more efficient script. Again thank you for the reply and I have actually considered to revisit some online challenges again because I feel stuck from just giving myself a project to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T22:46:11.680", "Id": "439680", "Score": "1", "body": "@ifsoMarcus Yeah, in the end almost nothing beats needing to use it in a real life problem...What you can (and should) do, though, is solve the problem as *proper* as possible. I.e. add docstrings and unittests, upload it to GitHub or similar and regularly push your updates (something I have not been doing diligently enough...). This way you already have a portfolio for if you want to apply to programming jobs." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T15:22:36.740", "Id": "226267", "ParentId": "226263", "Score": "1" } } ]
{ "AcceptedAnswerId": "226267", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T13:40:07.150", "Id": "226263", "Score": "1", "Tags": [ "python", "graphics" ], "Title": "Moving objects in loop in graphics.py" }
226263
<p>I wrote a functionality to read files and load them into the map <code>m_fileParams</code>.</p> <p>Then I am searching the specific keys in the map container using <code>find</code>. Here using <code>find</code> I am searching different keys.</p> <p>My code is working fine. But I wanted to know how best I can optimize the code?</p> <p>In several places I have used <code>find</code> to search the key in the map. Is there any way I can write generic method?</p> <p><code>m_fileParams</code> is declared in a header file:</p> <pre><code>std::map&lt;std::wstring, std::wstring&gt; m_fileParams; </code></pre> <p>Here is the <code>ReadFile</code> function, which resides in a .cpp file:</p> <pre><code>bool McEMRMgr::ReadFile() { IOperation* pFileReader = new McFileReader(); std::map&lt;std::wstring, std::wstring&gt; mapFileReaderResponse; if(pFileReader) { std::wstring strVendor, wstrFileLocation, wstrRegLocation; std::wstring FileType, regType; auto manufacSearchValue = m_fileParams.find(VENDOR); if (manufacSearchValue != m_fileParams.end()) { strVendor.assign(manufacSearchValue-&gt;second); transform( strVendor.begin(), strVendor.end(), strVendor.begin(), towlower); } else { strVendor.assign(L"default"); FileType.assign(L".File"); regType.assign(L".registry"); } auto emailSearchValue = m_fileParams.find(L"email_locations." + strVendor + L".type" + FileType); if (emailSearchValue != m_fileParams.end()) { if (emailSearchValue-&gt;second.compare(L"File") == 0) { auto FileSearchPath = m_fileParams.find(L"email_locations." + strVendor + L".paths" + FileType); wstrFileLocation = FileSearchPath-&gt;second; } } { emailSearchValue = m_fileParams.find(L"email_locations." + strVendor + L".type" + regType); if (emailSearchValue-&gt;second.compare(L"registry") == 0) { auto regSearchPath = m_fileParams.find(L"email_locations." + strVendor + L".paths" + regType); wstrRegLocation = regSearchPath-&gt;second; } } if (wstrFileLocation.length() != 0) { std::wstring oemFolderPath; auto oemSearchType = m_fileParams.find(L"oem_info_folder"); if (oemSearchType != m_fileParams.end()) { oemFolderPath.assign(oemSearchType-&gt;second); } else { oemFolderPath.assign(OEM_FOLDER_DEFAULT_PATH); } std::wstring oemPathPublicKey(oemFolderPath), oemPathSessionKey(oemFolderPath), oemPathUserChoices(oemFolderPath); oemPathPublicKey.append(PUBLIC_KEY_File); oemPathSessionKey.append(SESSION_KEY_File); oemPathUserChoices.append(USERCHOICES_File); pFileReader-&gt;SetParams((wchar_t*)oemPathPublicKey.c_str(), L"File"); pFileReader-&gt;Execute(); pFileReader-&gt;SetParams((wchar_t*)oemPathSessionKey.c_str(), L"File"); pFileReader-&gt;Execute(); pFileReader-&gt;SetParams((wchar_t*)oemPathUserChoices.c_str(), L"File"); pFileReader-&gt;Execute(); wchar_t* ptrWStr; wchar_t* buffer; ptrWStr = wcstok_s((wchar_t*)wstrFileLocation.c_str(), L" ", &amp;buffer); while (ptrWStr != NULL) { pFileReader-&gt;SetParams(ptrWStr, L"File"); pFileReader-&gt;Execute(); mapFileReaderResponse = pFileReader-&gt;GetResponse(); for (std::map&lt;std::wstring, std::wstring&gt;::iterator it = mapFileReaderResponse.begin(); it != mapFileReaderResponse.end(); ++it) { m_fileParams.insert({ it-&gt;first, it-&gt;second }); } ptrWStr = wcstok_s(nullptr, L" ", &amp;buffer); } if (mapFileReaderResponse.size() != 0) { m_cJobState.eFileStatus = OperationState::Success; } else { m_cJobState.eFileStatus = OperationState::Failed; } } if (wstrRegLocation.length() != 0) { pFileReader-&gt;SetParams((wchar_t*)wstrRegLocation.c_str(), L"registry"); pFileReader-&gt;Execute(); mapFileReaderResponse = pFileReader-&gt;GetResponse(); for (std::map&lt;std::wstring, std::wstring&gt;::iterator it = mapFileReaderResponse.begin(); it != mapFileReaderResponse.end(); ++it) { m_fileParams.insert({ it-&gt;first, it-&gt;second }); } } auto emailSearchType = m_fileParams.find(L"email"); std::wstring emailValue = emailSearchType-&gt;second; if (emailValue.length() &gt; 0) { MakeCopyofEmailToHKLM(emailValue); } else { } delete pFileReader; } return true; } </code></pre> <p>Someone please help me by providing your review comments.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T19:05:57.207", "Id": "439655", "Score": "1", "body": "Have you profiled the code or function in a release (or full optimizations turned on) build? It may not even be slow enough to be a problem." } ]
[ { "body": "<p>I can't say the code is very readable in general, although it is probably better than average. This function is way too long and should be separated into several functions according to logic. And the way you use the standard library facilities doesn't seem optimal.</p>\n\n<p>Here are some suggestions on the code:</p>\n\n<hr>\n\n<pre><code>IOperation* pFileReader = new McFileReader();\n</code></pre>\n\n<p><strong>No, No, No.</strong> C++ is not Java. There is no garbage collector in C++. This line makes your code inherently exception-unsafely and error-prone. See <a href=\"https://stackoverflow.com/q/6500313\">Why should C++ programmers minimize use of 'new'?</a>. The correct way is to declare a normal variable:</p>\n\n<pre><code>McFileReader fileReader{};\n</code></pre>\n\n<p>This avoids all sorts of problems.</p>\n\n<hr>\n\n<pre><code>if(pFileReader)\n</code></pre>\n\n<p>This is redundant because <code>new</code> never returns a null pointer. Instead, it throws an exception that is caught by an exception handler of type <code>std::bad_alloc</code>. Simply remove this check.</p>\n\n<hr>\n\n<pre><code>std::wstring strVendor, wstrFileLocation, wstrRegLocation;\nstd::wstring FileType, regType;\n</code></pre>\n\n<p>Declaring a bunch of variables at the start of a block is not advised in C++. A reader feels puzzled when seeing these two lines. Move these declarations to where these variables are actually used.</p>\n\n<hr>\n\n<pre><code>transform(\n strVendor.begin(), strVendor.end(),\n strVendor.begin(),\n towlower);\n</code></pre>\n\n<p>None of the arguments are guaranteed to nominate <code>std</code> in ADL, so use <code>std::transform</code> not <code>transform</code>. Also, <code>towlower</code> can't be used like this. Wrap it in a lambda.</p>\n\n<hr>\n\n<pre><code>strVendor.assign(manufacSearchValue-&gt;second);\n</code></pre>\n\n<p>Don't use <code>assign</code> when a simple assignment will do. <code>strVender = manufacSearchValue-&gt;second</code> is much better. This problem also recurs later in the code.</p>\n\n<p>Similarly, use <code>+=</code> instead of <code>append</code>.</p>\n\n<hr>\n\n<pre><code>pFileReader-&gt;SetParams((wchar_t*)oemPathPublicKey.c_str(), L\"File\");\n</code></pre>\n\n<p>The explicit cast to <code>wchar_t*</code> indicates a <em>serious</em> design problem. If you want to modify the string, use <code>&amp;oemPathPublicKey[0]</code> in C++11. If you don't want to modify the string, remove the cast. If <code>SetParams</code> is not const-correct, correct it.</p>\n\n<hr>\n\n<pre><code>wchar_t* ptrWStr;\nwchar_t* buffer;\nptrWStr = wcstok_s((wchar_t*)wstrFileLocation.c_str(), L\" \", &amp;buffer);\n</code></pre>\n\n<p>Now you are playing with pointers and <code>wcstok_s</code>. The first thing I notice is that <code>wcstok_s</code> doesn't exist in C++ at all. Even if it were to exist, you should be using the <code>string</code> operations. They are usually faster than the C functions if you use them properly.</p>\n\n<hr>\n\n<pre><code>m_fileParams.insert({ it-&gt;first, it-&gt;second });\n</code></pre>\n\n<p>Shouldn't it be <code>insert(*it)</code>? Or, if that doesn't work, <code>emplace(it-&gt;first, it-&gt;second)</code>?</p>\n\n<hr>\n\n<pre><code>auto emailSearchType = m_fileParams.find(L\"email\");\nstd::wstring emailValue = emailSearchType-&gt;second;\n</code></pre>\n\n<p>Why not <code>auto emailValue = emailSearchType.at(L\"email\");</code>?</p>\n\n<hr>\n\n<pre><code>else\n{\n}\n</code></pre>\n\n<p>This <code>else</code> clause is useless and can be removed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:10:29.980", "Id": "439740", "Score": "0", "body": "Thank you for your valuable inputs\nI used the dynamic allocation like as shown in the below line, \n\nIOperation* pFileReader = new McFileReader();\n\nbecause, \n\nwe have written this function to read the files and loads into the map. we usually don't know what size the file has, so you can't decide how much memory to allocate until you run the program." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:11:18.273", "Id": "439741", "Score": "0", "body": "And also class MCFileReader is deriving from IOperation like as shown below, \nclass McFileReader : public IOperation\n{\n\npublic:\n void SetParams(wchar_t* wszParams, wchar_t* wszParamType);\n bool Execute();\n};" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:11:51.380", "Id": "439742", "Score": "0", "body": "Even with this point also if it is not advisable to use dynamic allocation, as per your suggestion i will use local variable like\n\nMcFileReader fileReader;" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:15:29.993", "Id": "439744", "Score": "0", "body": "That’s irrelevant. You always use one McFileReader, so a local variable is better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:18:14.763", "Id": "439745", "Score": "0", "body": "ok, thank you..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:22:42.510", "Id": "439746", "Score": "0", "body": "And also about the pointer null check, I used if(pFileReader) , because \nIf new completes successfully, it always returns a pointer ( and as you said if it doesn't complete successfully, an exception is thrown, and nothing is returned)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:24:42.987", "Id": "439747", "Score": "1", "body": "@JohnPaulCoder That’s exactly why it should be removed. The pointer is always non null, so the check doesn’t really do anything." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T09:52:23.113", "Id": "226307", "ParentId": "226275", "Score": "0" } } ]
{ "AcceptedAnswerId": "226307", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T16:58:45.960", "Id": "226275", "Score": "3", "Tags": [ "c++", "c++11" ], "Title": "How to optimize the code snippet which has several calls to find method that is to read files and load them into the map?" }
226275
<p>The cube, 41063625 (<span class="math-container">\$345^3\$</span>), can be permuted to produce two other cubes: 56623104 (<span class="math-container">\$384^3\$</span>) and 66430125 (<span class="math-container">\$405^3\$</span>). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.</p> <p>Find the smallest cube for which exactly five permutations of its digits are cube.</p> <pre><code>from collections import Counter from time import perf_counter def get_cube_permutations(upper_bound, number_of_permutations): """Return minimum cube that has number_of_permutations permutations as cubes.""" cubes = [str(number ** 3) for number in range(1, upper_bound)] sorted_cubes = [''.join(sorted(cube)) for cube in cubes] count = Counter() for sorted_cube in sorted_cubes: count[sorted_cube] += 1 for sorted_cube, number_of_occurrences in count.items(): if number_of_occurrences == number_of_permutations: return cubes[sorted_cubes.index(sorted_cube)] return 0 if __name__ == '__main__': START_TIME = perf_counter() UPPER_BOUND = 10 ** 4 TARGET_PERMUTATIONS = 5 MINIMUM_CUBE = get_cube_permutations(UPPER_BOUND, TARGET_PERMUTATIONS) if MINIMUM_CUBE: print(f'Minimum cube that has {TARGET_PERMUTATIONS} permutations of its digits as cubes: {MINIMUM_CUBE}.') else: print(f'No cube found that has {TARGET_PERMUTATIONS} of its digits for numbers within range {UPPER_BOUND}.') print(f'Time: {perf_counter() - START_TIME} seconds.') </code></pre>
[]
[ { "body": "<p>I managed to improve the speed of your code by ~11% with simple changes:</p>\n\n<pre><code>def get_cube_permutations_improved(upper_bound, number_of_permutations):\n \"\"\"Return minimum cube that has number_of_permutations permutations as cubes.\"\"\"\n cubes = [number ** 3 for number in range(1, upper_bound)]\n sorted_cubes = [\"\".join(sorted(str(cube))) for cube in cubes] # create string here\n count = Counter(sorted_cubes) # insert it on Counter object initialization\n for sorted_cube, number_of_occurrences in count.items():\n if number_of_occurrences == number_of_permutations:\n return cubes[sorted_cubes.index(sorted_cube)]\n return 0\n</code></pre>\n\n<p>My test looks like this:</p>\n\n<pre><code>print(\"old version\")\nUPPER_BOUND = 10 ** 6 \nTARGET_PERMUTATIONS = 13\n# UPPER_BOUND = 10 ** 4\n# TARGET_PERMUTATIONS = 5\nSTART_TIME = perf_counter()\nMINIMUM_CUBE = get_cube_permutations(UPPER_BOUND, TARGET_PERMUTATIONS)\nif MINIMUM_CUBE:\n print(f\"Minimum cube that has {TARGET_PERMUTATIONS} permutations of its digits as cubes: {MINIMUM_CUBE}.\")\nelse:\n print(f\"No cube found that has {TARGET_PERMUTATIONS} of its digits for numbers within range {UPPER_BOUND}.\")\nprint(f\"Time: {perf_counter() - START_TIME} seconds.\")\nprint(\"improved version\")\nSTART_TIME = perf_counter()\nMINIMUM_CUBE = get_cube_permutations_improved(UPPER_BOUND, TARGET_PERMUTATIONS)\nif MINIMUM_CUBE:\n print(f\"Minimum cube that has {TARGET_PERMUTATIONS} permutations of its digits as cubes: {MINIMUM_CUBE}.\")\nelse:\n print(f\"No cube found that has {TARGET_PERMUTATIONS} of its digits for numbers within range {UPPER_BOUND}.\")\nprint(f\"Time: {perf_counter() - START_TIME} seconds.\")\n</code></pre>\n\n<p>My results for <code>UPPER_BOUND = 10 ** 6 and TARGET_PERMUTATIONS = 13</code>:</p>\n\n<pre><code>old version\nMinimum cube that has 13 permutations of its digits as cubes: 1027182645350792.\nTime: 2.5825698000000004 seconds.\nimproved version\nMinimum cube that has 13 permutations of its digits as cubes: 1027182645350792.\nTime: 2.3012089000000002 seconds.\n</code></pre>\n\n<p>My results for <code>UPPER_BOUND = 10 ** 4 and TARGET_PERMUTATIONS = 5</code>:</p>\n\n<pre><code>old version\nMinimum cube that has 5 permutations of its digits as cubes: 127035954683.\nTime: 0.020258699999999998 seconds.\nimproved version\nMinimum cube that has 5 permutations of its digits as cubes: 127035954683.\nTime: 0.018043399999999994 seconds.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T11:07:51.863", "Id": "226310", "ParentId": "226280", "Score": "0" } }, { "body": "<p>Several issues with your code:</p>\n\n<ol>\n<li>You are storing too much data.</li>\n<li>Inefficient usage of <code>Counter()</code></li>\n<li>Is <code>Counter()</code> ordered?</li>\n<li>You are needing to guess at upper bounds to the solution</li>\n<li>Your timing code is flawed.</li>\n</ol>\n\n<h2>Storing too much data</h2>\n\n<p>You store the cubes of 1 to <span class=\"math-container\">\\$10^4\\$</span>:</p>\n\n<pre><code>cubes = [str(number ** 3) for number in range(1, upper_bound)]\n</code></pre>\n\n<p>This is then used once as input to computing <code>sorted_cubes</code>, and then once to look up the value at a single index.</p>\n\n<p>When you get an index value from <code>sorted.cubes.index(sorted_cube)</code>, say 1000, you look up the value of <code>cubes[1000]</code>. The value at that location will be the string representation of the cube of the 1000th value, which by looking at the <code>range()</code> limits, we can conclude is the <span class=\"math-container\">\\$1001^3\\$</span>.</p>\n\n<p>So, you could instead:</p>\n\n<pre><code>return (sorted_cubes.index(sorted_cube) + 1) ** 3\n</code></pre>\n\n<p>Now that we've removed that pesky final lookup, <code>cubes</code> is only used once in the computation of <code>sorted_cubes</code>, so you can eliminate it entirely.</p>\n\n<pre><code>sorted_cubes = [''.join(sorted(str(number ** 3))) for number in range(1, upper_bound)]\n</code></pre>\n\n<p>Memory usage has been cut in half.</p>\n\n<h2>Inefficient usage of <code>Counter()</code></h2>\n\n<p>As mentioned by @Tweakimp in <a href=\"https://codereview.stackexchange.com/a/226310/100620\">their answer </a>, you're using <code>Counter()</code> poorly:</p>\n\n<pre><code>count = Counter()\nfor sorted_cube in sorted_cubes:\n count[sorted_cube] += 1\n</code></pre>\n\n<p>can be written as:</p>\n\n<pre><code>count = Counter(sorted_cubes)\n</code></pre>\n\n<h2>Is <code>Counter()</code> ordered?</h2>\n\n<p>Counter is a <code>dict</code> subclass, and as such on Python 3.6+, it maintains insertion order of the keys. But in earlier versions, the contents is unordered.</p>\n\n<p>This means, if two or more sets of cubic permutations of the required size are found, in Python 3.6+, the first cube added to the dictionary will be returned first in <code>count.items()</code>, and the correct <code>sorted_cube</code> will be used. This cannot be relied upon in prior versions of Python.</p>\n\n<h2>Guessing at the upper bounds</h2>\n\n<p>Where do you need to stop searching for 5 permutations? How about for 13 permutations? How about 20? Where did <code>UPPER_BOUND = 10 ** 4</code> come from? Did you just keep increasing it until it worked?</p>\n\n<p>You know there is an answer, so why not keep searching until one is found? Start at 1 digit cubes, and look for the required number of permutations. Then try 2 digit cubes, then 3 digit cubes, until an answer is found. The search space for each would be: <span class=\"math-container\">\\$\\sqrt[3]{10^{n}} \\le x \\lt \\sqrt[3]{10^{n+1}}\\$</span>, where <code>n</code> is the number of digits in the cube.</p>\n\n<h2>Your timing code is flawed.</h2>\n\n<p>This code:</p>\n\n<pre><code>START_TIME = perf_counter()\nMINIMUM_CUBE = ...\nprint(f\"... {MINIMUM_CUBE} ...\")\nprint(f'Time: {perf_counter() - START_TIME} seconds.')\n</code></pre>\n\n<p>produces different results on my computer depending on whether the cursor is at the top of a blank terminal window, or at the bottom long scroll of previous text. Avoid, as much as possible, including printing in timing results.</p>\n\n<pre><code>START_TIME = perf_counter()\nMINIMUM_CUBE = ...\nEND_TIME = perf_counter()\nprint(f\"... {MINIMUM_CUBE} ...\")\nprint(f'Time: {END_TIME - START_TIME} seconds.')\n</code></pre>\n\n<h2>Better implementation</h2>\n\n<p>Python 3.6+ only:</p>\n\n<pre><code>def cubic_permutations(required_permutations):\n min_cube = 1\n third = 1/3\n\n while True:\n max_cube = min_cube * 10 - 1\n lo = int(min_cube ** third)\n hi = int(max_cube ** third)\n\n cubes = [ \"\".join(sorted(str(x**3))) for x in range(lo, hi+1) ]\n count = Counter(cubes)\n digits = next((digits for digits, n in count.items()\n if n == required_permutations), None)\n\n if digits:\n root = cubes.index(digits) + lo\n return root ** 3\n\n min_cube *= 10\n</code></pre>\n\n<p>This code runs over 5 times faster than @Tweakimp's code for their 13 permutation code. No artificial upper bound is required. Memory usage is further reduced, since smaller subsets (from <code>lo</code> to <code>hi</code>) of <code>cubes</code> and <code>count</code> are in memory at once.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T20:47:42.097", "Id": "439802", "Score": "0", "body": "Nice. In each iteration both lo and hi are calculated, but lo is the hi of the last iterations low. Does this help us improve even more?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T22:21:02.380", "Id": "439816", "Score": "0", "body": "@Tweakimp Yes, that would remove one exponentiation from the loop, so should yield a slight speed improvement. I like the symmetry of the `lo` and `hi` calculation, and think it makes it slightly clearer what is going on, so I won't modify my answer to make that micro-improvement." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T19:07:25.967", "Id": "226335", "ParentId": "226280", "Score": "2" } } ]
{ "AcceptedAnswerId": "226335", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T18:34:56.250", "Id": "226280", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "programming-challenge" ], "Title": "Project Euler # 62 Cubic permutations in Python" }
226280
<p>I'm going through some code and trying to figure out how to get rid of duplicates from the following two methods. Both methods execute a simple login/register query to a local MySQL DB. I couldnt figure out a good design pattern to solve my problem, especially to get rid of the duplicate try-catch.</p> <p>Any advice?</p> <pre><code>public class DatabaseHandler { [...] public static boolean checkLogin(String username, String password) { Connection connection = createConenction(); PreparedStatement statement = null; String query = "select * from users where username = ? and password = ? "; try { statement = connection.prepareStatement(query); statement.setString(1, username); statement.setString(2, password); ResultSet result = statement.executeQuery(); return result.next(); //True if User exists } catch(SQLException e) { return false; } finally { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static boolean registerUser(String username, String password) { Connection connection = createConenction(); PreparedStatement statement = null; String query = "insert into users (username, password) values (?, ?)"; try { statement = connection.prepareStatement(query); statement.setString(1, username); statement.setString(2, password); statement.executeUpdate(); return true; } catch(SQLException e) { return false; } finally { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Funny coincidence, I just created the solution for your problem (<a href=\"https://codereview.stackexchange.com/questions/226191/php-one-time-prepared-statement-execution-function\">but in PHP</a>). The common thing here is the one-time use of a prepared statement, the difference is in the query string and arguments, so what you need is a function that accepts a query string, an argument determining what execution function to use (<code>executeQuery()</code> or <code>executeUpdate()</code>) and the parameters for the query:</p>\n\n<pre><code>// note: QueryType is an enum you should define\npublic static ResultSet query(String sql, QueryType queryType, Object... queryArgs){\n // ...\n}\n</code></pre>\n\n<p>Include the <code>try-catch</code> blocks in this function too of course, and return <code>null</code> when according to <code>queryType</code> there should be no results.</p>\n\n<p><strong>Note:</strong> I have no experience with database interaction with Java, so if there are only 2 different statement execution functions then you can use a boolean argument instead of the enum <code>QueryType</code>.</p>\n\n<p>Then your code could look like this:</p>\n\n<pre><code>public static boolean checkLogin(String username, String password) {\n String sql = \"select * from users where username = ? and password = ? \";\n ResultSet result = query(sql, QueryType.RETURN_RESULT, username, password);\n return result.next(); // true if User exists\n}\n</code></pre>\n\n<p>A note about your query string: I find it more convenient to use CAPS for keywords and lowercase text for names, it highlights the structure of the query.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T20:29:53.527", "Id": "439659", "Score": "0", "body": "thanks for your answer! Few things ive noticed when i tried to implement your solution: The `executeUpdate()` Method returns an Integer, so i cant have `ResultSet` as return type. I could however, use `executeQuery()` for all SQL-querys. Problem is, i would have to catch a `SQLException` in the `checkLogin` Method, because `result.next()` throws such. Kind of destroys the intend of the `query` Method. I thought about some kind of Interface/Abstract Class Pattern in the first place to solve this problem, but cant figure out. I will continue playing around with your suggestion tho!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T22:28:40.357", "Id": "439675", "Score": "0", "body": "@Clayy91 You could implement a `QueryResult` class with a `resultType` property that based on it you'll know what other property of that class contains the result (`int resultInt` or `ResultSet resultSet` for example) - or look straight at the property you expect to contain the result according to the type of query you made." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T19:10:29.833", "Id": "226282", "ParentId": "226281", "Score": "5" } }, { "body": "<p>You should really try to use a more modern approach to closeable resources. The try-with-resources statement has been introduced in Java 7 (2011).</p>\n\n<p>This gets rid of all the hocus-pocus around closing and nested exceptions for you. Trivial rewrite of the first function:</p>\n\n<pre><code>public static boolean checkLogin(String username, String password) {\n Connection connection = createConenction();\n String query = \"select * from users where username = ? and password = ? \";\n\n try (\n PreparedStatement statement = connection.prepareStatement(query)\n ) {\n statement.setString(1, username);\n statement.setString(2, password);\n ResultSet result = statement.executeQuery();\n return result.next(); //True if User exists\n } catch(SQLException e) {\n e.printStackTrace();\n return false;\n }\n}\n</code></pre>\n\n<p>Furthermore, if the method name <code>createConnection()</code> is not a lie, you should also close the connection. (Otherwise rename it to <code>getConnection()</code>):</p>\n\n<pre><code>public static boolean checkLogin(String username, String password) {\n String query = \"select * from users where username = ? and password = ? \";\n\n try (\n Connection connection = createConenction();\n PreparedStatement statement = connection.prepareStatement(query)\n ) {\n statement.setString(1, username);\n statement.setString(2, password);\n ResultSet result = statement.executeQuery();\n return result.next(); //True if User exists\n } catch(SQLException e) {\n e.printStackTrace();\n return false;\n }\n}\n</code></pre>\n\n<p>Apart from that little optimization in syntax, I do <em>not</em> think that the methods bear enough similarity to warrant a common abstraction. Writing and retrieving a line of data is a totally different business case and should be kept separate to be able to develop into different directions in the future.</p>\n\n<p>If you do not want to do all that basic handling of statements, result sets, rows, columns, rather look for a well established OR-mapping framework (e.g. JPA, Hibernate) instead of rolling your own.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T04:12:44.810", "Id": "226294", "ParentId": "226281", "Score": "2" } }, { "body": "<p>You must never store passwords as plain text in the database. Read an article about <em>password hashing</em> to avoid this mistake in the future.</p>\n\n<p>Make sure that you have a <em>unique index</em> on the <code>username</code> column. Otherwise it will be possible to create several users with the same username, and with equal or differing passwords.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T06:50:49.383", "Id": "226300", "ParentId": "226281", "Score": "4" } }, { "body": "<p>You can decide between to structural design patterns:</p>\n\n<ul>\n<li><a href=\"https://www.oodesign.com/template-method-pattern.html\" rel=\"nofollow noreferrer\">Template Method Pattern</a></li>\n<li><a href=\"https://www.oodesign.com/strategy-pattern.html\" rel=\"nofollow noreferrer\">Strategy Pattern</a></li>\n</ul>\n\n<p>I would go with the Template Method Pattern because you do not reuse the algorithm which is a benefit of the Strategy Pattern.</p>\n\n<p>In the first step we need to create an abstract class which has all the common code and a invocation of an abstract method where the algorithms distinguish. </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>abstract class PersistentAction {\n\n private final Connection connection;\n private final String username;\n private final String password;\n\n PersistentAction(Connection connection, String username, String password) { /* ... */ }\n\n final boolean execute(String query) {\n try(PreparedStatement statement = connection.prepareStatement(query)) {\n statement.setString(1, credential.getUsername());\n statement.setString(2, credential.getPassword());\n ResultSet result = statement.executeQuery();\n return evaluate(result);\n } catch(SQLException e) {\n return false;\n }\n }\n\n abstract boolean evaluate(Result result);\n}\n</code></pre>\n\n<p>After that we can create our algorithms which extends from our abstract class and implement the abstract method.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class HasNextEvaluation extends PersistentAction {\n\n @Override\n protected boolean evaluate(ResultSet result) {\n return result.next();\n }\n\n}\n\nclass ConstantTrue extends PersistentAction {\n\n @Override\n protected boolean evaluate(ResultSet result) {\n return true;\n }\n\n}\n</code></pre>\n\n<p>After the two steps we can achieve the following:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class DatabaseHandler {\n\n private static final Connection connection = createConenction();\n\n public static boolean checkLogin(String username, String password) {\n String query = \"select * from users where username = ? and password = ? \";\n\n PersistentAction action = new HasNextEvaluation(connection, username, password);\n return action.execute(query);\n }\n\n public static boolean registerUser(String username, String password) {\n String query = \"select * from users where username = ? and password = ? \";\n\n PersistentAction action = new ConstantTrue(connection, username, password);\n return action.execute(query);\n }\n}\n</code></pre>\n\n<p>From here I would improve the parameter list <code>checkLogin(String username, String password)</code> by using an <a href=\"https://refactoring.guru/introduce-parameter-object\" rel=\"nofollow noreferrer\">Paramter Object</a>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static boolean checkLogin(Credential credential) {\n /* ... */\n}\n</code></pre>\n\n<p>There are two benefits that are in my mind. The first is the short parameter list and the second one is that you could have multiple types of credentials:</p>\n\n<ul>\n<li>username and password</li>\n<li>email and password</li>\n<li>mobile number</li>\n<li>(even with biometrics ) </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T19:52:05.560", "Id": "439790", "Score": "0", "body": "Thank you, i was looking for a solution like this. But one thing i have noticed: What if i want to set an additional parameter for the `PreparedStatement`? Lets say i want to put an extra E-Mail textfield on the registration form, then i would have to add something like this `statement.setString(3, credential.getEmail());` in the `execute` method. This would result in false queries for those who only accepts two parameters. I hope im wrong because this is a cool solution, but to me this only seems to work as long as `query` stays identical." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T20:46:33.933", "Id": "439947", "Score": "0", "body": "Maybe you can create an abstract class `Query` and all your concrete query types that can interact with a `Credential`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:03:03.493", "Id": "226316", "ParentId": "226281", "Score": "1" } } ]
{ "AcceptedAnswerId": "226316", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T18:41:00.137", "Id": "226281", "Score": "5", "Tags": [ "java", "mysql", "authentication", "jdbc" ], "Title": "Java methods to add and authenticate users in MySQL" }
226281
<p>These are a few string routines (just the <code>mem*</code> ones). I've tried to optimize them the best I can without having them be too big, but I'm unsure if I've done a good job.</p> <p>I'd prefer size over speed unless it's just a few bytes, in which case that would be fine. I would also prefer not to sacrifice simplicity for speed.</p> <p><code>memchr.S</code> (<a href="https://stackoverflow.com/questions/57524415/is-cmovcc-considered-a-branching-instruction">related</a>):</p> <pre><code>.globl memchr memchr: mov %rdx, %rcx movzbl %sil, %eax repne scasb lea -1(%rdi), %rax test %rcx, %rcx cmove %rcx, %rax ret </code></pre> <p><code>memcmp.S</code>:</p> <pre><code>.globl memcmp memcmp: mov %rdx, %rcx repe cmpsb movzbl -1(%rdi), %eax movzbl -1(%rsi), %edx sub %edx, %eax ret </code></pre> <p><code>memcpy.S</code>:</p> <pre><code>.globl memcpy memcpy: mov %rdx, %rcx mov %rdi, %rax rep movsb ret </code></pre> <p><code>memmove.S</code>:</p> <pre><code>.globl memmove memmove: mov %rdx, %rcx mov %rdi, %rax cmp %rdi, %rsi jge 0f dec %rdx add %rdx, %rdi add %rdx, %rsi std 0: rep movsb cld ret </code></pre> <p><code>memrchr.S</code>:</p> <pre><code>.globl memrchr memrchr: mov %rdx, %rcx add %rdx, %rdi movzbl %sil, %eax std repne scasb cld lea 1(%rdi), %rax test %rcx, %rcx cmove %rcx, %rax ret </code></pre> <p><code>memset.S</code>:</p> <pre><code>.globl memset memset: mov %rdx, %rcx mov %rdi, %rdx movzbl %sil, %eax rep stosb mov %rdx, %rax ret </code></pre> <p>As usual for Stack Exchange sites, this code is released under CC/by-sa 3.0, but any future changes can be accessed <a href="https://github.com/JL2210/minilibc/tree/master/arch/x86_64/src/string/" rel="noreferrer">here</a>.</p>
[]
[ { "body": "<p>The code looks straight-forward and really optimized for size and simplicity.</p>\n\n<p>There's a small detail that I would change, though: replace <code>cmove</code> with <code>cmovz</code>, to make the code more expressive. It's not that \"being equal\" would be of any interest here, it's the zeroness of <code>%ecx</code> that is interesting.</p>\n\n<p>I like the omitted second <code>jmp</code> in memmove. It's obvious after thinking a few seconds about it.</p>\n\n<p><a href=\"https://stackoverflow.com/a/26104615\">According to this quote</a> it's ok to rely on the direction flag being always cleared.</p>\n\n<p>I still suggest to write a few unit tests to be on the safe side.</p>\n\n<p></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T22:57:28.570", "Id": "439682", "Score": "0", "body": "See my answer for a bug that I found on my own (found by writing unit tests)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T21:15:58.467", "Id": "226289", "ParentId": "226285", "Score": "5" } }, { "body": "<p>There's a bug in your code if <code>memchr</code> finds <code>%sil</code> in the last byte of <code>%rdi</code>; if <code>%rcx</code> tests to be zero and yet the byte has been found, it will incorrectly return zero.</p>\n\n<p>To fix that, do something like this:</p>\n\n<pre><code>.globl memchr\nmemchr:\n mov %rdx, %rcx\n movzbl %sil, %eax\n repne scasb\n sete %cl\n lea -1(%rdi), %rax\n test %cl, %cl\n cmovz %rcx, %rax\n ret\n</code></pre>\n\n<p>The same applies to <code>memrchr</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T22:41:55.923", "Id": "226291", "ParentId": "226285", "Score": "3" } }, { "body": "<p>In memmove you have the following:</p>\n\n<pre><code> cmp %rdi, %rsi\n jge 0f\n</code></pre>\n\n<p>(<code>cmp rsi, rdi</code> in Intel syntax I believe.) For rsi = 8000_0000_0000_0000h and rdi = 7FFF_FFFF_FFFF_FFFFh (we want to jump to make a forward move here) the signed-comparison conditional branch \"jump if greater or equal\" evaluates rsi as being \"less than\" rdi (rsi being a negative number in 64-bit two's complement while rdi is positive), so it doesn't jump and will make a backwards move. This is incorrect. You should use the equivalent unsigned branch \"jump if above or equal\", <code>jae</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T14:26:37.397", "Id": "439735", "Score": "1", "body": "Isn't this only an issue when a userspace address and kernelspace address are mixed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T14:27:25.067", "Id": "439736", "Score": "0", "body": "How likely is this in reality, though? The least you could expect is a segfault." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T14:29:09.610", "Id": "439737", "Score": "1", "body": "It may not be an issue depending on the operating system / address-space layout. However, if it does happen, then a wrong move direction (if the buffers are actually overlapping) will result in silently corrupting the destination buffer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-25T21:40:17.950", "Id": "446893", "Score": "0", "body": "This won't ever happen because addresses are only actually used up to 48 bits, much less than `0x8000000000000000`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T14:17:58.547", "Id": "226312", "ParentId": "226285", "Score": "1" } } ]
{ "AcceptedAnswerId": "226289", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T19:38:19.147", "Id": "226285", "Score": "7", "Tags": [ "strings", "assembly", "x86" ], "Title": "String routines" }
226285
<p>I was looking for a in-memory cache class, but couldn't find any in the .Net Core framework; luckily I found one already implemented <a href="https://stackoverflow.com/a/3719378/1642116">here</a>.</p> <p>I made some minor modifications to it and tried to make it thread safe. I believe I succeeded; but boy, did I do a sloppy job? Just throwing locks around and whatnot.</p> <p>I'd like to reduce thread contention and improve its performance. I considered using the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=netcore-2.2" rel="nofollow noreferrer">ReadWriterLockSlim</a>* class; one instances for the private dict and one for the private linked list.</p> <p>Can someone help me improve the performance of this class?</p> <p>For reference, at any given time there may be up to 40 threads hammering down this cache.</p> <p>I can't provide a real and concise usage example of this class right now; and I have not yet measured the following numbers, but I expect that most 4/5 cache accesses will result in a hit, and 1/5 in a miss followed by an add.</p> <p>An actual, yet codeless, example of usage of this class is to store the fitness of (immutable) individuals in a genetic algorithm. Since the individuals are immutable, their fitnesses stay the same as long as they live; thus I can compute it once and cache the result.</p> <p>The most up-to-date version of the code can be found in <a href="https://codereview.stackexchange.com/a/226336/56709">my own answer</a>; since I received such great feedback and couldn't choose a single answer as <em>the</em> answer, I decided to compile the suggestions, and post the resulting code, in a single new answer. This way I'm able to share the final result with the community, acknowledge the help and still keep the question / answers valid.</p> <p>I won't accept my answer as "the answer" because I don't want to fragsteal.</p> <pre><code>namespace Minotaur.Collections { using System; using System.Collections.Generic; /// &lt;remarks&gt; /// This class is based on the following inplementation https://stackoverflow.com/a/3719378/1642116 /// &lt;/remarks&gt; public sealed class LruCache&lt;K, V&gt; { private readonly int _capacity; private readonly Dictionary&lt;K, LinkedListNode&lt;LRUCacheEntry&lt;K, V&gt;&gt;&gt; _cacheMap; private readonly LinkedList&lt;LRUCacheEntry&lt;K, V&gt;&gt; _lruList = new LinkedList&lt;LRUCacheEntry&lt;K, V&gt;&gt;(); private readonly object _lock = new object(); /// &lt;remarks&gt; /// Providing the value 0 to &lt;paramref name="capacity"/&gt; /// effectively disables the cache. /// &lt;/remarks&gt; public LruCache(int capacity) { if (capacity &lt; 0) throw new ArgumentOutOfRangeException(nameof(capacity) + " must be &gt;= 0"); this._capacity = capacity; this._cacheMap = new Dictionary&lt;K, LinkedListNode&lt;LRUCacheEntry&lt;K, V&gt;&gt;&gt;(capacity: capacity); } /// &lt;remarks&gt; /// This method is thread-safe. /// &lt;/remarks&gt; public void Add(K key, V value) { if (key == null) throw new ArgumentNullException(nameof(key)); lock (_lock) { if (_capacity == 0) return; if (_cacheMap.Count &gt;= _capacity) RemoveLastRecentlyUsed(); var cacheItem = new LRUCacheEntry&lt;K, V&gt;(key, value); var node = new LinkedListNode&lt;LRUCacheEntry&lt;K, V&gt;&gt;(cacheItem); _lruList.AddLast(node); _cacheMap.Add(key, node); } } /// &lt;remarks&gt; /// This method is thread-safe. /// &lt;/remarks&gt; public bool TryGet(K key, out V value) { if (key == null) throw new ArgumentNullException(nameof(key)); lock (_lock) { var isCached = _cacheMap.TryGetValue(key, out var node); if (!isCached) { value = default; return false; } // Updating the last recently used thingy _lruList.Remove(node); _lruList.AddLast(node); value = node.Value.Value; return true; } } private void RemoveLastRecentlyUsed() { // Remove from lru list var node = _lruList.First; _lruList.RemoveFirst(); // Remove from cache _cacheMap.Remove(node.Value.Key); } private sealed class LRUCacheEntry&lt;KeyType, ValueType&gt; { public readonly KeyType Key; public readonly ValueType Value; public LRUCacheEntry(KeyType k, ValueType v) { Key = k; Value = v; } } } </code></pre> <p>}</p> <p>*then I remembered I don't really know how to use it correctly and would probably end up increasing contention...</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T22:24:01.797", "Id": "439817", "Score": "3", "body": "Regarding _\" I'm currently trying to implement an elegant and low-contention `TValue GetOrCreate(TKey key, Func<TValue> valueCreator)` function\"_, that's a lot harder than it sounds (if you want to guarantee a single call to `valueCreate`). See [this question](https://codereview.stackexchange.com/questions/225187/wrapping-imemorycache-with-semaphoreslim/225189#225189), and if I may suggest reading point 3 in [my answer](https://codereview.stackexchange.com/a/225189/39858). Also, you shouldn't change the code in the question: that would be welcome as a new question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T23:52:02.827", "Id": "439821", "Score": "0", "body": "I have not changed the code in the question; I created a answer with a compilation of the suggestions.\nThanks for links!\nAnd yes, I noticed how hard that is... And kinda gave up." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T10:30:42.000", "Id": "439874", "Score": "0", "body": "Sorry, I was referring to _\" will update thi question when I'm done.\"_: I didn't twig that edit was from before the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T13:42:55.843", "Id": "439888", "Score": "0", "body": "Small typo, it's “*least* recently used”, not “last”." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T14:12:48.847", "Id": "439889", "Score": "0", "body": "@KonradRudolph Thank you, some one else already pointed that old and I already fixed it." } ]
[ { "body": "<blockquote>\n<pre><code>/// &lt;remarks&gt;\n/// Providing the value 0 to &lt;paramref name=\"capacity\"/&gt;\n/// effectively disables the cache.\n/// &lt;/remarks&gt;\n</code></pre>\n</blockquote>\n\n<p><code>_capacity</code> is a <code>private readonly</code> field. I can't think of a situation where to instantiate an cache object with an immutable capacity set to <code>0</code> - hence useless, but you may have some idea with that?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> lock (_lock)\n {\n if (_capacity == 0)\n return;\n</code></pre>\n</blockquote>\n\n<p>As a consequence of the immutable <code>_capacity</code> initialized to <code>0</code>, the above check doesn't have to be protected by the <code>_lock</code> because the cache will never change.</p>\n\n<hr>\n\n<p>Because there is \"heavy\" manipulation of the cache in both <code>Add(...)</code> and <code>TryGet(...)</code>, I don't see any benefits of trying to use a reader/writer lock, so I would keep the use of <code>lock()</code> here. But other reviewers may have a more detailed view on that.</p>\n\n<hr>\n\n<p>You could consider to implement <code>IEnumerable&lt;T&gt;</code> or another iterator mechanism in order to make it possible to view the entire content of the cache.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T11:38:30.940", "Id": "439712", "Score": "2", "body": "The cache size is provided by a command line argument. If the user believes there is some error happening and that it may be fixed by \"disabling the cache\"; is can just pass the value 0 to --fitness-cache-size. I thought this was a elegant way to provide the \"disable cache\" functionality.\nI could have created another class \"NullCache\", created an interface ICache and, depending on the values of command line, instantiated a different implementation o ICache... But I the end I thought capacity=0 was good enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T11:46:02.313", "Id": "439714", "Score": "0", "body": "@Trauer: That seems as a valid explanation, but I would maybe handle error situations differently - but I lack informations about the concrete usage :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T11:48:11.073", "Id": "439716", "Score": "1", "body": "By the way, I totally agree with you. Originally (i.e. 2 days), the constructor did throw capacities <= 0. I changed it recently to make it easier (for me, as a programmer) to provide a way to the user disable the caching." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T06:35:08.887", "Id": "226299", "ParentId": "226287", "Score": "7" } }, { "body": "<blockquote>\n <p><em>..but I expect that most 4/5 cache accesses will result in a hit, and 1/5 in a miss followed by an add.</em></p>\n</blockquote>\n\n<p>You are not exposing your sync root <code>_lock</code>, meaning this class isn't thread-safe for consumers. The only meaningful way to use your class is as follows:</p>\n\n<pre><code>if (!cache.TryGet(key, out var value))\n{\n // watch out! one of the other threads may already have added the same value\n cache.Add(key, valueGenerator());\n}\n</code></pre>\n\n<p>This would be a better approach:</p>\n\n<pre><code>lock (cache.SyncRoot) \n{\n if (!cache.TryGet(key, out var value))\n {\n cache.Add(key, valueGenerator());\n }\n}\n</code></pre>\n\n<p>Even better would be to provide a <code>GetOrAdd</code> method:</p>\n\n<pre><code>var cachedResultRetrieved = cache.GetOrAdd(key, out var value, valueGenerator);\n</code></pre>\n\n<p>You may also argue whether using a global lock is the most efficient way of handling thread-safety here. I believe using <code>ConcurrentDictionary</code> would solve most threading issues. The only atomic operation I see is this one:</p>\n\n<blockquote>\n<pre><code>_lruList.Remove(node);\n_lruList.AddLast(node);\n</code></pre>\n</blockquote>\n\n<p>This would still require some locking mechanism. I don't think it's that important that both the <code>cache</code> and the <code>lrulist</code> are updated in the same lock. It's not crucial that the <strong>exact</strong> oldest item gets deleted.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T11:43:30.407", "Id": "439713", "Score": "2", "body": "Woah, you guys really know what you are doing. Very nicely observed issue and proposed solution; I'm going with the GetOrAdd approach. Later on I'll benchmark a Concurrenct dict versus a Global lock. Thanks for all the suggestions!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T08:31:16.650", "Id": "226304", "ParentId": "226287", "Score": "11" } }, { "body": "<p>This is a neat little implementation. It's nice that <code>LruCacheEntry</code> is a private inner class. It does indeed look to be thread-safe in its current state.</p>\n\n<hr />\n\n<p>When calling <code>Add</code>, if the <code>key</code> is already present, then a new node is added to <code>LruList</code> before the code crashes because the key is already present in the dictionary. This means you could end up with an ever growing <code>LruList</code>, which would be bad.</p>\n\n<p>You should probably check if <code>key</code> is already present and decide what to do after that... you might want to replace the value, or do nothing, or... (consult dfhwze's answer)</p>\n\n<hr />\n\n<p>Generally type-parmeters follow the pattern <code>TName</code> in .NET: in you case I would expect <code>TKey</code> and <code>TValue</code>. Whatever you do, you should be consistent between classes, but you'd be better off just removing <code>&lt;KeyType, ValueType&gt;</code>, since <code>LRUCacheEntry</code> already knows about <code>K</code> and <code>V</code>. <code>LRUCacheEntry</code> should be <code>LruCacheEntry</code> to be consistent with <code>LruCache</code> and the .NET naming conventions.</p>\n\n<hr />\n\n<p>I would attach an <code>else</code> to <code>if (!isCached)</code> so that the control flow is clearer and the static checker can tell you when you accidently comment out <code>return false</code>.</p>\n\n<hr />\n\n<p>I'm always glad to see inline documentation of the public (and private) API, but the comments here are really not very helpful. </p>\n\n<p>Some of your comments could generally be better:</p>\n\n<ul>\n<li><p>Spelling error: \"inplementation\"</p></li>\n<li><p>\"Thingy\" is a tad vague</p></li>\n<li><p>It is not documented that <code>null</code> is an invalid key</p></li>\n<li><p>There is nothing explaining that it is a Least-Recently User eviction policy (<code>Lru</code> wouldn't cut it for me)</p></li>\n<li><p>I'd probably want a comment attached to the <code>private</code> method indicating the lock must be taken. An assert would be even better:</p>\n\n<pre><code>Debug.Assert(Monitor.IsEntered(_lock));\n</code></pre></li>\n</ul>\n\n<hr />\n\n<p>As Henrik Hansen says, you can't really avoid a mutex with this implementation, but you may be able to reduce the amount of stuff that is inside the <code>lock</code>.</p>\n\n<p>One possible option could be to use a <code>ConcurrentDictionary</code>, as dfhwze has suggested: when you try to get a value, you ask the dictionary. If it finds it, <em>then</em> you take the lock and update the linked list (you don't take a lock if it isn't present, and you hold the lock for less time): you need to check your node is still in the inked list, because it might been removed before you took the lock, because it may have been replaced already.</p>\n\n<p>When adding, you perform a check (as mentioned above), and if a change needs to be made, you again take the lock, perform the check again, and perform the add (update the list and dictionary) inside the lock if you need to. All this effort may or may not reduce the time spent in the lock, and so the amount of contention.</p>\n\n<p>Unless you use a linked-list designed for concurrent use, I don't think you are going to be able to avoid a mutex when modifying <code>_lruList</code> without fundamentally changing how the cache works.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T11:46:24.837", "Id": "439715", "Score": "0", "body": "Thanks for pointing out the bug in Add, I hadn't noticed that one!\nThanks for noting the naming convention violation (already fixed that one).\nAbout the comments; they are jus place holders while I'm still poking with the mechanics off the class; I'll make'em far more descriptive when I'm fully satisfied with the implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T11:56:31.337", "Id": "439719", "Score": "1", "body": "You can handle the problem in `Add(...)` by using the `key` indexer instead of the `Add(key, value)` on the dictionary `_cacheMap`: `_cacheMap[key] = value;`. This will not throw but just replace if the key exists." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T12:00:52.830", "Id": "439721", "Score": "1", "body": "@HenrikHansen that will still cause the list to inflate, as the old node will only be removed when it reaches the end of `_lruList`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T12:01:48.507", "Id": "439723", "Score": "0", "body": "@VisualMelon: Stupid me, of course!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T08:35:15.540", "Id": "226305", "ParentId": "226287", "Score": "9" } }, { "body": "<h3>Cosmetics</h3>\n\n<p>You can simplify your code by removing the generic arguments from <code>LRUCacheEntry</code>. Since it's a nested class it can use its parent class' types without redefining them. You could also make it a <code>readonly struct</code> and save a couple of instances. </p>\n\n<pre><code>private readonly struct LRUCacheEntry\n{\n public readonly TKey Key;\n public readonly TValue Value;\n\n public LRUCacheEntry(TKey k, TValue v)\n {\n Key = k;\n Value = v;\n }\n\n public static implicit operator TValue(LRUCacheEntry entry) =&gt; entry.Value;\n}\n</code></pre>\n\n<p>If you add to it an <code>implicit operator</code> to <code>TValue</code>, you can simplify this weird looking line </p>\n\n<blockquote>\n<pre><code>value = node.Value.Value;\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code> value = node.Value;\n</code></pre>\n\n<h3><code>RemoveLastRecentlyUsed</code></h3>\n\n<blockquote>\n<pre><code> if (_cacheMap.Count &gt;= _capacity)\n RemoveLastRecentlyUsed();\n</code></pre>\n</blockquote>\n\n<p>I find you should move the <code>if</code> to <code>RemoveLastRecentlyUsed</code> and let it handle everthing about its job of removing items. Currently the logic is two places.</p>\n\n<h3>Disabling the cache</h3>\n\n<p>You should give the <code>0</code> a name like <code>CacheDisabled</code> but creating another class doing nothing would be much better than then tricking this one into something <em>unnatural</em>.</p>\n\n<p>At least you should expose the <code>Capacity</code> or another property like <code>bool Enabled</code> so that the user can see what kind of cache he is using. Might also be useful for debugging. Otherwise you need to look into its private state.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T13:06:11.143", "Id": "226311", "ParentId": "226287", "Score": "7" } }, { "body": "<p>Since I couldn't choose a single answer as <em>the answer</em>, I decided to compilte all the suggestions and comments made and show how the final class(es) looks. It still doesn't use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=netcore-2.2\" rel=\"nofollow noreferrer\">ReaderWriterLockSlim</a>, but the code is far cleaner and contains one or two less bugs.\nMaybe the final results can be used by others :) thanks to everyone for the feedback, I love this community.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/754233/is-it-there-any-lru-implementation-of-idictionary/3719378#3719378\">Initial implementation</a> by <a href=\"https://stackoverflow.com/users/448597/martin\">Martin</a>, from StackOverflow.</p>\n\n<p>Notable changes, in no specific order:</p>\n\n<ul>\n<li>Exposed SyncRoot [dfhwze]</li>\n<li>Add AddOrCreate method [dfhwze]</li>\n<li>Fixed issue in method `Add(...) [VisualMelon]</li>\n<li>Improved naming of typ-parameters (T -> TKey, V -> TValue) [VisualMelon]</li>\n<li>Added safety measures / documentation code in private methods, e.g. <code>Debug.Assert(Monitor.IsEntered(_lock))</code> [VisualMelon]</li>\n<li>Added <code>else</code> to <code>if</code> statements [VisualMelon]</li>\n<li>Improved documentation and fixed typos [VisualMelon]</li>\n<li>Created NullCache class and ICache interface [Henrik Hansen]</li>\n<li>Moved \"should remove item logic\" to method <code>RemoveLeastRecentlyUsedIfNecessary</code> method [3chb0t]</li>\n<li>Sexified of the code by removing generic arguments from LruCacheEntry [3chb0t]</li>\n</ul>\n\n<p>Final results, LruCache.cs:</p>\n\n<pre><code>namespace Minotaur.Collections {\n using System;\n using System.Collections.Generic;\n using System.Diagnostics;\n using System.Threading;\n\n /// &lt;summary&gt;\n /// This class is in-memory, thread-safe cache.\n /// The evicition policy is the Least Recently Used (LRU),\n /// see https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU).\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// This class is based on the following implementation https://stackoverflow.com/a/3719378/1642116\n /// &lt;/remarks&gt;\n public sealed class LruCache&lt;TKey, TValue&gt;: ICache&lt;TKey, TValue&gt; {\n private readonly int _capacity;\n private readonly Dictionary&lt;TKey, LinkedListNode&lt;LruCacheEntry&gt;&gt; _cacheMap;\n private readonly LinkedList&lt;LruCacheEntry&gt; _lruList = new LinkedList&lt;LruCacheEntry&gt;();\n public readonly object SyncRoot = new object();\n\n /// &lt;summary&gt;\n /// The constructor of the class.\n /// &lt;paramref name=\"capacity\"/&gt; must be &gt;= 0.\n /// If you want to disable the caching of the system,\n /// consindering using the NullCache class.\n /// &lt;/summary&gt;\n public LruCache(int capacity) {\n if (capacity &lt;= 0)\n throw new ArgumentOutOfRangeException(nameof(capacity) + \" must be &gt; 0\");\n\n this._capacity = capacity;\n this._cacheMap = new Dictionary&lt;TKey, LinkedListNode&lt;LruCacheEntry&gt;&gt;(capacity: capacity);\n }\n\n /// &lt;summary&gt;\n /// Adds the pair (&lt;paramref name=\"key\"/&gt;, &lt;paramref name=\"value\"/&gt;)\n /// to the cache.\n /// If the key is already in the cache, an exception is thrown.\n /// &lt;remarks&gt;\n /// This method is thread-safe.\n /// &lt;/remarks&gt;\n public void Add(TKey key, TValue value) {\n if (key == null)\n throw new ArgumentNullException(nameof(key));\n\n // We are doing as much work as we can outside of the lock\n var cacheItem = new LruCacheEntry(key, value);\n var lruNode = new LinkedListNode&lt;LruCacheEntry&gt;(cacheItem);\n\n lock (SyncRoot) {\n if (!_cacheMap.ContainsKey(key)) {\n _cacheMap.Add(key: key, value: lruNode);\n RemoveLeastRecentlyUsedIfNecessary();\n } else {\n throw new InvalidOperationException(\"The value is already in the cache.\");\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Tries to get the value associated with &lt;paramref name=\"key\"/&gt;.\n /// \n /// If the key is stored in the cache,\n /// &lt;paramref name=\"value\"/&gt; is set to the value associated with it,\n /// the key's \"least recently used\" data is updated,\n /// and the method returns true.\n /// \n /// If the key is not stored in the cache,\n /// &lt;paramref name=\"value\"/&gt; is set to default\n /// and the method returns false.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// This method is thread-safe.\n /// &lt;/remarks&gt;\n public bool TryGet(TKey key, out TValue value) {\n if (key == null)\n throw new ArgumentNullException(nameof(key));\n\n lock (SyncRoot) {\n var isCached = _cacheMap.TryGetValue(key, out var lruNode);\n\n if (!isCached) {\n value = default;\n return false;\n } else {\n UpdateUsage(lruNode);\n value = lruNode.Value.Value;\n return true;\n }\n }\n }\n\n /// &lt;summary&gt;\n /// Tries to get the value associated with &lt;paramref name=\"key\"/&gt;.\n /// If the value is not stored in the cache,\n /// the function &lt;paramref name=\"valueCreator\"/&gt; \n /// is called and the result is stored in the cache.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// This method is thread-safe.\n /// &lt;/remarks&gt;\n public TValue GetOrCreate(TKey key, Func&lt;TValue&gt; valueCreator) {\n if (key == null)\n throw new ArgumentNullException(nameof(key));\n if (valueCreator is null)\n throw new ArgumentNullException(nameof(valueCreator));\n\n // We take the lock for a long time,\n // but we must ensure that the entire operation is atomic.\n // Maybe using System.Threading.ReaderWriterLockSlim and some\n // black magic we could reduce contention, but aint that \n // high level of a wizard\n\n lock (SyncRoot) {\n var isCached = _cacheMap.TryGetValue(key: key, value: out var lruNode);\n if (isCached) {\n UpdateUsage(lruNode);\n return lruNode.Value.Value;\n }\n\n // I wish this could be called outside the lock :(\n var value = valueCreator();\n\n var cacheEntry = new LruCacheEntry(\n key: key,\n valeu: value);\n\n lruNode = new LinkedListNode&lt;LruCacheEntry&gt;(cacheEntry);\n\n _cacheMap.Add(key: key, value: lruNode);\n RemoveLeastRecentlyUsedIfNecessary();\n\n return value;\n }\n }\n\n private void UpdateUsage(LinkedListNode&lt;LruCacheEntry&gt; node) {\n Debug.Assert(Monitor.IsEntered(SyncRoot));\n\n _lruList.Remove(node);\n _lruList.AddLast(node);\n }\n\n private void RemoveLeastRecentlyUsedIfNecessary() {\n Debug.Assert(Monitor.IsEntered(SyncRoot));\n\n if (_cacheMap.Count &lt; _capacity)\n return;\n\n var node = _lruList.First;\n _lruList.RemoveFirst();\n _cacheMap.Remove(node.Value.Key);\n }\n\n private sealed class LruCacheEntry {\n public readonly TKey Key;\n public readonly TValue Value;\n\n public LruCacheEntry(TKey key, TValue valeu) {\n Key = key;\n Value = valeu;\n }\n }\n }\n}\n</code></pre>\n\n<p>NullCache.cs</p>\n\n<pre><code>namespace Minotaur.Collections {\n using System;\n\n /// &lt;summary&gt;\n /// This class is used to effectively disable caching\n /// in place where a ICache can be used.\n /// &lt;/summary&gt;\n public sealed class NullCache&lt;TKey, TValue&gt;: ICache&lt;TKey, TValue&gt; {\n\n /// &lt;summary&gt;\n /// Does nothing.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// &lt;paramref name=\"key\"/&gt; still can't be null.\n /// &lt;/remarks&gt;\n public void Add(TKey key, TValue value) {\n if (key == null)\n throw new ArgumentNullException(nameof(key));\n }\n\n /// &lt;summary&gt;\n /// Always assigns default do &lt;paramref name=\"value\"/&gt; and returns false.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// &lt;paramref name=\"key\"/&gt; still can't be null.\n /// &lt;/remarks&gt;\n public bool TryGet(TKey key, out TValue value) {\n if (key == null)\n throw new ArgumentNullException(nameof(key));\n\n value = default;\n return false;\n }\n\n /// &lt;summary&gt;\n /// Invokes &lt;paramref name=\"valueCreator\"/&gt; and returns its output.\n /// &lt;/summary&gt;\n /// &lt;remarks&gt;\n /// Neither &lt;paramref name=\"key\"/&gt; nor &lt;paramref name=\"valueCreator\"/&gt; can be\n /// null.\n /// &lt;/remarks&gt;\n public TValue GetOrCreate(TKey key, Func&lt;TValue&gt; valueCreator) {\n if (key == null)\n throw new ArgumentNullException(nameof(key));\n if (valueCreator is null)\n throw new ArgumentNullException(nameof(valueCreator));\n\n return valueCreator();\n }\n }\n}\n</code></pre>\n\n<p>ICache.cs</p>\n\n<pre><code>namespace Minotaur.Collections {\n using System;\n\n public interface ICache&lt;TKey, TValue&gt; {\n void Add(TKey key, TValue value);\n bool TryGet(TKey key, out TValue value);\n TValue GetOrCreate(TKey key, Func&lt;TValue&gt; valueCreator);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T20:03:56.210", "Id": "439791", "Score": "3", "body": "A self-answer with a summary of changes you've made, and which input you appreciated from other answers, is a good way to sum it all up. Note, though, that if you want this code reviewed, you should ask a follow-up question, and we'll be happy to review that question as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T20:08:51.067", "Id": "439792", "Score": "1", "body": "I was pretty satisfied with the code, and I didn't think it would benefit from another round of review; but now that you commented I'm not so sure anymore, hehe.\nBut yeah, I wanted to share the final result with the community, but without modifying the question and making the answers nonsensical.\nI don't think I'll choose this as an answer because I don't want to \"frag-steal\". But anyway, here what we produced :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T19:57:51.253", "Id": "226336", "ParentId": "226287", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T20:54:47.500", "Id": "226287", "Score": "12", "Tags": [ "c#", "performance", "multithreading", ".net-core" ], "Title": "Reducing contention in thread-safe LruCache" }
226287
<blockquote> <p>Write a program that should read a file formatted <strong>strictly</strong> like this below:</p> <pre><code>$ cat sample bingo=2 bingo2=939 bingo3=text </code></pre> <p>The left and right side of <code>=</code> are consecutively parameter name and its respective value. The values can be integer or strings. Each parameter is separated by a newline. The parameter name and its value will not be more than 127 bytes.</p> </blockquote> <p>This program is fed an input search token, and if found, <code>parse_param_file()</code> will fill the input arguments with string or integer value.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #define TEXT "sample" /* * Function: parse_param_file * Arguments: * token - param name that needs to be looked up * buf - buffer for string value. Pass NULL if unwanted * buf_int - buffer for integer value. Pass NULL if unwanted * filename - string formatted path to the file */ int parse_param_file(const char *token, char **buf, int *buf_int, const char *filename) { if (!token || (!buf &amp;&amp; !buf_int)) { printf("%s: invalid args\n", __FUNCTION__); return 1; } FILE *f = fopen(filename, "r"); if (f == NULL) { printf("%s: %s not found\n", __FUNCTION__, filename); return 1; } char *left = malloc(128); char *right = malloc(128); char *dlim_ptr, *end_ptr; char fbuf[256]; while (fgets(fbuf, 256, f)) { dlim_ptr = strstr(fbuf, "="); end_ptr = strstr(dlim_ptr, "\n"); strncpy(left, fbuf, dlim_ptr - fbuf); strncpy(right, dlim_ptr + 1, end_ptr - dlim_ptr - 1); if (strcmp(left, token) == 0) { /* Param found */ if (buf != NULL) *buf = strdup(right); if (buf_int != NULL) *buf_int = atoi(right); fclose(f); free(left); free(right); return 0; } } fclose(f); printf("%s: Param not found in %s\n", __FUNCTION__, filename); free(left); free(right); return 1; } /* How to use parse_param_file() */ int main(void) { char *buf = malloc(128); int val = 0; /* Test 1 */ if (parse_param_file("bingo2", NULL, NULL, TEXT)) fprintf(stderr, "parse_param_file() failed\n"); printf("buf : %s\n", buf); printf("int : %d\n", val); /* Test 2 */ if (parse_param_file("bingo3242", NULL, &amp;val, TEXT)) fprintf(stderr, "parse_param_file() failed\n"); printf("buf : %s\n", buf); printf("int : %d\n", val); /* You must clear *buf and val if you want to reuse them as args again */ /* Test 3 */ if (parse_param_file("bingo3", &amp;buf, &amp;val, TEXT)) fprintf(stderr, "parse_param_file() failed\n"); printf("buf : %s\n", buf); printf("int : %d\n", val); free(buf); return 0; } </code></pre>
[]
[ { "body": "<h3>Interface</h3>\n<p>I'm not overly fond of the interface you've defined to the function. I think trying to combine reading integers and reading strings into a single function makes it more difficult to use. For most C code, I think the old guiding principle of UNIX (&quot;do one thing, and do it well&quot;) provides excellent guidance. As such, I'd probably have two separate functions, one for reading a string, the other for reading a number.</p>\n<p>I haven't tested it to be sure, but at first glance it also looks like if you ask to read a number, it does a poor job of signalling failure. For example, if your file has: <code>foo=0</code> and you try to read <code>foo</code> as a number, it'll set the number to 0, and return 0. But if the file contains <code>foo=Joe</code> instead, it looks to me like it'll do exactly the same.</p>\n<p>I'd prefer that if it couldn't convert the rest of the line after the <code>=</code> to a number that it return 1 to indicate that it has failed.</p>\n<h3>Memory Allocation</h3>\n<p>Since you only use our <code>left</code> and <code>right</code> inside of your function, and free them again before returning, there's probably no need to allocate them on the heap. You can just allocate them as local arrays, and use them. The obvious exception to this would be if you were targeting a tiny micro-controller that might well have less than 256 bytes available on the stack. In that case, however, you usually won't have a file system either, so the entire function becomes irrelevant.</p>\n<h3>Standard Library</h3>\n<p>I think judicious use of <code>fscanf</code> can simplify the code quite a bit.</p>\n<p>For reading a string, it seems like the obvious interface would be to just return the value part of the pair, and if it's not found, return a NULL pointer:</p>\n<pre><code>char *read_string(FILE *file, char const *desired_name) { \n char name[128];\n char val[128];\n\n while (fscanf(file, &quot;%127[^=]=%127[^\\n]%*c&quot;, name, val) == 2) {\n if (0 == strcmp(name, desired_name)) {\n return strdup(val);\n }\n }\n return NULL;\n}\n</code></pre>\n<p>When reading a number, we probably need something closer to your original interface, with a return value to indicate success/failure, and receive a pointer to an int where we write the value (if it's found):</p>\n<pre><code>int read_int(FILE *file, char const *desired_name, int *ret) {\n char *temp = read_string(file, desired_name);\n\n char *stop;\n *ret = strtol(temp, &amp;stop, 10);\n int ret_val = stop == NULL || *stop != '\\0';\n free(temp);\n return ret_val;\n}\n</code></pre>\n<p>Note that as it stands right now, the return value reflects converting the <em>entire</em> remainder of the line (everything after the <code>=</code>) to the desired number. If part of it can be converted, that part will be written to the destination, but the return will still indicate failure. For example, if you had <code>foo=1234abcd</code>, attempting to read <code>foo</code> as a number would give you <code>1234</code>, but return 1 because the <code>abcd</code> part couldn't be converted.</p>\n<p>It would also be possible to simply ignore any trailing garbage, so <code>foo=1234abcd</code> would read the <code>1234</code> part, and return 0 to signal success:</p>\n<pre><code>int read_int(FILE *file, char const *desired_name, int *ret) {\n char *temp = read_string(file, desired_name);\n\n char *stop;\n *ret = strtol(temp, &amp;stop, 10);\n int ret_val = stop == temp;\n free(temp);\n return ret_val;\n}\n</code></pre>\n<p>In this case, we just need to check that at least one character was converted, in which case <code>stop</code> will have be advanced at least one character after the input.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T09:55:17.120", "Id": "439706", "Score": "0", "body": "Given that both functions will be used together, the function `read_int` could accept the value string as a parameter, and therefore we have one less strdup&free." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T18:15:20.917", "Id": "439783", "Score": "0", "body": "@CacahueteFrito: It could, but since the original returned a string allocated with `strdup`, I treated that as a requirement. But you're right, that it's probably worth some thought whether to treat it as a requirement, or require the caller to pass the address/size of a buffer instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T09:27:01.427", "Id": "439872", "Score": "0", "body": "\"*The obvious exception to this would be if you were targeting a tiny micro-controller that might well have less than 256 bytes available on the stack*\" -- in that case you probably won't have a heap either, and those buffers will be statically allocated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T12:09:40.307", "Id": "440006", "Score": "1", "body": "`stop == NULL` in `int ret_val = stop == NULL || *stop != '\\0';` is strange as it is never true without UB. I suspect you wanted `int ret_val = stop ==temp || *stop != '\\0';`. You may want to look into `errno` and truncation of `long` into `int` too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T12:28:50.250", "Id": "440007", "Score": "1", "body": "`return stop == temp;` is UB. Do not use `temp` after `free(temp);` - even if to just compare pointers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T17:44:55.487", "Id": "440058", "Score": "0", "body": "@chux: I've heard that before, but have yet to find or see anybody else find a normative reference for the claim. Appendix J.2 does say (more or less) the same as you have, but J.2 itself is informative, not normative, and gives §7.22.3 as the supposed normative reference--but although I've reread §7.22.3 dozens of times over the years, I've yet to find anything there that states, implies, or even hints that this is actually true. Dereferencing the pointer after freeing is clearly UB--but comparing the value...nothing normative seems to support the claim." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T02:56:41.567", "Id": "440121", "Score": "1", "body": "@JerryCoffin C11 6.2.4 has \"The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.\", so after `free()`, the value is _indeterminate_ (either an unspecified value or a trap representation). `stop == temp` after `free(temp)` can lead to a trap - e.g. \"no further operations\". Perhaps not UB, yet still better to avoid a potential trap and perform any compare before `free(temp)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T09:08:25.193", "Id": "440137", "Score": "1", "body": "@chux: Fair enough. Thanks." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T06:20:45.287", "Id": "226297", "ParentId": "226293", "Score": "10" } }, { "body": "<p>Your program crashes when it reads a line from the parameters file that doesn't contain an <code>=</code> sign.</p>\n\n<p>The name of the macro <code>TEXT</code> is misleading. It doesn't contain a text but a filename.</p>\n\n<p>Whenever you output an error message, it belongs on <code>stderr</code> instead of <code>stdout</code>. To do this, replace <code>printf(</code> with <code>fprintf(stderr,</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T07:05:27.220", "Id": "226301", "ParentId": "226293", "Score": "6" } }, { "body": "<h2><code>__func__</code></h2>\n\n<p>Unlike <code>__FUNCTION__</code>, <code>__func__</code> is standard C since C99. Some compilers might not support C99 and therefore in those compilers you have to use whatever they provide, but if your compiler supports C99, you should use <code>__func__</code>. If you have a crappy compiler, think about using a better one.</p>\n\n<hr>\n\n<h2>magic numbers</h2>\n\n<p><a href=\"https://stackoverflow.com/q/47882/6872717\">What is a magic number, and why is it bad?</a></p>\n\n<p>Don't use any numbers different than 0, 1, or 2 in your code. The only place where numbers deserve to go is in constant macros like this:</p>\n\n<pre><code>#define MAX_STRLEN (127)\n</code></pre>\n\n<p>Note: As Roland Illig pointed out in his comment, this is still a magic number, but it is already much better than the alternative. To improve it, a comment about why 127 and not another number, would be very appropriate just above the definition.</p>\n\n<hr>\n\n<h2><code>BUFSIZ</code></h2>\n\n<p>When you create a buffer, and you don't need a strict size (when you need a very large buffer, or you are short of memory), you can use <code>BUFSIZ</code> which is defined in <code>&lt;stdio.h&gt;</code>, which is around 1KiB~4KiB.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n...\n\nchar fbuf[BUFSIZ];\n</code></pre>\n\n<hr>\n\n<h2><code>ARRAY_SIZE()</code></h2>\n\n<p>Use this macro wherever possible.</p>\n\n<p>Typically defined as: <code>#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))</code></p>\n\n<p>It makes your code safer:</p>\n\n<p>If you ever change the size of an array, it will be updated, while if you hardcoded the size as a magic number, you will have to update every number, and if you hardcoded it as a macro (sometimes, ARRAY_SIZE can't be used, and this is the only possibility), if you change the name of the macro, you will have to update it.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))\n\n...\n\nchar fbuf[BUFSIZ];\nwhile (fgets(fbuf, ARRAY_SIZE(fbuf), f)) {\n</code></pre>\n\n<p>Note: Never use <code>sizeof</code> where <code>ARRAY_SIZE</code> should be used. It's very unsafe, because if an array ever changes to be a pointer (for example if it is a function parameter), ARRAY_SIZE will raise a warning on recent compilers, while sizeof will give wrong results, and produce hard to find bugs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T12:26:00.177", "Id": "439724", "Score": "1", "body": "MAX_STRLEN is still as magic as 127. From the context it is clear that the 127 is a maximum. The question remains: of which string? Every string in the whole program? Inventing an unexpressive name for a magic number doesn't make it less magic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T13:41:49.947", "Id": "439730", "Score": "0", "body": "@RolandIllig Above such things, a comment would be appropriate. But magic numbers are better kept together in the beginning of the file. I wrote that name, because in this simple program, every processed string (not the fgets buffer, for which I would use BUFSIZ) seems to use 127. One of the main advantages is that you don't repeat 127 in all the code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T10:08:54.363", "Id": "226308", "ParentId": "226293", "Score": "7" } }, { "body": "<p>Well I don't know exactly what <code>strstr</code> does, but I would've used <code>strtok</code> (string tokenizer) somewhere in the process as its purpose is to find delimiters and split strings there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T18:26:02.147", "Id": "439785", "Score": "3", "body": "Here you have what `strstr()` does: [`man strstr`](http://man7.org/linux/man-pages/man3/strstr.3.html): It searches a substring in a string." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:05:30.837", "Id": "226326", "ParentId": "226293", "Score": "-3" } }, { "body": "<p>Ok, first some comments. I’ll add code if you want - just can’t do it effectively from my phone.</p>\n\n<ol>\n<li><p>Basically any string function that doesn’t take the length of the string is problematic. It has the potential to read beyond the end of the buffer. atoi should be replaced with strtol, strcmp with strncmp, ...</p>\n\n<ol start=\"2\">\n<li>Allocating fixed sizes of memory, just to release the fixed sizes of memory is pointless. Don’t do that. Now having the allocation and the free in the same function is very beneficial, do that over allocating something buried in a function and remembering to deallocate it later.</li>\n</ol></li>\n<li><p>The standard string library is very slow. It is ok for very simple things, as long as you only need to do them once. If you need to do this faster, you might want to use a tool like lex or flex to do so. You can also write your own lexical scanner based on deterministic automata - it’s a good exercise, but flex is much easier.</p></li>\n</ol>\n\n<p>Ok, I’ll have to fix my formatting later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T16:43:33.220", "Id": "439923", "Score": "0", "body": "Links to \"lex\" or \"flex\" would be appropriate. Is that a program or is it a library that can be used from C?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T22:25:56.623", "Id": "440100", "Score": "1", "body": "@CacahueteFrito Lex and flex are programs that generate lexical analyzers. The programs generated are state machines using tables. https://en.wikipedia.org/wiki/Lex_(software) https://www.gnu.org/software/flex/" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T09:59:48.070", "Id": "226372", "ParentId": "226293", "Score": "1" } }, { "body": "<p><strong>Undefined behavior</strong></p>\n\n<p><code>strcmp(left, token)</code>, <code>strdup(right)</code> are UB as <code>left, right</code> do not certainly point to <em>strings</em> (<em>null character</em> terminated arrays).</p>\n\n<p>Could replace </p>\n\n<pre><code>strncpy(left, fbuf, dlim_ptr - fbuf);\n</code></pre>\n\n<p>with below to insure null termination.</p>\n\n<pre><code>sprintf(left, \"%.*s\", (int) (dlim_ptr - fbuf), fbuf);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T13:32:16.920", "Id": "440016", "Score": "0", "body": "Another replacement to strncpy could be `strscpy`, which should be written because it's not even an extension." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:55:25.173", "Id": "440045", "Score": "0", "body": "@CacahueteFrito `strscpy()` is a reasonable alternative yet `strscpy()` is not part of the standard C library. I'd classify it as an extension to standard C." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T17:46:22.150", "Id": "440059", "Score": "0", "body": "A great extension that no compiler or library provides. AFAIK, only the Linux kernel has it :(" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T12:21:42.327", "Id": "226415", "ParentId": "226293", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T01:01:29.770", "Id": "226293", "Score": "11", "Tags": [ "c", "parsing", "file", "configuration" ], "Title": "Parse a simple key=value config file in C" }
226293
<p>I have been trying learn OOP lately, and have made a simple program that simulates some sort of drive thru experience using a 9 digit keypad to add, delete, and pay for items ordered from the menu.</p> <p>Everything works as intended, as far as I can tell. I feel like some of my classes may be doing too much, and that overall this program could be simplified. </p> <p>One of the things I am not sure about is the Customer class, because it only holds the name string. It seems like the customer should be able to do things like pay, etc. </p> <p>The Order class on the other hand, seems like it's doing too many things.</p> <p>Please let me know what you think, and what you would have done differently.</p> <p>Here's the code, and thanks for your time!</p> <p>Main Class:</p> <pre><code>/******************************************************************************* * Title: Fast Food Simulator * Author: Some Dude * Date: 7/14/2019 * Purpose: Learning basic OOP design * * Description: * ! A simple program that simulates placing an order at a drive-thru * using a keypad for input. * * ! User can add/delete items from their order, and pay for the items ******************************************************************************/ package com.company; import java.util.Scanner; public class Main { private static Scanner scanner = new Scanner(System.in); private static Menu mainMenu = new Menu(); private static Customer newCustomer; private static Order customerOrder = new Order(); private static Keypad driveThruKeypad = new Keypad(); /* Main Function Here! */ public static void main(String[] args) { CustomerMessages.displayGreeting(); getCustomerName(); CustomerMessages.displayKeypadInstructions(); getOrder(); customerOrder.payForOrder(); CustomerMessages.goodbye(); } /*************************************************************************** *! While the order is active, *! Show menu *! Display order (if they have actually ordered something) *! Get keypad input from customer *! Allows user to add/delete items from their order **************************************************************************/ private static void getOrder() { char itemSelection = '0'; while (itemSelection != '#') { mainMenu.displayMenu(); if (customerOrder.getItemCount() &gt; 0) customerOrder.displayOrder(newCustomer.getCustomerName()); itemSelection = driveThruKeypad.getKeypadEntry(); if (driveThruKeypad.deleteBtnPressed(itemSelection)) deleteItem(); else customerOrder.addItem(mainMenu.getMenuItemName(itemSelection), mainMenu.getMenuItemPrice(itemSelection)); } } /*************************************************************************** * Prompts user to select an item to delete, then deletes it * only if the item has actually been ordered **************************************************************************/ private static void deleteItem() { char itemSelection = 0; System.out.println("What Item would you like to delete?"); itemSelection = driveThruKeypad.getKeypadEntry(); customerOrder.removeItem(mainMenu.getMenuItemName(itemSelection), mainMenu.getMenuItemPrice(itemSelection)); } /*************************************************************************** * Prompts the customer to enter their name, then initializes the Customer * instance *newCustomer* using the name given by customer **************************************************************************/ private static void getCustomerName() { System.out.println("Please enter your name"); newCustomer = new Customer(scanner.nextLine()); } } </code></pre> <p>Customer Class:</p> <pre><code>/******************************************************************************* * Title: Fast Food Simulator * Author: Some Dude * Date: 7/14/2019 * Purpose: Class for a customer, will hold name, and maybe a member id later ******************************************************************************/ package com.company; public class Customer { private String customerName; Customer(String name) { this.customerName = name; } public String getCustomerName() { return customerName; } } </code></pre> <p>Keypad Class</p> <pre><code>/******************************************************************************* * Title: Keypad * Author: Some Dude * Date: 7/14/2019 * * * Description: * ! Interface for a 9 digit keypad ******************************************************************************/ package com.company; import java.util.Scanner; public class Keypad { private Scanner keypadReader = new Scanner(System.in); /* Control buttons */ private final char SUBMIT_BUTTON = '#'; private final char DELETE_BUTTON = '-'; /* User defined button ranges */ private final char minNumberInput = '0'; private final char maxNumberInput = '9'; /*************************************************************************** *! Gets input from user until the button pressed was a valid button * on the keypad (Valid buttons are defined up top) **************************************************************************/ char getKeypadEntry() { char keypadEntry = '0'; boolean inputIsValid = false; while (!inputIsValid) { System.out.println("Enter a keypad option: "); keypadEntry = keypadReader.next().charAt(0); inputIsValid = validateKeypadEntry(keypadEntry); } return keypadEntry; } /*************************************************************************** *! Checks user input to make sure it's valid **************************************************************************/ private boolean validateKeypadEntry(char keypadInput) { if ((keypadInput &gt;= minNumberInput) &amp;&amp; (keypadInput &lt;= maxNumberInput)) return true; else return (keypadInput == SUBMIT_BUTTON) || (keypadInput == DELETE_BUTTON); } /* Checks to see if the '#' button was pressed */ public boolean orderCompleteBtnPressed(int input) { return input == SUBMIT_BUTTON; } /* Checks to see if the '-' button was pressed */ public boolean deleteBtnPressed(int input) { return input == DELETE_BUTTON; } } </code></pre> <p>Order Class:</p> <pre><code>/******************************************************************************* * Title: Order * Author: Some Dude * Date: 7/14/2019 * Purpose: Handles everything that has to do with the order * * Description: Handles everything that has to do with the order such as -&gt; *! Adding/deleting order items *! Accepting payment for the order *! Keeping track of subtotal(no tax), and grandTotal(After tax) *! Keeping track of items in the order ******************************************************************************/ package com.company; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Order { /* Scanner used for keypad input */ private Scanner scanner = new Scanner(System.in); private final double STATE_TAX = 0.10; /* Order total before/after tax */ private double subTotal; private double grandTotal; /* Counter for items ordered and list to hold item names*/ private int itemCount; private ArrayList&lt;String&gt; orderItems; public Order() { this.itemCount = 0; this.subTotal = 0.00; this.grandTotal = 0.00; this.orderItems = new ArrayList&lt;&gt;(); } /*************************************************************************** *! Add and item to the order, increment itemCount, increase price **************************************************************************/ void addItem(String itemName, double itemPrice) { if ((!itemName.equals("")) &amp;&amp; (itemPrice &gt; 0.00)) { this.orderItems.add(itemName); this.itemCount++; this.subTotal += itemPrice; System.out.println(itemName + " Added to your order"); updateGrandTotal(); } } /*************************************************************************** *! If item has actually been ordered, delete it, else, show err message **************************************************************************/ void removeItem(String itemName, double itemPrice) { if (this.orderItems.contains(itemName)) { this.orderItems.remove(itemName); this.itemCount -= 1; this.subTotal -= itemPrice; System.out.println(itemName + " Deleted from your order"); updateGrandTotal(); } else System.out.println(itemName + " is not in your order"); } double getGrandTotal() { return this.grandTotal; } public double getSubTotal() { return this.subTotal; } public int getItemCount() { return itemCount; } private void setSubTotal(double amount) { this.subTotal = amount; } /* Adds the tax rate to the order */ private void updateGrandTotal() { this.grandTotal = this.subTotal + (this.subTotal * this.STATE_TAX); } /* Checks to see if item is in orderItems list */ private boolean findOrderItem(String itemName) { return this.orderItems.contains(itemName); } /* Displays the order details to the user */ public void displayOrder(String customerName) { System.out.println( "************************************************************"); System.out.printf("%s's order details:\n", customerName); System.out.printf("Items ordered: %d\n", itemCount); System.out.println(Arrays.toString(this.orderItems.toArray())); System.out.printf("Price before tax: $%.2f\n", subTotal); System.out.printf("Grand total: $%.2f\n", grandTotal); System.out.println( "************************************************************"); } /* While order is not paid for, get money from customer */ public void payForOrder() { double cashRecieved = 0.00; while (grandTotal != 0.00) { /* Round grandTotal to 2nd decimal place */ grandTotal = round2Decimals(grandTotal); System.out.printf("Your total is $%.2f\n", grandTotal); System.out.println("Enter your payment amount"); cashRecieved = scanner.nextDouble(); if (cashRecieved &gt; 0) grandTotal -= cashRecieved; if (grandTotal &lt; 0.00) calculateChange(); } } /* Calculates the change due (Only used when grandTotal is &lt; 0.00) */ private void calculateChange() { double changeDue = 0.00; changeDue = (0.00 - grandTotal); grandTotal = 0.00; changeDue = round2Decimals(changeDue); System.out.println("Your change is " + changeDue); } /* Returns a double rounded to the 2nd value (2.222 = 2.22) */ private double round2Decimals(double num) { return (double) Math.round(num * 100) / 100; } } </code></pre> <p>Customer Messages Class:</p> <pre><code>/******************************************************************************* * Title: Customer Messages * Author: Some Dude * Date: 7/14/2019 * * Purpose: Stores all of the general messages that the company would * want to show on the screen ******************************************************************************/ package com.company; public class CustomerMessages { public static void displayGreeting() { System.out.println("Welcome to some burger joint!"); } public static void goodbye() { System.out.println("Thank you for eating at some burger joint!\n" + "Please come again!"); } /* Shows the instructions for the keypad */ public static void displayKeypadInstructions() { System.out.println("\n"); System.out.println( "************************************************************"); System.out.println("~Keypad Instructions~"); System.out.println("To add an item to your order, please press the " + "keypad number that matches the item number on the screen"); System.out.println("To delete an item from your order, press the '-' " + "key on the keypad"); System.out.println("To submit your order, press the '#' key on the " + "keypad"); System.out.println( "************************************************************"); } } </code></pre> <p>Menu Class:</p> <pre><code>/******************************************************************************* * Title: Menu * Author: Some Dude * Date: 7/14/2019 * * Purpose: Interface for the main menu * * Description: * ! Shows the current menu * ! Keeps track of how many menu items are available * ! Keeps track of menu item prices and names ******************************************************************************/ package com.company; public class Menu { /* Menu Prices */ private final double CHEESEBURGER_PRICE = 5.25; private final double FRENCH_FRIES_PRICE = 2.00; private final double DRINK_PRICE = 1.00; /* Menu Items */ private final String CHEESEBURGER = "Cheeseburger"; private final String FRIES = "Fries"; private final String DRINK= "Drink"; /* The amount of items currently on the menu */ private final int totalMenuItems = 3; /* Displays menu options and prices */ void displayMenu() { System.out.println("***************************"); System.out.println("~Menu~"); System.out.println("1) Cheeseburger $" + CHEESEBURGER_PRICE); System.out.println("2) Fries $" + FRENCH_FRIES_PRICE); System.out.println("3) Drink $" + DRINK_PRICE); System.out.println("***************************"); } public double getCheeseburgerPrice() { return CHEESEBURGER_PRICE; } public double getFrenchFriesPrice() { return FRENCH_FRIES_PRICE; } public double getDrinkPrice() { return DRINK_PRICE; } public int getTotalMenuItems() { return totalMenuItems; } /*************************************************************************** * Returns the name of the item that matches the item selection number, * Return blank string if menu item doesn't exist **************************************************************************/ public String getMenuItemName(char itemSelection) { switch (itemSelection) { case '1': return CHEESEBURGER; case '2': return FRIES; case '3': return DRINK; default: return ""; } } /*************************************************************************** * Returns the price of the item that matches the itemSelection number * Return 0.00 if item doesn't exist **************************************************************************/ double getMenuItemPrice(char itemSelection) { switch (itemSelection) { case '1': return CHEESEBURGER_PRICE; case '2': return FRENCH_FRIES_PRICE; case '3': return DRINK_PRICE; default: return 0.00; } } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>On an overall impression, your code looks really clean, and I think that logic separation between your classes is pretty clear.</p></li>\n<li><p>Don't use double with money, as there are precision issues. Consider using BigDecimal. That way you will also avoid using sloppy funtions like <code>round2Decimals</code>.</p></li>\n<li><p>On your Keypad class, you should inject the scanner dependency.</p></li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Keypad\n{\n\n private Scanner keypadReader;\n public Order(Scanner keypadReader)\n {\n this.itemCount = 0;\n this.subTotal = 0.00;\n this.grandTotal = 0.00;\n this.orderItems = new ArrayList&lt;&gt;();\n this.keypadReader = keypadReader;\n }\n\n // ...\n}\n</code></pre>\n\n<ul>\n<li><p>Why prepending comments with bang symbols <code>!</code>? This provides no usefulness and should be removed.</p></li>\n<li><p>Use preincrements: <code>this.itemCount -= 1;</code> <span class=\"math-container\">\\$\\to\\$</span> <code>--this.itemCount;</code>.</p></li>\n<li><p>Your menu class may be impossible to handle with, let's say, 5 or 6 more ingredients. You may want create a <code>Dish</code> class with a name and a price as attributes.</p></li>\n<li><p><code>CustomerMessages</code> class should be <code>static</code>.</p></li>\n<li><p>Consider using JavaDoc:</p></li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code>/**\n * @author Some Dude\n * @since 7/14/2019\n *\n * Interface for the main menu:\n * - Shows the current menu\n * - Keeps track of how many menu items are available\n * - Keeps track of menu item prices and names\n */\n</code></pre>\n\n<ul>\n<li><p>Avoid long <code>/**********</code>... comments. Just <code>/*</code> or <code>/**</code> (for JavaDoc) suffices.</p></li>\n<li><p>Take a look at the Liskov Substitution Principle. Considerable case here is not using <code>ArrayList</code>s for your attributes, but simply <code>List</code>s:</p></li>\n</ul>\n\n<pre class=\"lang-java prettyprint-override\"><code> private List&lt;String&gt; orderItems; // No longer ArrayList!!!!\n\n\n public Order()\n {\n this.itemCount = 0;\n this.subTotal = 0.00;\n this.grandTotal = 0.00;\n this.orderItems = new ArrayList&lt;&gt;();\n }\n</code></pre>\n\n<ul>\n<li><p>Don't use multi-line comments for single-line comments: <code>/* Menu Items */</code> <span class=\"math-container\">\\$\\to\\$</span> <code>// Menu items</code></p></li>\n<li><p>Check for static functions in your classes (i.e. <code>void displayMenu()</code> should be static, as well with <code>CHEESEBURGER_PRICE</code> and the other magic numbers/strings).</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T08:27:25.123", "Id": "439866", "Score": "1", "body": "Yes I was thinking the same thing about my `round2Decimals()` function, it is sloppy. The `!` symbols in my comments are just a habit from the programming language I use for my robot automation job, which is similar to C in some ways. I wasn't exactly sure the best practices for java documentation comments, so thanks for pointing that out. Thanks for your time!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:14:33.577", "Id": "226328", "ParentId": "226306", "Score": "2" } }, { "body": "<p>\nHello, the changes I'm proposing you involves the class <code>Menu</code> , because at the moment every time you modify the menu (adding or deleting a menu item) you have to define a new method to get name and price of the new menuitem or you are obliged to delete methods that uses a deleted item. \nThe solution I propose you to avoid this issues is creating a new class called <code>MenuItem</code> , above the code of the class:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class MenuItem {\n private String name;\n private Double price;\n\n public MenuItem(String name, Double price) {\n this.name = name;\n this.price = price;\n }\n\n public String getName() {\n return name;\n }\n\n\n public Double getPrice() {\n return price;\n }\n\n @Override\n public String toString() {\n return String.format(\"%s $%.2f\", name, price);\n }\n}\n</code></pre>\n\n<p>You can check that I override method <code>toString</code> : this method will return a string with price limited to the first two digits like Cheeseburger $5,25.\nNow the <code>Menu</code> class will contains an <code>ArrayList</code> of <code>MenuItem</code> objects, above the code of the class:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Menu {\n\n private List&lt;MenuItem&gt; items;\n\n public Menu() {\n this.items = new ArrayList&lt;MenuItem&gt;();\n this.items.add(new MenuItem(\"Cheeseburger\", 5.25));\n this.items.add(new MenuItem(\"Fries\", 2.00));\n this.items.add(new MenuItem(\"Drink\", 1.00));\n }\n\n public void displayMenu()\n {\n System.out.println(\"***************************\");\n System.out.println(\"~Menu~\");\n int i = 1;\n for (MenuItem item : items) {\n System.out.println(String.format(\"%d) %s\", i++, item));\n }\n System.out.println(\"***************************\");\n }\n\n public MenuItem getMenuItem(int itemSelection) {\n return items.get(itemSelection);\n }\n}\n</code></pre>\n\n<p>You can see that now you can add or remove elements from the menu. I modified the type of parameter itemSelection from char to int otherwise your menu would be limited to items from 1 to 9.\nNow the test class code:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Main {\n\npublic static void main(String[] args) {\n Menu menu = new Menu();\n menu.displayMenu();\n int itemSelection = 1;\n MenuItem item = menu.getMenuItem(--itemSelection); //menu displayed and arraylist differs for one position \n System.out.println(item); //it will print Cheeseburger $5,25\n System.out.println(item.getName()); //it will print Cheeseburger\n System.out.println(item.getPrice()); //it will print 5.25\n}\n</code></pre>\n\n<p>If the menu starts from 1 , you always have to remember decrementing of one the menuitem selected from the customer to match the arrayList inside the class Menu.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T17:21:12.217", "Id": "226385", "ParentId": "226306", "Score": "0" } } ]
{ "AcceptedAnswerId": "226328", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T08:45:57.307", "Id": "226306", "Score": "6", "Tags": [ "java", "beginner", "simulation" ], "Title": "Fast Food Order Simulator" }
226306
<p>I'm looking for some feedback on a pomodoro clock that I recently wrote with React.</p> <p>I'm pretty new to React and coding in general. I followed a couple of online courses, but I'm mostly self-taught. My academic background and my actual job have nothing to do with programming, so I really don't know how to rate my work. </p> <p>A couple of things I have doubts on:</p> <ul> <li>Is the code clean and easily readable? </li> <li>Is there some common practice that I didn't follow?</li> </ul> <p>Of course any other advice or observation would be much appreciated.</p> <p>Here's the code of the main component, but since I used more modules it would make my day if you could take a look at the <a href="https://github.com/peschina/Pomodoro-clock/tree/a423fc58307ba6223aefb10fde9c995555c77d8d" rel="nofollow noreferrer">github repo</a>.</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>class App extends React.Component { constructor() { super(); this.state = { // prop used by SetInterval and ClearInterval timerId: 0, start: 0, // this property is used by tick method startTime: "25:00", // value displayed by timer currentTime: "25:00", workTime: "25", shortBreakTime: "5", longBreakTime: "30", // how many pomodoros before long break lBDelay: 4, pomodorosCompleted: 0, // session is Ready when startTime is updated sessionReady: "work", sessionRunning: "", theme: "violet", sound: "on", // to set the correct CSS variables for svg animation animationWasPaused: false }; this.notificationDOMRef = React.createRef(); } componentDidMount() { let circle = document.querySelector("circle"); circle.style.setProperty("--time", "initial"); } // handles notification component addNotification(mess, typ) { this.notificationDOMRef.current.addNotification({ message: mess, type: typ, insert: "top", container: "top-right", animationIn: ["animated", "fadeIn"], animationOut: ["animated", "fadeOut"], dismiss: { duration: 5000 }, dismissable: { click: true } }); }; prepareNewSession = () =&gt; { const val = this.state[`${this.state.sessionReady}Time`]; const time = val &lt; 10 ? `0${val}:00` : `${val}:00`; this.setState({ sessionRunning: "", startTime: time, currentTime: time }); }; handleStart = () =&gt; { const { sessionRunning, sessionReady, startTime, animationWasPaused } = this.state; // disable button if session is already running if (sessionRunning) { this.addNotification("session has already started", "warning"); return; } // toggle session that is starting now this.setState({ sessionRunning: sessionReady, start: Date.now(), timerId: setInterval(this.setTimer, 1000) }); // start svg timer let circle = document.querySelector("circle"); if (animationWasPaused) { circle.style.setProperty("--pauseHandler", "running"); this.setState({ animationWasPaused: false }); return; } const seconds = `${toSeconds(startTime)}s`; circle.style.setProperty("--time", seconds); circle.style.setProperty("--pauseHandler", "running"); }; setTimer = () =&gt; { const { startTime, start, currentTime, timerId, sessionReady, pomodorosCompleted, lBDelay } = this.state; // convert string to number and then to seconds let duration = toSeconds(startTime); let display = tick(duration, start); this.setState({ currentTime: display }); if (currentTime === "00:00") { clearInterval(timerId); this.alarm.play(); // according to session that just finished update props in state and start new session if (sessionReady === "work") { // check if we already have n pomodoros completed and need to switch to long break this.setState({ pomodorosCompleted: pomodorosCompleted + 1 }); const remainder = (pomodorosCompleted + 1) % lBDelay; remainder === 0 ? this.handleSelect("longBreak") : this.handleSelect("shortBreak"); } else { this.handleSelect("work"); } // give time to update svg circle CSS var setTimeout(this.handleStart, 1); } }; handleStop = () =&gt; { let { sessionRunning, timerId, currentTime } = this.state; if (!sessionRunning) { this.addNotification("session isn't running", "warning"); return; } clearInterval(timerId); // pause svg timer const circle = document.querySelector("circle"); circle.style.setProperty("--pauseHandler", "paused"); this.setState({ sessionRunning: "", startTime: currentTime, animationWasPaused: true }); }; handleReset = () =&gt; { const { sessionRunning, timerId } = this.state; if (!sessionRunning) { this.addNotification("session isn't running", "warning"); return; } clearInterval(timerId); this.prepareNewSession(); // reset svg timer let circle = document.querySelector("circle"); circle.style.setProperty("--time", "initial"); circle.style.setProperty("--pauseHandler", "paused"); }; handleChange = ({ target }) =&gt; { const { name } = target; let { value } = target; let bgMax; let bgMin; this.setState({ [name]: value }); if (value === "0") { if (name === "lBDelay") return; this.addNotification("Session should last at least one minute", "danger"); setTimeout(() =&gt; this.setState({ [name]: 1 }), 800); return; } if (name === "theme") { // set values for background bgMax = target.options[target.selectedIndex].dataset.max; bgMin = target.options[target.selectedIndex].dataset.min; updateTheme(value, bgMax, bgMin); return; } }; // this method sets props in state so that the session is ready to start // the session doesn't start automatically, but only when Start button is clicked! handleSelect = selected =&gt; { const { sessionRunning, timerId } = this.state; // check if session is already running. If yes display notification, if not update state so session is ready to start if (sessionRunning === selected) { this.addNotification("Session is already running", "warning"); return; } this.setState({ sessionReady: selected }, () =&gt; this.prepareNewSession()); clearInterval(timerId); // reset svg timer let circle = document.querySelector("circle"); circle.style.setProperty("--time", "initial"); circle.style.setProperty("--pauseHandler", "paused"); }; validateForm = schema =&gt; { const errors = this.validate(schema); if (errors) { const messages = Object.values(errors); messages.map(m =&gt; this.addNotification(m, "danger")); } return errors; }; validate = schema =&gt; { const { workTime, shortBreakTime, longBreakTime, lBDelay } = this.state; const { error } = Joi.validate({ workTime: workTime, shortBreakTime: shortBreakTime, longBreakTime: longBreakTime, lBDelay: lBDelay }, schema, { abortEarly: false } ); if (!error) return null; let errors = {}; error.details.map(i =&gt; { errors[i.path[0]] = i.message; }); return errors; }; saveChangesInSettings = () =&gt; { this.prepareNewSession(); // trigger notification this.addNotification("Changes have been saved!", "success"); }; progressTracker = () =&gt; { const { pomodorosCompleted } = this.state; return ( &lt; span className = "d-flex justify-content-center pb-5" &gt; { `You have completed ${pomodorosCompleted} ${ pomodorosCompleted === 1 ? "pomodoro" : "pomodoros" }` } &lt; /span&gt; ); }; alarm = new UIfx({ asset: alarm }); render() { const { workTime, shortBreakTime, longBreakTime, currentTime, sessionReady, lBDelay, pomodorosCompleted, theme, sound } = this.state; return ( &lt;React.Fragment&gt; &lt;div id="background"&gt; &lt;Container&gt; &lt;div&gt; &lt;Navigationbar activeKeyInNav={sessionReady} workTime={workTime} shortBreakTime={shortBreakTime} longBreakTime={longBreakTime} lBDelay={lBDelay} theme={theme} sound={sound} saveChanges={this.saveChangesInSettings} validateForm={this.validateForm} onChange={this.handleChange} onSelect={this.handleSelect} /&gt; &lt;ReactNotification ref={this.notificationDOMRef} /&gt; &lt;Timer currentTime={currentTime} pomodorosCompleted={pomodorosCompleted} /&gt; &lt;TimerControls onStart={this.handleStart} onStop={this.handleStop} onReset={this.handleReset} /&gt; &lt;/div&gt; &lt;div id="backgroundLarge" /&gt; &lt;/Container&gt; &lt;/div&gt; &lt;Container className="pt-4"&gt; &lt;ToDoListForm /&gt; &lt;hr /&gt; {this.progressTracker()} &lt;/Container&gt; &lt;/React.Fragment&gt; ); } } export default App;</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T14:24:11.007", "Id": "226313", "Score": "4", "Tags": [ "beginner", "animation", "react.js", "timer", "jsx" ], "Title": "React - pomodoro clock" }
226313
<p>I've made a solution for a problem which involves changing order of objects having some mass, so it costs a mass of an object A and a mass of an object B to make a swap.</p> <p>The full description of the problem and the original source code is at <a href="https://codereview.stackexchange.com/questions/226145/least-cost-swapping-in-c">Least cost swapping in C++</a> Please, review my code.</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;vector&gt; int constexpr MaxWeight = 6500, MinVertexes = 2, MaxVertexes = 1000000; struct ObjectCollection { int amountOfObjects = 0; std::vector&lt;int&gt; weights; std::vector&lt;int&gt; startingOrder; std::vector&lt;int&gt; endingOrder; int minWeight = MaxWeight; }; std::vector&lt;int&gt; readOrder(std::istringstream&amp; iss, int const amountOfObjects) { std::vector&lt;int&gt; v; v.reserve(amountOfObjects); int i = 1; while(!iss.eof() &amp;&amp; i &lt;= amountOfObjects) { int number; iss &gt;&gt; number; if (number - 1 &gt; amountOfObjects) throw std::logic_error("Too high index in order"); v.push_back(number-1); i++; } if (v.size() != amountOfObjects) throw std::logic_error("Too few values in line"); return v; } void readWeightsAndSetMinWeight(std::istringstream&amp; iss, ObjectCollection&amp; objects) { objects.weights.reserve(objects.amountOfObjects); int i = 1; while (!iss.eof() &amp;&amp; i &lt;= objects.amountOfObjects) { int number; iss &gt;&gt; number; if (number&gt; MaxWeight) throw std::logic_error("Too high weight"); objects.weights.push_back(number); objects.minWeight = std::min(objects.minWeight, number); i++; } if (objects.weights.size() != objects.amountOfObjects) throw std::logic_error("Too few values in line"); } //todo version for weight ObjectCollection readFromFile(std::string const&amp; filename) { ObjectCollection objects; std::ifstream file(filename); if (!file.is_open()) throw std::exception("Unable to open file"); for (int i = 0; i &lt; 4; i++) { std::string line; std::getline(file, line); if (line.empty()) throw std::logic_error("Invalid input"); std::istringstream iss(line); if (i == 0) { iss &gt;&gt; objects.amountOfObjects; if (objects.amountOfObjects&lt;MinVertexes || objects.amountOfObjects&gt;MaxVertexes) throw std::exception("Invalid amount of vertexes"); } else if (i == 1) { objects.weights.reserve(objects.amountOfObjects); for (int j = 0; j &lt; objects.amountOfObjects; j++) { //int number; //iss &gt;&gt; number; //objects.weights.push_back(number); //objects.minWeight = std::min(objects.minWeight, objects.weights[j]); readWeightsAndSetMinWeight(iss, objects); } } else if (i == 2) { objects.startingOrder = readOrder(iss,objects.amountOfObjects); } else if (i == 3) { objects.endingOrder = readOrder(iss, objects.amountOfObjects); } } return objects; } long long calculateLowestCostOfWork(ObjectCollection const&amp; objects) { int n = objects.amountOfObjects; std::vector&lt;int&gt; permutation(n); //constructing permutation for (int i = 0; i &lt; n; i++) { permutation[objects.endingOrder[i]] = objects.startingOrder[i]; } long long result = 0; std::vector&lt;bool&gt; visitedVertexes(n); for (int i = 0; i &lt; n; i++) { int numberOfElementsInCycle = 0; int minWeightInCycle = MaxWeight; long long sumOfWeightsInCycle = 0; if (!visitedVertexes[i]) { int vertexToVisit = i; //decomposition for simple cycles and calculating parameters for each cycle while (!visitedVertexes[vertexToVisit]) { visitedVertexes[vertexToVisit] = true; numberOfElementsInCycle++; vertexToVisit = permutation[vertexToVisit]; sumOfWeightsInCycle += objects.weights[vertexToVisit]; minWeightInCycle = std::min(minWeightInCycle, objects.weights[vertexToVisit]); } //calculating lowest cost for each cycle long long swappingWithMinWeightInCycle = sumOfWeightsInCycle + (static_cast&lt;long long&gt;(numberOfElementsInCycle) - 2) * static_cast&lt;long long&gt;(minWeightInCycle); long long swappingWithMinWeight = sumOfWeightsInCycle + minWeightInCycle + (static_cast&lt;long long&gt;(numberOfElementsInCycle) + 1) * static_cast&lt;long long&gt;(objects.minWeight); result += std::min(swappingWithMinWeightInCycle, swappingWithMinWeight); } } return result; } int main(int argc, char* argv[]) { if (argc &lt; 2) { std::cerr &lt;&lt; "Error: missing filename\n"; return 1; } ObjectCollection elephants; try { elephants = readFromFile(argv[1]); std::cout &lt;&lt; calculateLowestCostOfWork(elephants); } catch (std::exception const&amp; ex) { std::cerr &lt;&lt; "Error: " &lt;&lt; ex.what() &lt;&lt; "\n"; return 1; } catch (...) { std::cerr &lt;&lt; "Error unknown \n"; return 1; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:48:42.943", "Id": "439750", "Score": "3", "body": "Could you include the task description in this question as well? Even if it's just a copy-paste. Having to go through links to know what the question is about is something not many reviewers appreciate." } ]
[ { "body": "<p>This is not a comparative review.</p>\n\n<p><strong>Self Documenting Code</strong><br>\nThere is a standard header file that supplies <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"noreferrer\">constant values for exiting</a> <code>main()</code>. For both C and C++ the standard constants for exiting are <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code>. The C++ header for this is</p>\n\n<pre><code>#include &lt;cstdlib&gt;\n\nint main(int argc, char* argv[])\n{\n if (argc &lt; 2)\n {\n std::cerr &lt;&lt; \"Error: missing filename\\n\";\n return EXIT_FAILURE;\n }\n\n ObjectCollection elephants;\n try\n {\n elephants = readFromFile(argv[1]);\n std::cout &lt;&lt; calculateLowestCostOfWork(elephants);\n }\n catch (std::exception const&amp; ex)\n {\n std::cerr &lt;&lt; \"Error: \" &lt;&lt; ex.what() &lt;&lt; \"\\n\";\n return EXIT_FAILURE;\n }\n catch (...)\n {\n std::cerr &lt;&lt; \"Error unknown \\n\";\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p><strong>Vertical Spacing</strong><br>\nThe code might be easier to read and maintain if there was some vertical spacing between logic blocks in the functions.</p>\n\n<p><strong>Numeric Constants On Only One Line</strong><br>\nThe code might be easier to read and maintain each declaration for a numeric constant was on a separate line.</p>\n\n<pre><code>int constexpr MaxWeight = 6500;\nint constexpr MinVertexes = 2;\nint constexpr MaxVertexes = 1000000;\n</code></pre>\n\n<p><strong>Then and Else Clauses</strong><br>\nPlan for future maintenance. Quite often updating code requires the insertion of an additional statement in a <code>then</code> or <code>else</code> clause in an <code>if</code> statement. It is generally a good practice to make all of the if statements have compound statements to ease future modification. Separating the <code>if</code> from the action also makes the code a little more readable.</p>\n\n<blockquote>\n<pre><code> if (number - 1 &gt; amountOfObjects) throw std::logic_error(\"Too high index in order\");\n</code></pre>\n</blockquote>\n\n<pre><code> if (number - 1 &gt; amountOfObjects)\n {\n throw std::logic_error(\"Too high index in order\");\n }\n</code></pre>\n\n<p><strong>Variable Names</strong><br>\nIn the input functions the code might be more understandable if variables used indicated what was being read in, the variable name <code>number</code> might be a little too general. We know it is a number because it is declared as int. In the function <code>int readWeightsAndSetMinWeight()</code> perhaps <code>weight</code> could be used instead of <code>number</code>?</p>\n\n<p><strong>Commented Out Code</strong><br>\nWhen code gets moved into a function, there is generally no reason to leave the code in comments in the original place. It can be confusing to someone that has to maintain the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:10:33.143", "Id": "226322", "ParentId": "226315", "Score": "7" } }, { "body": "<pre><code>if (line.empty()) throw std::logic_error(\"Invalid input\");\n</code></pre>\n\n<p><code>std::logic_error</code> is used for \"violating logical preconditions or class invariants\", which generally translates to programmer error (and means it's seldom the correct exception type to use).</p>\n\n<p>Invalid input data certainly doesn't fit this category, and we should probably use <code>std::runtime_error</code> instead.</p>\n\n<hr>\n\n<pre><code>for (int i = 0; i &lt; 4; i++)\n{\n std::string line;\n std::getline(file, line);\n if (line.empty()) throw std::logic_error(\"Invalid input\");\n std::istringstream iss(line);\n\n if (i == 0) ...\n else if (i == 1) ...\n else if (i == 2) ...\n else if (i == 3) ...\n}\n</code></pre>\n\n<p>A for loop with a separate branch for every iteration? Hmm.</p>\n\n<p>We can avoid this by abstracting the code that needs to be repeated (reading a line) into a separate function, and then do something like:</p>\n\n<pre><code>objects.count = ReadObjectCount(readLine(file));\nobjects.weights = ReadObjectWeights(readLine(file), objects.count);\nobjects.minWeight = CalculateMinWeight(objects.weights);\nobjects.startingOrder = ReadObjectOrder(readLine(file), objects.count);\nobjects.endingOrder = ReadObjectOrder(readLine(file), objects.count);\n...\n</code></pre>\n\n<p>It's probably neater to calculate the min weight after we've read all of the weights, instead of doing it as we go.</p>\n\n<hr>\n\n<p>The <code>amountOfObjects</code> should be a <code>std::size_t</code>, since it can't be negative, and should match the vectors' index type.</p>\n\n<p>Similarly, the order vectors should contain <code>std::size_t</code> if they represent indices into a vector.</p>\n\n<p>Presumably weights can also never be negative. So we should use an unsigned type like <code>std::uint32_t</code> or <code>std::uint64_t</code> for them, and be consistent (the current code uses both <code>int</code> and <code>long long</code>).</p>\n\n<hr>\n\n<pre><code>std::vector&lt;int&gt; readOrder(std::istringstream&amp; iss, int const amountOfObjects) \n{\n std::vector&lt;int&gt; v;\n v.reserve(amountOfObjects);\n int i = 1;\n while(!iss.eof() &amp;&amp; i &lt;= amountOfObjects)\n {\n int number;\n iss &gt;&gt; number;\n if (number - 1 &gt; amountOfObjects) throw std::logic_error(\"Too high index in order\");\n v.push_back(number-1);\n i++;\n }\n if (v.size() != amountOfObjects) throw std::logic_error(\"Too few values in line\");\n return v;\n}\n</code></pre>\n\n<p>We should check that we read each number successfully by checking the stream state. (Again, we can abstract that into a separate function).</p>\n\n<p>Presumably the indices must be <code>&gt;= 0</code> (as well as less than the object count), so we should check that if we aren't using an unsigned type.</p>\n\n<p>Maybe something like:</p>\n\n<pre><code>std::size_t readValue(std::istringstream&amp; iss)\n{\n std::size_t value;\n iss &gt;&gt; value;\n\n if (!iss) // check if we failed to read the value\n throw std::runtime_error(\"Invalid input.\");\n\n return value;\n}\n\nstd::vector&lt;std::size_t&gt; readOrder(std::istringstream iss, std::size_t objectCount)\n{\n std::vector&lt;std::size_t&gt; v;\n v.reserve(objectCount);\n\n for (auto i = std::size_t{0}; i != objectCount; ++i)\n v.push_back(readValue(iss, objectCount));\n\n std::string anything;\n iss &gt;&gt; anything;\n\n if (!anything.empty() || !iss.eof())\n throw std::runtime_error(\"Extra stuff at end of line.\");\n\n OffsetAndCheckValues(v); // do the range checking and -1\n\n return v;\n}\n</code></pre>\n\n<p>Doing the range checking and offsetting by 1 later (after reading all the values), makes the <code>readValue</code> function more reusable.</p>\n\n<hr>\n\n<p>In C++ it's usual to iterate using the pre-increment operator (<code>++i</code>), because it reflects the intent more accurately (we don't need a temporary unincremented variable).</p>\n\n<p>It's also more common to use <code>!=</code> as the end condition, instead of <code>&lt;</code>, since this translates better to using iterators.</p>\n\n<p>Make sure to use the appropriate type for iteration (e.g. <code>std::size_t</code> for iterating over vector indices).</p>\n\n<pre><code>for (std::size_t i = 0; i != objects.count; ++i)\n</code></pre>\n\n<hr>\n\n<p>It's good to use descriptive names, but some of them are a bit excessive. At some point the longer names just hinder readability.</p>\n\n<pre><code>std::vector&lt;bool&gt; visited(objects.count);\n...\n std::size_t cycleSize = 0;\n std::uint64_t cycleMin = MaxWeight;\n std::uint64_t cycleSum = 0;\n</code></pre>\n\n<hr>\n\n<p>Prefer to <code>return</code> or <code>continue</code> early to avoid unnecessary indentation:</p>\n\n<pre><code> if (visited[i])\n continue;\n\n // no need to indent this code...\n</code></pre>\n\n<hr>\n\n<p>Note that <code>numberOfElementsInCycle</code> (and others) aren't used if we have visited the vertex, so could be declared after this check.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T00:44:25.807", "Id": "439826", "Score": "0", "body": "\"It's probably neater to calculate the min weight after we've read all of the weights, instead of doing it as we go.\" But that costs reading all vector (even 1 000 000 elements) again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T01:00:01.833", "Id": "439828", "Score": "0", "body": "\"So we should use an unsigned type like std::uint32_t or std::uint64_t for them, and be consistent (the current code uses both int and long long).\" No, the current code uses a int for weight and long long for sum of them. Should i change it somehow? But it would cost an additional space in std::vector<long long> to do so?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T07:27:49.743", "Id": "439854", "Score": "1", "body": "1. Yeah. But reading those 1000000 elements from a text file on the hard-drive is probably so slow in comparison that it doesn't matter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T07:51:14.870", "Id": "439860", "Score": "1", "body": "2. You can use a different type for the sum if it's necessary, but it's simpler not to (and we should really be checking for overflow with whatever type we use). Either way an unsigned type gives us more range than a signed one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T22:25:59.980", "Id": "439960", "Score": "0", "body": "Due to rebuild to getting a single line and returning istringstream, i am getting error in readWeightsAndSetMinWeight function \"can't convert from std::istringstream to std::istringstream &\". How do i fix it and why it's happening?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T22:37:29.240", "Id": "439962", "Score": "0", "body": "What's the reason for std::string anything;?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T05:20:47.390", "Id": "439980", "Score": "1", "body": "@JanDycz Sounds like that error is because you can't assign a value to a non-const reference. If you change the function to take the istringstream by value, it should work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T05:37:15.267", "Id": "439981", "Score": "1", "body": "`std::string anything;` was to check that there's nothing else (other than whitespace) on the current line. If `anything` isn't empty after trying to read into it, or if we didn't hit eof(), then there's some extra data on the line. Thinking about it, it's probably better just to check for eof after reading the last expected value (although that would disallow any trailing whitespace)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:49:23.997", "Id": "440042", "Score": "0", "body": "Hi @user673679. I would like to change input from passing filename as argument to passing from input like myprogram < file.txt How can i achieve that?" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T21:19:18.437", "Id": "226345", "ParentId": "226315", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:02:54.687", "Id": "226315", "Score": "4", "Tags": [ "c++" ], "Title": "C++ Least cost swapping 2" }
226315
<h2>Introduction</h2> <p>I provide a regular <code>9</code>x<code>9</code> <a href="https://en.wikipedia.org/wiki/Sudoku" rel="nofollow noreferrer">Sudoku</a> solver, reducing the puzzle to an <a href="https://en.wikipedia.org/wiki/Exact_cover" rel="nofollow noreferrer">Exact Cover Problem</a>. The algorithm used is <a href="https://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X" rel="nofollow noreferrer">Knuth's Algorithm X</a> as implemented using <a href="https://en.wikipedia.org/wiki/Dancing_Links" rel="nofollow noreferrer">Dancing Links (DLX)</a>. As I found no such solving technique on Code Review written in C#, I took up the challenge to have a go at it. </p> <p><sup>The problem definitions and used algorithms are behind links because it takes a lot of reading to understand these concepts.</sup></p> <hr> <h2>Challenge Description</h2> <p>This is a LeetCode challenge: <a href="https://leetcode.com/problems/sudoku-solver/description/" rel="nofollow noreferrer">#37 - Sudoku Solver</a>.</p> <blockquote> <p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p> <p>A sudoku solution must satisfy all of the following rules:</p> <ul> <li>Each of the digits <code>1-9</code> must occur exactly once in each row.</li> <li>Each of the digits <code>1-9</code> must occur exactly once in each column.</li> <li>Each of the the digits <code>1-9</code> must occur exactly once in each of the 9 3x3 sub-boxes of the grid.</li> <li>Empty cells are indicated by the character '<code>.</code>'.</li> </ul> </blockquote> <hr> <h2>Goal</h2> <p>I'll first show the unit test that solves a board, before presenting a bottom-up presentation to come to this solution. Next steps include <em>exact cover</em> -> <em>dancing links</em> -> <em>sudoku solver</em>.</p> <pre><code>[TestMethod] public void Solve() { var board = new char[,] { {'5','3','.','.','7','.','.','.','.'}, {'6','.','.','1','9','5','.','.','.'}, {'.','9','8','.','.','.','.','6','.'}, {'8','.','.','.','6','.','.','.','3'}, {'4','.','.','8','.','3','.','.','1'}, {'7','.','.','.','2','.','.','.','6'}, {'.','6','.','.','.','.','2','8','.'}, {'.','.','.','4','1','9','.','.','5'}, {'.','.','.','.','8','.','.','7','9'} }; var expected = new char[,] { {'5','3','4','6','7','8','9','1','2'}, {'6','7','2','1','9','5','3','4','8'}, {'1','9','8','3','4','2','5','6','7'}, {'8','5','9','7','6','1','4','2','3'}, {'4','2','6','8','5','3','7','9','1'}, {'7','1','3','9','2','4','8','5','6'}, {'9','6','1','5','3','7','2','8','4'}, {'2','8','7','4','1','9','6','3','5'}, {'3','4','5','2','8','6','1','7','9'} }; var sudoku = new Sudoku(); sudoku.Solve(board); CollectionAssert.AreEqual(expected, board); } </code></pre> <hr> <h2>Exact Cover</h2> <p>An Exact Cover Problem is a specific type of Constaint Satisfaction Problem where all constraints have to be met, and no constraint can be met more than once. Each set is a collection of candidate constraints. Finding a solution requires to find combinations of sets that meet all the constraints.</p> <p>I need some configurable options, since consumers may decide how many solutions should be probed for. For instance, if you need a unique solution, search for 2 solutions and if the solver found only one, you know it's the unique solution.</p> <pre><code>public class SolverOptions { public int MaxRecursion { get; set; } = -1; public int MaxSolutions { get; set; } = -1; public bool IncludeCluesInSolution = false; public bool HasRecursionLevelExceeded(int recursionLevel) { return MaxRecursion &gt; -1 &amp;&amp; recursionLevel &gt; MaxRecursion; } public bool HasSolutionsExceeded(IEnumerable&lt;ISet&lt;int&gt;&gt; solutions) { return MaxSolutions &gt; -1 &amp;&amp; solutions.Count() &gt;= MaxSolutions; } } </code></pre> <p>Any solver implementation must implement the interface. Given a problem and some options, one or more solutions are probed for. Each solution is a set containing the id's of the initial sets used to meet the requirements.</p> <pre><code>public interface ICSPSolver { IReadOnlyCollection&lt;ISet&lt;int&gt;&gt; Solve(ExactCover problem, SolverOptions options); } </code></pre> <p>The problem's state is stored.</p> <pre><code>public class ExactCover { public ISet&lt;int&gt; Constraints { get; } public IDictionary&lt;int, ISet&lt;int&gt;&gt; Sets { get; } public ISet&lt;int&gt; Clues { get; } public ExactCover(ISet&lt;int&gt; constraints, IDictionary&lt;int, ISet&lt;int&gt;&gt; sets, ISet&lt;int&gt; clues) { Constraints = constraints; Sets = sets; Clues = clues; } public IReadOnlyCollection&lt;ISet&lt;int&gt;&gt; Solve(ICSPSolver solver, SolverOptions options) { return solver.Solve(this, options); } } </code></pre> <hr> <h2>Dancing Links</h2> <p>Dancing links implements a fast algorithm for solving an exact cover problem. It works on a <em>circular bi-directional doubly linked list</em>, which also happens to be a <em>sparse matrix</em>.</p> <p>To accomplish such Toroidal Matrix structure, we require a node.</p> <pre><code>class DLXNode { internal DLXNode header, row; internal DLXNode up, down, left, right; internal int constraint, set, rowCount; internal DLXNode() =&gt; up = down = left = right = header = row = this; internal bool IsLast =&gt; right == this; internal void AddLast(DLXNode node) =&gt; row.left.Append(node); internal void AddLastDown(DLXNode node) =&gt; header.up.AppendDown(node); internal void Append(DLXNode node) { right.left = node; node.right = right; node.left = this; right = node; } internal void AppendDown(DLXNode node) { down.up = node; node.down = down; node.up = this; down = node; header.rowCount++; } internal IEnumerable&lt;DLXNode&gt; Iterate(Func&lt;DLXNode, DLXNode&gt; direction) { var node = this; do { yield return node; node = direction(node); } while (node != this); } public override string ToString() { var isHeader = header == this; var isRow = row == this; var isRoot = isHeader &amp;&amp; isRow; return isRoot ? "R" : isHeader ? $"H{header.constraint}" : isRow ? $"R{row.set}" : $"C({header.constraint},{row.set})"; } } </code></pre> <p>And the implementation of the DLX solver.</p> <pre><code>public class DLX : ICSPSolver { public IReadOnlyCollection&lt;ISet&lt;int&gt;&gt; Solve(ExactCover problem, SolverOptions options) { var root = Parse(problem); var solutions = new List&lt;ISet&lt;int&gt;&gt;(); var currentSolution = new Stack&lt;int&gt;(); var recursionLevel = 0; Explore(root, solutions, currentSolution, problem.Clues, recursionLevel, options); return solutions.AsReadOnly(); } internal bool CheckForSolution( DLXNode root, IList&lt;ISet&lt;int&gt;&gt; solutions, Stack&lt;int&gt; currentSolution, ISet&lt;int&gt; clues, int recursionLevel, SolverOptions options) { if (root.IsLast || options.HasRecursionLevelExceeded(recursionLevel) || options.HasSolutionsExceeded(solutions)) { if (root.IsLast) { var solution = new HashSet&lt;int&gt;(currentSolution); if (options.IncludeCluesInSolution) { foreach (var clue in clues) { solution.Add(clue); } } solutions.Add(solution); } return true; } return false; } internal DLXNode GetHeaderWithMinimumRowCount(DLXNode root) { DLXNode next = null; foreach (var header in root.Iterate(n =&gt; n.right).Skip(1)) { if (next == null || header.rowCount &lt; next.rowCount) { next = header; } } return next; } internal void Explore( DLXNode root, IList&lt;ISet&lt;int&gt;&gt; solutions, Stack&lt;int&gt; currentSolution, ISet&lt;int&gt; clues, int recursionLevel, SolverOptions options) { if (CheckForSolution( root, solutions, currentSolution, clues, recursionLevel, options)) { return; } var header = GetHeaderWithMinimumRowCount(root); if (header.rowCount &lt;= 0) { return; } Cover(header); foreach (var row in header.Iterate(n =&gt; n.down).Skip(1)) { currentSolution.Push(row.row.set); foreach (var rightNode in row.Iterate(n =&gt; n.right).Skip(1)) { Cover(rightNode); } Explore(root, solutions, currentSolution, clues, recursionLevel + 1, options); foreach (var leftNode in row.Iterate(n =&gt; n.left).Skip(1)) { Uncover(leftNode); } currentSolution.Pop(); } Uncover(header); } internal void Cover(DLXNode node) { if (node.row == node) return; var header = node.header; header.right.left = header.left; header.left.right = header.right; foreach (var row in header.Iterate(n =&gt; n.down).Skip(1)) { foreach (var rightNode in row.Iterate(n =&gt; n.right).Skip(1)) { rightNode.up.down = rightNode.down; rightNode.down.up = rightNode.up; rightNode.header.rowCount--; } } } internal void Uncover(DLXNode node) { if (node.row == node) return; var header = node.header; foreach (var row in header.Iterate(n =&gt; n.up).Skip(1)) { foreach (var leftNode in row.Iterate(n =&gt; n.left).Skip(1)) { leftNode.up.down = leftNode; leftNode.down.up = leftNode; leftNode.header.rowCount++; } } header.right.left = header; header.left.right = header; } internal DLXNode Parse(ExactCover problem) { var root = new DLXNode(); var headerLookup = new Dictionary&lt;int, DLXNode&gt;(); var rowLookup = new Dictionary&lt;int, DLXNode&gt;(); var givens = new HashSet&lt;int&gt;(problem.Clues .SelectMany(x =&gt; problem.Sets[x]).Distinct()); foreach (var constraint in problem.Constraints.Where(x =&gt; !givens.Contains(x))) { var header = new DLXNode { constraint = constraint, row = root }; headerLookup.Add(constraint, header); root.AddLast(header); } foreach (var set in problem.Sets.Where(x =&gt; !x.Value.Any(y =&gt; givens.Contains(y)))) { var row = new DLXNode { set = set.Key, header = root }; rowLookup.Add(set.Key, row); root.AddLastDown(row); foreach (var element in set.Value) { if (headerLookup.TryGetValue(element, out var header)) { var cell = new DLXNode { row = row, header = header }; row.AddLast(cell); header.AddLastDown(cell); } } } return root; } } </code></pre> <p>These unit tests should give you an idea how the algorithm can be used for trivial problems.</p> <pre><code> [TestMethod] public void ManySolutions() { var problem = new ExactCover( new HashSet&lt;int&gt; { 1, 2, 3 }, new Dictionary&lt;int, ISet&lt;int&gt;&gt; { { 0, new HashSet&lt;int&gt; { 1 } } , { 1, new HashSet&lt;int&gt; { 2 } } , { 2, new HashSet&lt;int&gt; { 3 } } , { 3, new HashSet&lt;int&gt; { 2, 3 } } , { 4, new HashSet&lt;int&gt; { 1, 2 } } }, new HashSet&lt;int&gt;()); var solutions = problem.Solve( new DLX(), new SolverOptions()); var printed = Print(problem, solutions); AssertAreEqual(@" Constraints: {1, 2, 3} Set 0: {1} Set 1: {2} Set 2: {3} Set 3: {2, 3} Set 4: {1, 2} Solutions: 3 Solution #1: {1}, {2}, {3} Solution #2: {1}, {2, 3} Solution #3: {3}, {1, 2}", printed); } [TestMethod] public void ManySolutionsWithClues() { var problem = new ExactCover( new HashSet&lt;int&gt; { 1, 2, 3 }, new Dictionary&lt;int, ISet&lt;int&gt;&gt; { { 0, new HashSet&lt;int&gt; { 1 } } , { 1, new HashSet&lt;int&gt; { 2 } } , { 2, new HashSet&lt;int&gt; { 3 } } , { 3, new HashSet&lt;int&gt; { 2, 3 } } , { 4, new HashSet&lt;int&gt; { 1, 2 } } }, new HashSet&lt;int&gt; { 2 }); var solutions = problem.Solve( new DLX(), new SolverOptions() { IncludeCluesInSolution = true }); var printed = Print(problem, solutions); AssertAreEqual(@" Constraints: {1, 2, 3} Set 0: {1} Set 1: {2} Set 2: {3} [Clue] Set 3: {2, 3} Set 4: {1, 2} Solutions: 2 Solution #1: {1}, {2}, {3} Solution #2: {3}, {1, 2}", printed); } string Print(ExactCover problem, IReadOnlyCollection&lt;ISet&lt;int&gt;&gt; solutions) { var b = new StringBuilder(); var i = 0; b.AppendLine($"Constraints: {Print(problem.Constraints)}"); foreach (var set in problem.Sets) { var isClue = problem.Clues.Contains(set.Key); if (isClue) { b.AppendLine($"Set {set.Key}: {Print(set.Value)} [Clue]"); } else { b.AppendLine($"Set {set.Key}: {Print(set.Value)}"); } } b.AppendLine($"Solutions: {solutions.Count}"); foreach (var solution in solutions) { b.AppendLine($"Solution #{++i}: {string.Join(", ", solution.OrderBy(_ =&gt; _).Select(s =&gt; Print(problem.Sets[s])))}"); } return b.ToString(); } string Print&lt;T&gt;(IEnumerable&lt;T&gt; set) =&gt; !set.Any() ? "Empty" : $"{{{string.Join(", ", set.OrderBy(_ =&gt; _))}}}"; static string Normalize(string input) =&gt; Regex.Replace(input, @"\s+", string.Empty); static void AssertAreEqual(string excepted, string actual) =&gt; Assert.AreEqual(Normalize(excepted), Normalize(actual)); </code></pre> <hr> <h2>Sudoku Solver</h2> <p>As a final step, we reduce a Sudoku board to a DLX matrix, solve it and map the data back to the Sudoku board. The format chosen corresponds to the challenge.</p> <pre><code>public class Sudoku { public void Solve(char[,] board) { var problem = Reduce(board); // The challenge allows us to assert a single solution is available var solution = problem.Solve( new DLX(), new SolverOptions { MaxSolutions = 1 }).Single(); Augment(board, solution); } internal void Augment(char[,] board, ISet&lt;int&gt; solution) { var n2 = board.Length; var n = (int)Math.Sqrt(n2); foreach (var match in solution) { var row = match / (n * n); var column = match / n % n; var number = match % n; var symbol = Encode(number); board[row, column] = symbol; } } internal ExactCover Reduce(char[,] board) { var n2 = board.Length; var n = (int)Math.Sqrt(n2); var m = (int)Math.Sqrt(n); // The constraints for any regular Sudoku puzzle are: // - For each row, a number can appear only once. // - For each column, a number can appear only once. // - For each region(small square), a number can appear only once. // - Each cell can only have one number. // For 9x9 Sudoku, the binary matrix will have 4 x 9² columns. var constraints = new HashSet&lt;int&gt;(Enumerable.Range(0, 4 * n * n)); // The sets for any regular Sudoku puzzle are all permutations of: // - Each row, each column, each number // For 9x9 Sudoku, the binary matrix will have 9³ rows. var sets = new Dictionary&lt;int, ISet&lt;int&gt;&gt;(); var clues = new HashSet&lt;int&gt;(); foreach (var row in Enumerable.Range(0, n)) { foreach (var column in Enumerable.Range(0, n)) { var region = m * (row / m) + column / m; foreach (var number in Enumerable.Range(0, n)) { sets.Add((row * n + column) * n + number, new HashSet&lt;int&gt; { // number in row row * n + number, // number in column (n + column) * n + number, // number in region (2 * n + region) * n + number, // cell has number (3 * n + row) * n + column }); } if (TryDecode(board[row, column], out var given)) { clues.Add((row * n + column) * n + given); } } } var problem = new ExactCover(constraints, sets, clues); return problem; } internal char Encode(int number) =&gt; (char)('1' + number); internal bool TryDecode(char symbol, out int number) { if (symbol == '.') { number = -1; return false; } number = symbol - '1'; return true; } } </code></pre> <hr> <h2>Questions</h2> <ul> <li>Usability: can this code be reused for different variants of the puzzle?</li> <li>Usability: can this code be reused for different problems such as the <em>n queen problem</em>?</li> <li>Performance: can this algorithm be improved for performance</li> <li>General coding guidelines</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:36:59.793", "Id": "439748", "Score": "2", "body": "[tag:programming-challenge] questions are on my blacklist so you'll get only a +1 from me :-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:42:51.447", "Id": "439749", "Score": "0", "body": "Yes but this is a very interesting one. Try to ignore the challenge, and check out the algorithm instead ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:52:12.090", "Id": "439751", "Score": "1", "body": "mhmm, still not sure. These _problems_ are of limited practical value if any. Though I have one thing: `new HashSet<int>(problem.Clues.SelectMany(x => problem.Sets[x]).Distinct())` Unless you're using some new hash-set, I'd say that `Distinct` is redundant here :-P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:55:33.187", "Id": "439752", "Score": "0", "body": "well, ok, I'll take a look... the linq queries I see here are hurting my eyes :-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:59:54.407", "Id": "439753", "Score": "0", "body": "@t3chb0t lol, thanks for having a look. You are right about that Distinct, silly me :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:01:48.743", "Id": "439754", "Score": "4", "body": "_These problems are of limited practical value if any_ -> not this one I reckon. Constraint satisfaction problem solvers are used for many problems, not just puzzles. They are very useful when generating schedules (railways, schools, ..)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:02:18.603", "Id": "439755", "Score": "0", "body": "So much `internal`... this is going to be hard work!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:03:28.130", "Id": "439756", "Score": "0", "body": "@VisualMelon perhaps it would be better to just have the class internal, and instance operations public... not sure, feel free to review me :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:05:30.983", "Id": "439757", "Score": "1", "body": "No, it looks like a sane enough use (but yeah, making the class `internal` would probably be a good idea)... it's just that `internal` means 'this is tricky code I don't trust _you_ to use, but I still need it to couple my classes', and usually this signals lots of (probably necessary) complexity..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:06:55.477", "Id": "439758", "Score": "1", "body": "@VisualMelon That's a good point. using internal too much might lead to not caring at all about encapsulation within the assembly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:16:37.033", "Id": "439759", "Score": "0", "body": "From what wiki says, is this algorithm just a nicer name for _brute-force_... right? _\"the most obvious trial-and-error approach\"_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:20:45.807", "Id": "439760", "Score": "0", "body": "@t3chb0t It's not a brute force. It solves these puzzles on average 30 times faster as brute force." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T02:45:20.843", "Id": "439838", "Score": "0", "body": "Do you happen to have a link to a non-wiki page/article/document that would explain these concepts in a fashion understandable for humans? I sometimes wish there was no wiki because it spams all search results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T07:10:12.977", "Id": "439851", "Score": "1", "body": "@t3chb0t At what insane hour are you awake mate? :o ... here's a link: https://www.ocf.berkeley.edu/~jchu/publicportal/sudoku/0011047.pdf" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T09:41:06.507", "Id": "439873", "Score": "1", "body": "I get up early every day and when the weekend comes... you can't help it, you're awake at the usual hour without an alarm o_O I like this pdf." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T16:32:20.740", "Id": "440731", "Score": "0", "body": "I actually was studing the algorithms for this question but then someone had to post the question about the builder pattern... you know how it ended :P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T16:33:59.223", "Id": "440732", "Score": "0", "body": "@t3chb0t Yeah some things trigger something in you and you transform into .. r3ckEt" } ]
[ { "body": "<h3>SolverOptions</h3>\n\n<blockquote>\n<pre><code>public class SolverOptions\n{\n public int MaxRecursion { get; set; } = -1;\n public int MaxSolutions { get; set; } = -1;\n</code></pre>\n</blockquote>\n\n<p>Instead of using undocumented magic values, why not use <code>uint?</code>?</p>\n\n<p>I'm not sure what <code>MaxRecursion</code> gains you. IMO it would be more useful to have a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.iprogress-1\" rel=\"nofollow noreferrer\">progress report</a> and a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken\" rel=\"nofollow noreferrer\">way to cancel the search</a>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public bool IncludeCluesInSolution = false;\n</code></pre>\n</blockquote>\n\n<p>What's a \"clue\" in a general exact cover problem? I think this is at the wrong level of abstraction.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public bool HasSolutionsExceeded(IEnumerable&lt;ISet&lt;int&gt;&gt; solutions)\n {\n return MaxSolutions &gt; -1 &amp;&amp; solutions.Count() &gt;= MaxSolutions;\n }\n</code></pre>\n</blockquote>\n\n<p>Ugh. This either forces you to evaluate the solution set multiple times (if it's lazy) or it forces you to use a non-lazy <code>IEnumerable</code>, which means caching the full solution set in memory. IMO it would be far preferable for the searcher to return a lazy enumeration and simply keep count of the solutions returned and compare the count to <code>MaxSolutions</code>. Alternatively, and this is what I did with my Java implementation many years ago, the search could take a callback which accepts the solution and returns a <code>bool</code> indicating whether to continue searching.</p>\n\n<hr>\n\n<h3>ICSPSolver</h3>\n\n<blockquote>\n<pre><code>public interface ICSPSolver\n{\n IReadOnlyCollection&lt;ISet&lt;int&gt;&gt; Solve(ExactCover problem, SolverOptions options);\n}\n</code></pre>\n</blockquote>\n\n<p>I'm not convinced by the name. There are constraint satisfaction problems which can't be reduced to exact cover.</p>\n\n<p>See my comments above on preferring to return a lazy <code>IEnumerable</code>, which would mean changing the return type here.</p>\n\n<hr>\n\n<h3>ExactCover</h3>\n\n<blockquote>\n<pre><code>public class ExactCover\n{\n public ISet&lt;int&gt; Constraints { get; }\n public IDictionary&lt;int, ISet&lt;int&gt;&gt; Sets { get; }\n public ISet&lt;int&gt; Clues { get; }\n</code></pre>\n</blockquote>\n\n<p>Why <code>int</code>? Knuth writes in a context in which everything is described in a fairly minimalist imperative language from the 1970s, but this code is in a modern polymorphic language. I would be strongly inclined to make the universe a type parameter, and then if the caller wants to number the elements of the universe and work with <code>int</code>s for speed of comparisons then let them, but don't make it obligatory.</p>\n\n<p>For my taste the properties should all have read-only types. It is unfortunate that .Net doesn't have an <code>IReadOnlySet&lt;T&gt;</code>: I consider that it's worth writing one, and a read-only wrapper for <code>ISet&lt;T&gt;</code>.</p>\n\n<p>I am baffled as to what the three properties represent. As far as I'm concerned the absolutely necessary component of an exact cover problem is an <code>IEnumerable&lt;IEnumerable&lt;TUniverse&gt;&gt;</code> representing the subsets; and the other, optional, component is an <code>IEnumerable&lt;TUniverse&gt;</code> to detect the case where the union of the subsets is missing one or more elements.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public ExactCover(ISet&lt;int&gt; constraints, IDictionary&lt;int, ISet&lt;int&gt;&gt; sets, ISet&lt;int&gt; clues)\n {\n Constraints = constraints;\n Sets = sets;\n Clues = clues;\n }\n</code></pre>\n</blockquote>\n\n<p>There's always a case to be made for copying your inputs to prevent the caller mutating them.</p>\n\n<hr>\n\n<h3>DLXNode</h3>\n\n<blockquote>\n<pre><code>class DLXNode\n{\n internal DLXNode header, row;\n internal DLXNode up, down, left, right;\n</code></pre>\n</blockquote>\n\n<p>See previous comments on using a modern language. I don't believe that it's necessary to manually implement the linked lists of Knuth's description, and by delegating that kind of thing to the library you can save yourself a lot of pain debugging.</p>\n\n<hr>\n\n<h3>DLX</h3>\n\n<blockquote>\n<pre><code>public class DLX : ICSPSolver\n{\n public IReadOnlyCollection&lt;ISet&lt;int&gt;&gt; Solve(ExactCover problem, SolverOptions options)\n {\n var root = Parse(problem);\n</code></pre>\n</blockquote>\n\n<p>I'm intrigued by the name. To me, <code>Parse</code> means transforming a <code>string</code> into the thing it represents. What does it mean to you?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> internal bool CheckForSolution(\n internal DLXNode GetHeaderWithMinimumRowCount(DLXNode root)\n internal void Explore(\n internal void Cover(DLXNode node)\n internal void Uncover(DLXNode node)\n internal DLXNode Parse(ExactCover problem)\n</code></pre>\n</blockquote>\n\n<p>These could, and therefore should, all be <code>static</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var solution = new HashSet&lt;int&gt;(currentSolution);\n if (options.IncludeCluesInSolution)\n {\n foreach (var clue in clues)\n {\n solution.Add(clue);\n }\n }\n</code></pre>\n</blockquote>\n\n<p><code>solution.UnionWith(clues)</code> would be more elegant.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> internal DLXNode GetHeaderWithMinimumRowCount(DLXNode root)\n {\n DLXNode next = null;\n\n foreach (var header in root.Iterate(n =&gt; n.right).Skip(1))\n {\n if (next == null || header.rowCount &lt; next.rowCount)\n {\n next = header;\n }\n }\n\n return next;\n }\n</code></pre>\n</blockquote>\n\n<p>Among the obviously useful things lacking from Linq is a function <code>public static TSource MinBy&lt;TSource, TValue&gt;(this IEnumerable&lt;TSource&gt; elts, Func&lt;TSource, TValue&gt; valuation) where TValue : IComparable&lt;TValue&gt;</code>. I heartily recommend that you factor this function out of <code>GetHeaderWithMinimumRowCount</code> and add it to your utility library.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> foreach (var constraint in problem.Constraints.Where(x =&gt; !givens.Contains(x)))\n</code></pre>\n</blockquote>\n\n<p><code>problem.Constraints.Except(givens)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:46:59.463", "Id": "439763", "Score": "0", "body": "Great review, I have a lot to refactor :) About that readonly set, .NET Core has a _ImmutableHashSet_ which I looked into, but couldn't use in my .NET Framework code. https://docs.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutablehashset-1?view=netcore-2.2. The most interesting improvement to me is using the callback with caller code to steer the algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:50:45.347", "Id": "439764", "Score": "1", "body": "@dfhwze, ooh, I didn't know about that. Thanks. FWIW, you're wrong about not being able to use them in .Net Framework: if you follow the link text \"*about immutable collections and how to install*\" from the page you link, it takes you to a page which says that \"*They're available starting with the .NET Framework 4.5 via NuGet.*\" You have to enable prerelease packages and install `System.Collections.Immutable`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:59:08.213", "Id": "439765", "Score": "0", "body": "Thanks for that tip. _To me, Parse means transforming a string_ => I use Parse because in compilers, an input is 'parsed' into an abstract syntax tree, usually called ASTNode. To me, transforming the Sudoku input (whatever the input may be) to a DLXNode is the same concept." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T09:07:47.600", "Id": "439871", "Score": "0", "body": "_IEnumerable<TUniverse>_ -> this is _ISet<int> Constraints_; _IEnumerable<IEnumerable<TUniverse>>_ -> this is _IDictionary<int, ISet<int>> Sets_. I opted for a dict over enumerable of sets to let consumers of the API decide whether they want to map the matching sets (int, set<int>) using the key (int) or the set (set<int>). For Sudoku, I opted to use the key to map the results back to the board." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T22:40:24.860", "Id": "456148", "Score": "0", "body": "The whole point of Dancing Links is that it's a specific technique of implementing and using linked lists -- specifically, the name refers to the way one can \"cheat\" by not freeing deleted items from a list / modifying their pointers, so that they can be cheaply reinserted (these are the links that dance). If you're going to use generic linked lists from a library, it can hardly be called \"Dancing Links\" anymore." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T23:29:07.990", "Id": "456150", "Score": "0", "body": "@ShreevatsaR, actually I prefer to implement it with hashsets. I do have some sympathy for your etymological argument, but IMO the key feature of algorithm X is the heuristic for deciding in which order to brute force. I see the linked list hacking as more a point of historical interest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-03T23:54:28.583", "Id": "456156", "Score": "0", "body": "@PeterTaylor If talking about \"Algorithm X\" rather than \"dancing links\", sure. But Knuth's intention was to popularize the low-level technique of dancing links. (See the first page of [his 2000 paper](https://arxiv.org/pdf/cs/0011047.pdf) or TAOCP section 7.2.2.1 \"Dancing Links\" (out as Fasc 5 this week, [draft ps.gz online](https://www-cs-faculty.stanford.edu/~knuth/fasc5c.ps.gz).) He introduced Algorithm X (which otherwise has nothing much notable about it; it's pretty much the straightforward approach) only to illustrate it. DL is still more efficient so not only of historical interest IMO." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:40:43.280", "Id": "226324", "ParentId": "226317", "Score": "3" } } ]
{ "AcceptedAnswerId": "226324", "CommentCount": "17", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:28:49.667", "Id": "226317", "Score": "3", "Tags": [ "c#", "programming-challenge", "linked-list", "sudoku", "backtracking" ], "Title": "LeetCode #37: Sudoku as Exact Cover Problem solved using Dancing Links" }
226317
<p>My code is functioning the way I'm expecting, with the <code>if</code>. However, it is not pythonic to me, and that bugs me.</p> <p>The multiple if in the code below are supposed to update a property_id field on a database when reading the csv files, properties.csv. if property_id in the file is equal to '2502', it should update the table tenants of the database with the property_id '95560' instead of '2502' and etc (see code below).</p> <pre><code># -*- coding: utf-8 -*- import csv import io import os from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from io import StringIO import boto3 import psycopg2 from botocore.exceptions import ClientError import replace as rep LOW = 30.0 NEUTRAL = 70.0 CAT = ['OTHERS', 'HSS', 'UTILS', 'TBD', 'IT'] tables_order = ['properties', 'tenants', 'leases', 'managers', 'tenant_area', 'budget', 'tenant_property_occupied_area', 'tenant_client_occupied_area', 'schedule'] tables_fields = { 'leases': ['property_id', 'lease_id', 'break_option', 'charges_amount', 'currency', 'debtor', 'end_date', 'erv_pa', 'floor_area', 'floor_index', 'floor_name', 'lease_status', 'occupational_status', 'rent_amount', 'start_date', 'tenant_id', 'tenant_name'], 'tenants': ['tenant_id', 'tenant_name', 'address', 'total_area', 'debtor', 'currency', 'mobile_phone', 'direct_phone', 'phone', 'contact_name', 'mail', 'property_id'], 'properties': ['property_id', 'comment', 'is_listed', 'property_name', 'address', 'total_area', 'debtor', 'rent_amount', 'charges_amount', 'currency', 'client_name', 'year_constructed', 'budget_used', 'budget_used_date', 'annual_budget', 'year_last_refurbished', 'latitude', 'longitude'], 'managers': ['property_id', 'name', 'role', 'mail', 'phone', 'direct_phone', 'mobile_phone'], 'tenant_area': ['property_id', 'tenant_id', 'area', 'rent_amount', 'rent_exposure', 'area_exposure'], 'budget': ['property_id', 'category', 'budget'], 'tenant_property_occupied_area': ['tenant_id', 'property_id', 'area'], 'tenant_client_occupied_area': ['tenant_id', 'client_name', 'area'], 'schedule': ['Property Ref', 'client_parent_ref', 'Client Ref', 'Client Name', 'Property Name', 'Property Town', 'vat_opted', 'Unit ref', 'Unit Name', 'Tenant Ref', 'Tenant', 'property_type_code', 'Property Manager', 'property_status_code', 'lease ref', 'Lease status', 'ref', 'passing_rent', 'annual_s_c', 'Lease years', 'Lease months', 'Lease days', 'Monthly Rent', 'term_start_date', 'term_end_date', 'next_review_date', 'review_basis', 'outside_1954_act', 'holding_over', 'expiry_date', 'managed_by', 'valuation_date', 'valuation_amount', 'floor_area', 'prime_record', 'measured_in', 'comments', 'credit_controller', 'valuation_effective_date', 'client_type', 'CF team', 'FM team', 'PM team', 'Health &amp; Safety', 'SC auditors', 'Utility recovery', 'Debtor ref- current tenancy', 'Debtor name', 'tenancy.start_date', 'occupation_start_date', 'Review frequency', 'breach status', 'Erv_Psf'] } temp2nd_lst = ['95560','2502','21489','660133','921010','580000','921600','673301','3953','3751','2514','4900'] class Service: def __init__(self, dao): self.dao = dao def process(self): print('Starting') exceptions = io.StringIO() is_there_exceptions = False properties_area_and_rent = {} try: properties_ids = [] for table_name in tables_order: print(table_name) with open('/home/andykw/cloned_projects/dadoo/dadoo-ingest-repmdata/mockdata_fr/' + table_name + '.csv', 'r') as file: # it opens csv files in the directory s = file if os.environ['ORIGIN'] == 'ie': delimiter = ';' else: delimiter = ',' reader = csv.DictReader(s, delimiter=delimiter) for row in reader: if table_name == 'properties': if row['property_id'] not in properties_ids: print('toto') continue elif table_name == 'tenants': # The condition above # check if the name of the table is tenants # if it is the case, the if are doing their work print('tato') if row.get('property_id') == '2502': row.update({'property_id': '95560'}) elif row.get('property_id') == '21489': row.update({'property_id': '2502'}) elif row.get('property_id') == '660133': row.update({'property_id': '21489'}) elif row.get('property_id') == '921010': row.update({'property_id': '660133'}) elif row.get('property_id') == '580000': row.update({'property_id': '921010'}) elif row.get('property_id') == '921600': row.update({'property_id': '580000'}) elif row.get('property_id') == '673301': row.update({'property_id': '921600'}) elif row.get('property_id') == '3953': row.update({'property_id': '673301'}) elif row.get('property_id') == '3751': row.update({'property_id': '3953'}) elif row.get('property_id') == '2514': row.update({'property_id': '3751'}) elif row.get('property_id') == '4900': row.update({'property_id': '2514'}) elif row.get('property_id') == '21065': row.update({'property_id': '4900'}) self.dao.insert(table_name, clean(row), tables_fields[table_name]) d = self.dao.get_most_recent_date_modified(tables_order) self.dao.insert('settings', {'date': d, 'name': 'data_date'}, ['date', 'name']) except Exception as e: print(e) if is_there_exceptions: print('toto') print('Finished') </code></pre> <p>As I said, the <code>if</code>is doing what it should do e.g, catching the property_id like 2502 and row updating it with the property_id that I want. There are only a dozen of examples in this case.</p> <p>However as I said above, I'm looking for something more pythonic and using the list <code>temp2nd_lst</code>.</p> <p>I tried something like the code below</p> <blockquote> <pre><code>properties_ids = [] temp_1st_lst = ['2502','21489','660133','921010','580000','921600','673301','3953','3751','2514','4900','21065'] temp_2nd_lst = ['95560','2502','21489','660133','921010','580000','921600','673301','3953','3751','2514','4900'] i_temp = 1 if table_name == 'tenants': for prop_id in temp_1st_lst: row.update({'property_id': temp_2nd_lst[i_temp]}) i_temp = += 1 </code></pre> </blockquote> <p>Issue is it is looping 12 times, and updating my records with the last <code>property_id</code> of the list, <code>temp_2nd_list</code>, 4900, instead of shuffling the property id like with the if.</p> <p>Any ideas are more than welcomed as I'm trying to figure out how to do in a more pythonic way than using the if.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:05:39.690", "Id": "439766", "Score": "0", "body": "Is your code working as intended? see our help center for more info about how to ask a good question: https://codereview.stackexchange.com/help/dont-ask" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:10:32.327", "Id": "439767", "Score": "1", "body": "Hi @dfhwze, my code is working as intended." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:41:49.827", "Id": "439772", "Score": "1", "body": "I'm not sure why this is being closed for the reasons it is. I can't see anywhere where they indicate that the code isn't working as expected. The very last part isn't working, but I don't think that invalidates it as it isn't the main code up for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:50:01.143", "Id": "439774", "Score": "0", "body": "@Carcigenicate and last but not least, I said explicitly that the last part, was not working and I was not sure what to do. :)" } ]
[ { "body": "<p>Create a dictionary mapping the old property IDs to the new ones, then do a lookup:</p>\n\n<pre><code># I'm only showing few pairs of transformations for brevity.\n# You'll need to expand this to include the rest\nOLD_TO_NEW_IDS = {'2502': '95560',\n '21489': '2502',\n '660133': '21489',\n '921010': '660133'} \n\n# Get the old ID\nold_id = row.get('property_id')\n\n# Do a lookup and get the new ID\nnew_id = OLD_TO_NEW_IDS.get(old_id, None) # Will return None if the lookup failed to find the old ID\n\nif new_id: # Only update if the new ID is not None\n row.update({'property_id': new_id})\n</code></pre>\n\n<p>Having a long dictionary like that in your code is unfortunate though. You may want to consider storing it as a JSON or similar format to file, and loading/parsing it as needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T01:43:36.010", "Id": "439836", "Score": "0", "body": "I'd also make a log entry when an id gets mapped to a new id. Mr. Murphy is known to make typos when updating mappings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T13:31:23.870", "Id": "439886", "Score": "0", "body": "Hi @Carcigenicate, you rock!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T13:32:48.157", "Id": "439887", "Score": "0", "body": "So simple, yet so powerful. I've never seen the lookup as such before. Ty." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T14:21:00.067", "Id": "439891", "Score": "0", "body": "@RootTwo I'm not sure what you're referring to. Who's \"Mr Murphy\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T14:21:57.807", "Id": "439892", "Score": "1", "body": "@AndyK Ya, dictionaries are incredibly useful. Whenever you have two associated pieces of data and need to find the pair of data based one one of the pieces, you should probably be using a dictionary. That scenario is far more common than it sounds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T16:00:58.553", "Id": "439918", "Score": "0", "body": "@Carcigenicate, A reference to [Murphy's Law](https://en.wikipedia.org/wiki/Murphy%27s_law)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:57:04.393", "Id": "226325", "ParentId": "226319", "Score": "4" } } ]
{ "AcceptedAnswerId": "226325", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T15:47:17.207", "Id": "226319", "Score": "2", "Tags": [ "python", "python-3.x", "sql", "csv" ], "Title": "Remapping property IDs when inserting CSV data to a database table" }
226319
<blockquote> <p><em>Note: If you don't know much about Fourier transform algorithms, a simple review of whether I am doing anything inefficient with C++ in general would be appreciated.</em></p> </blockquote> <p>I've been working on implementing an efficient Radix2 Fast Fourier Transform in C++ and I seem to have hit a roadblock. I have optimized it in every possible way I can think of and it is very fast, but when comparing it to the Numpy FFT in Python it is still significantly slower. Note that my FFT is not done in-place, but neither is the Python implementation so I should be able to achieve at least the same efficiency as Numpy.</p> <p>I've already taken advantage of symmetry when the input is a real signal which allows the use of an N/2 point FFT for an N-length real signal, and I also pre-compute all of the twiddle factors and optimize the twiddle factor calculation so redundant twiddle factors are not re-calculated.</p> <p><strong>The code:</strong></p> <pre><code>#include &lt;cassert&gt; #include &lt;complex&gt; #include &lt;vector&gt; // To demonstrate runtime #include &lt;chrono&gt; #include &lt;iostream&gt; static std::vector&lt;std::complex&lt;double&gt;&gt; FFTRadix2(const std::vector&lt;std::complex&lt;double&gt;&gt;&amp; x, const std::vector&lt;std::complex&lt;double&gt;&gt;&amp; W); static bool IsPowerOf2(size_t x); static size_t ReverseBits(const size_t x, const size_t n); std::vector&lt;std::complex&lt;double&gt;&gt; FFT(const std::vector&lt;double&gt;&amp; x) { size_t N = x.size(); // Radix2 FFT requires length of the input signal to be a power of 2 // TODO: Implement other algorithms for when N is not a power of 2 assert(IsPowerOf2(N)); // Taking advantage of symmetry the FFT of a real signal can be computed // using a single N/2-point complex FFT. Split the input signal into its // even and odd components and load the data into a single complex vector. std::vector&lt;std::complex&lt;double&gt;&gt; x_p(N / 2); for (size_t n = 0; n &lt; N / 2; ++n) { // x_p[n] = x[2n] + jx[2n + 1] x_p[n] = std::complex&lt;double&gt;(x[2 * n], x[2 * n + 1]); } // Pre-calculate twiddle factors std::vector&lt;std::complex&lt;double&gt;&gt; W(N / 2); std::vector&lt;std::complex&lt;double&gt;&gt; W_p(N / 4); for (size_t k = 0; k &lt; N / 2; ++k) { W[k] = std::polar(1.0, -2 * M_PI * k / N); // The N/2-point complex DFT uses only the even twiddle factors if (k % 2 == 0) { W_p[k / 2] = W[k]; } } // Perform the N/2-point complex FFT std::vector&lt;std::complex&lt;double&gt;&gt; X_p = FFTRadix2(x_p, W_p); // Extract the N-point FFT of the real signal from the results std::vector&lt;std::complex&lt;double&gt;&gt; X(N); X[0] = X_p[0].real() + X_p[0].imag(); for (size_t k = 1; k &lt; N / 2; ++k) { // Extract the FFT of the even components auto A = std::complex&lt;double&gt;( (X_p[k].real() + X_p[N / 2 - k].real()) / 2, (X_p[k].imag() - X_p[N / 2 - k].imag()) / 2); // Extract the FFT of the odd components auto B = std::complex&lt;double&gt;( (X_p[N / 2 - k].imag() + X_p[k].imag()) / 2, (X_p[N / 2 - k].real() - X_p[k].real()) / 2); // Sum the results and take advantage of symmetry X[k] = A + W[k] * B; X[k + N / 2] = A - W[k] * B; } return X; } std::vector&lt;std::complex&lt;double&gt;&gt; FFT(const std::vector&lt;std::complex&lt;double&gt;&gt;&amp; x) { size_t N = x.size(); // Radix2 FFT requires length of the input signal to be a power of 2 // TODO: Implement other algorithms for when N is not a power of 2 assert(IsPowerOf2(N)); // Pre-calculate twiddle factors std::vector&lt;std::complex&lt;double&gt;&gt; W(N / 2); for (size_t k = 0; k &lt; N / 2; ++k) { W[k] = std::polar(1.0, -2 * M_PI * k / N); } return FFTRadix2(x, W); } static std::vector&lt;std::complex&lt;double&gt;&gt; FFTRadix2(const std::vector&lt;std::complex&lt;double&gt;&gt;&amp; x, const std::vector&lt;std::complex&lt;double&gt;&gt;&amp; W) { size_t N = x.size(); // Radix2 FFT requires length of the input signal to be a power of 2 assert(IsPowerOf2(N)); // Calculate how many stages the FFT must compute size_t stages = static_cast&lt;size_t&gt;(log2(N)); // Pre-load the output vector with the input data using bit-reversed indexes std::vector&lt;std::complex&lt;double&gt;&gt; X(N); for (size_t n = 0; n &lt; N; ++n) { X[n] = x[ReverseBits(n, stages)]; } // Calculate the FFT one stage at a time and sum the results for (size_t stage = 1; stage &lt;= stages; ++stage) { size_t N_stage = static_cast&lt;size_t&gt;(std::pow(2, stage)); size_t W_offset = static_cast&lt;size_t&gt;(std::pow(2, stages - stage)); for (size_t k = 0; k &lt; N; k += N_stage) { for (size_t n = 0; n &lt; N_stage / 2; ++n) { auto tmp = X[k + n]; X[k + n] = tmp + W[n * W_offset] * X[k + n + N_stage / 2]; X[k + n + N_stage / 2] = tmp - W[n * W_offset] * X[k + n + N_stage / 2]; } } } return X; } // Returns true if x is a power of 2 static bool IsPowerOf2(size_t x) { return x &amp;&amp; (!(x &amp; (x - 1))); } // Given x composed of n bits, returns x with the bits reversed static size_t ReverseBits(const size_t x, const size_t n) { size_t xReversed = 0; for (size_t i = 0; i &lt; n; ++i) { xReversed = (xReversed &lt;&lt; 1U) | ((x &gt;&gt; i) &amp; 1U); } return xReversed; } int main() { size_t N = 16777216; std::vector&lt;double&gt; x(N); int f_s = 8000; double t_s = 1.0 / f_s; for (size_t n = 0; n &lt; N; ++n) { x[n] = std::sin(2 * M_PI * 1000 * n * t_s) + 0.5 * std::sin(2 * M_PI * 2000 * n * t_s + 3 * M_PI / 4); } auto start = std::chrono::high_resolution_clock::now(); auto X = FFT(x); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(stop - start); std::cout &lt;&lt; duration.count() &lt;&lt; std::endl; } </code></pre> <p><strong>Output (running a few times and averaging):</strong></p> <blockquote> <p>3671677</p> </blockquote> <p><em>This was compiled in Visual Studio 2019 in Release mode with the</em> <code>/O2</code><em>,</em> <code>/Oi</code> <em>and</em> <code>/Ot</code> <em>optimization compiler flags to try and squeeze as much speed as possible out of it.</em></p> <hr> <p>A comparable snippet of Python code that uses the Numpy FFT is shown below:</p> <pre><code>import numpy as np import datetime N = 16777216 f_s = 8000.0 t_s = 1/f_s t = np.arange(0, N*t_s, t_s) y = np.sin(2*np.pi*1000*t) + 0.5*np.sin(2*np.pi*2000*t + 3*np.pi/4) start = datetime.datetime.now() Y = np.fft.fft(y) stop = datetime.datetime.now() duration = stop - start print(duration.total_seconds()*1e6) </code></pre> <p><strong>Output (running a few times and averaging):</strong></p> <blockquote> <p>2100411.0</p> </blockquote> <hr> <p>As you can see, the Python implementation is still faster by about 43%, but I can't think of any ways my implementation can be improved.</p> <p>From what I understand, the Numpy version is actually implemented with C code underneath so I'm not terribly disappointed in the performance of my own code, but it still leaves me wondering what I am missing that I could still do better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:26:13.270", "Id": "439769", "Score": "1", "body": "Can you give a hint about the used C++ standard (11, 14, 17) Can you use additional libraries such as gsl or abseil?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:32:52.313", "Id": "439770", "Score": "1", "body": "@miscco, C++11 is currently used but C++17 is available. Additional libraries are not out of the question. If they are available through the Conan package manager that would be a huge plus. Also it is important that it stays cross platform compatible so OS specific libraries are a no go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T20:45:08.647", "Id": "439946", "Score": "0", "body": "Radix 2 is a slow algorithm by today's standards" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T21:13:40.650", "Id": "439949", "Score": "0", "body": "You're only letting MSVC's auto-vectorize with SSE2? I'd at least try letting it use AVX2 and maybe a fast-math option. Or preferably a compiler like gcc or clang with `-O3 -march=native -ffast-math`. Or if you have ICC it's well known for good auto-vectorization. NumPy might well be manually vectorized for SSE2 and AVX / AVX2, with intrinsics like `_mm_shuffle_ps()` for SIMD vectors. And `_mm_shuffle_epi8` for bit-reversal using a lookup table for 4-bit chunks. Plain portable ISO C++ can't represent/expose a lot of useful things that modern CPUs can do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T21:19:41.190", "Id": "439951", "Score": "0", "body": "@ScottSeidman, can you provide the names of any faster algorithms? As far as I am aware Radix 2 is essentially the fastest you can get but comes with a restriction that your input length is a power of 2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T21:22:47.580", "Id": "439952", "Score": "0", "body": "@PeterCordes thanks that sounds like some good advice. I'm trying to keep this as portable as possible so portability is one of the main restrictions here. It doesn't have to be lightning fast, but I just want to squeeze as much out of it as I can without having to write any platform specific code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T21:44:20.097", "Id": "439958", "Score": "0", "body": "FFTW, for one example" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T22:44:28.647", "Id": "439963", "Score": "0", "body": "Ok, then you have to realize that by limiting yourself to pure ISO C++, and/or by not even enabling AVX+FMA for the compiler to use, you're leaving significant performance on the table on modern CPUs. That's a tradeoff you sometimes want to make when performance isn't critical and you want a single portable binary. Many other FFT libraries have decided that performance *is* critical and use runtime dispatching to select an optimized version based on what the current CPU can do, or can be statically compiled to use AVX + FMA." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T22:47:05.357", "Id": "439964", "Score": "0", "body": "Writing portable code that can auto-vectorize nicely with (with SSE2 or AVX + FMA, or ARM NEON, or PowerPC Altivec) is possible for some problems, though. So at least try enabling AVX+FMA for your compiler to give it a chance against manually-vectorized runtime-dispatching FFT libraries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T23:30:17.127", "Id": "439970", "Score": "0", "body": "@PeterCordes, I'll look into that. I've never even heard of auto-vectorization which shows how inexperienced I am haha. Sounds like it could make a significant difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T01:02:36.287", "Id": "439977", "Score": "0", "body": "Thank you everyone for all of the very helpful advice. So far after taking a bunch of the advice while still keeping everything generic and cross-platform compatible I've managed to cut down the runtime to about 2.15 million microseconds. (Although my computer is a bit inconsistent so I'm not sure how accurate my results are.) I am still investigating some of the improvements suggested by @harold and imagine I can still get significantly better performance once I do a little more research and get a better understanding of some things!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T11:28:52.810", "Id": "440004", "Score": "0", "body": "Is it possible to swap the loop order for k and n? The W[n * W_offset] could be cached in a variable for the inner loop. Also you can cache W[n * W_offset] * X[k + n + N_stage / 2]; in a variable to avoid double calculation (although the compiler might do that for you)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T13:01:34.503", "Id": "440011", "Score": "0", "body": "@lalala, I just tried switching the loop order and to my surprise it actually drastically increased the runtime! Not sure why. I have done your second suggestion though because the compiler was not doing that for me and it sped things up a bit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-04T00:46:38.600", "Id": "442713", "Score": "0", "body": "@ScottSeidnan, I'm fairly certain FFTW is implemented using a Radix2 algorithm when the input is a length that is a power of 2, but it's significantly faster because it's super optimized for the specific hardware that it gets compiled on. FFTW is not just one algorithm. It is implemented with many algorithms and the best algorithm is selected based on both the length of the input signal and the detected hardware." } ]
[ { "body": "<p>Putting this through the built-in profiler reveals some hot spots. Perhaps surprisingly: <code>ReverseBits</code>. It's not the biggest thing in the list, but it is significant while it shouldn't be.</p>\n\n<p>You could use one of the many alternate ways to implement <code>ReverseBits</code>, or the sequence of bit-reversed indexes (which does not require reversing all the indexes), or the overall bit-reversal permutation (which does not require bit reversals).</p>\n\n<p>For example here is a way to compute the sequence of bit-reversed indexes without explicitly reversing any index:</p>\n\n<pre><code>for (size_t n = 0, rev = 0; n &lt; N; ++n)\n{\n X[n] = x[rev];\n size_t change = n ^ (n + 1);\n#if _WIN64\n rev ^= change &lt;&lt; (__lzcnt64(change) - (64 - stages));\n#else\n rev ^= change &lt;&lt; (__lzcnt(change) - (32 - stages));\n#endif\n}\n</code></pre>\n\n<p>On my PC, that reduces the time from around 2.8 million microseconds to 2.3 million microseconds.</p>\n\n<p>This trick works by using that the XOR between adjacent indexes is a mask of ones up to and including the least significant zero (the +1 carries through the least significant set bits and into that least significant zero), which has a form that can be reversed by just shifting it. The reversed mask is then the XOR between adjacent reversed indexes, so applying it to the current reversed index with XOR increments it.</p>\n\n<p><code>__lzcnt64</code> and <code>_WIN64</code> are for MSVC, you could use more preprocessor tricks to find the right intrinsic and bitness-detection for the current compiler. Leading zero count can be avoided by using <code>std::bitset</code> and its <code>count</code> method:</p>\n\n<pre><code>size_t change = n ^ (n + 1);\nstd::bitset&lt;64&gt; bits(~change);\nrev ^= change &lt;&lt; (bits.count() - (64 - stages));\n</code></pre>\n\n<p><code>count</code> is recognized by GCC and Clang as an intrinsic for <code>popcnt</code>, but it seems not by MSVC, so it is not reliable for high performance scenarios.</p>\n\n<p>Secondly, there is a repeated expression: <code>W[n * W_offset] * X[k + n + N_stage / 2]</code>. The compiler is often relied on to remove such duplication, but here it didn't happen. Factoring that out reduced the time to under 2 million microseconds.</p>\n\n<p>Computing the twiddle factors takes a bit more time than it needs to. They are powers of the first non-trivial twiddle factor, and could be computed iteratively that way. This suffers from some build-up of inaccuracy, which could be improved by periodically resetting to the proper value computed by <code>std::polar</code>. For example,</p>\n\n<pre><code>auto twiddle_step = std::polar(1.0, -2.0 * M_PI / N);\nauto twiddle_current = std::polar(1.0, 0.0);\nfor (size_t k = 0; k &lt; N / 2; ++k)\n{\n if ((k &amp; 0xFFF) == 0)\n twiddle_current = std::polar(1.0, -2.0 * M_PI * k / N);\n W[k] = twiddle_current;\n twiddle_current *= twiddle_step;\n\n // The N/2-point complex DFT uses only the even twiddle factors\n if (k % 2 == 0)\n {\n W_p[k / 2] = W[k];\n }\n}\n</code></pre>\n\n<p>On my PC that reduces the time from hovering around 1.95 million µs to around 1.85 million µs, not a huge difference but easily measurable.</p>\n\n<p>More advanced: use SSE3 for the main calculation, for example (not well tested, but seems to work so far)</p>\n\n<pre><code>__m128d w_real = _mm_set1_pd(W[n * W_offset].real());\n__m128d w_imag = _mm_set1_pd(W[n * W_offset].imag());\n__m128d z = _mm_loadu_pd(reinterpret_cast&lt;double*&gt;(&amp;X[k + n + N_stage / 2]));\n__m128d z_rev = _mm_shuffle_pd(z, z, 1);\n__m128d t = _mm_addsub_pd(_mm_mul_pd(w_real, z), _mm_mul_pd(w_imag, z_rev));\n\n__m128d x = _mm_loadu_pd(reinterpret_cast&lt;double*&gt;(&amp;X[k + n]));\n__m128d t1 = _mm_add_pd(x, t);\n__m128d t2 = _mm_sub_pd(x, t);\n_mm_storeu_pd(reinterpret_cast&lt;double*&gt;(&amp;X[k + n]), t1);\n_mm_storeu_pd(reinterpret_cast&lt;double*&gt;(&amp;X[k + n + N_stage / 2]), t2);\n</code></pre>\n\n<p>That takes it from 1.85 million µs down to around 1.6 million µs on my PC.</p>\n\n<hr>\n\n<p>Using a different algorithm, Stockham algorithm the version from <a href=\"http://wwwa.pikara.ne.jp/okojisan/otfft-en/optimization1.html\" rel=\"nofollow noreferrer\">List-8</a> and some miscellaneous things, the time goes down to 0.9 million µs. It's a huge win already and this is not the best version of the algorithm. The linked website has faster versions with fancier tricks and SIMD too, so it's there if you want it. As a bonus, no bit reversing is used at all, so no need for a compiler-specific intrinsic.</p>\n\n<p>The real work happens here: (taken from the linked website)</p>\n\n<pre><code>void fft0(int n, int s, bool eo, complex_t* x, complex_t* y)\n// n : sequence length\n// s : stride\n// eo : x is output if eo == 0, y is output if eo == 1\n// x : input sequence(or output sequence if eo == 0)\n// y : work area(or output sequence if eo == 1)\n{\n const int m = n / 2;\n const double theta0 = 2 * M_PI / n;\n\n if (n == 2) {\n complex_t* z = eo ? y : x;\n for (int q = 0; q &lt; s; q++) {\n const complex_t a = x[q + 0];\n const complex_t b = x[q + s];\n z[q + 0] = a + b;\n z[q + s] = a - b;\n }\n }\n else if (n &gt;= 4) {\n for (int p = 0; p &lt; m; p++) {\n const complex_t wp = complex_t(cos(p*theta0), -sin(p*theta0));\n for (int q = 0; q &lt; s; q++) {\n const complex_t a = x[q + s * (p + 0)];\n const complex_t b = x[q + s * (p + m)];\n y[q + s * (2 * p + 0)] = a + b;\n y[q + s * (2 * p + 1)] = (a - b) * wp;\n }\n }\n fft0(n / 2, 2 * s, !eo, y, x);\n }\n}\n\nvoid fft(int n, complex_t* x) // Fourier transform\n// n : sequence length\n// x : input/output sequence\n{\n complex_t* y = new complex_t[n];\n fft0(n, 1, 0, x, y);\n delete[] y;\n // scaling removed because OP doesn't do it either\n //for (int k = 0; k &lt; n; k++) x[k] /= n;\n}\n</code></pre>\n\n<p>And here is that wrapper to do a Real FFT with a Complex FFT with half the number of points,</p>\n\n<pre><code>std::vector&lt;std::complex&lt;double&gt;&gt; FFT2(const std::vector&lt;double&gt;&amp; x)\n{\n size_t N = x.size();\n\n // Radix2 FFT requires length of the input signal to be a power of 2\n // TODO: Implement other algorithms for when N is not a power of 2\n assert(IsPowerOf2(N));\n\n // Taking advantage of symmetry the FFT of a real signal can be computed\n // using a single N/2-point complex FFT. Split the input signal into its\n // even and odd components and load the data into a single complex vector.\n std::vector&lt;std::complex&lt;double&gt;&gt; x_p(N / 2);\n std::copy(x.data(), x.data() + x.size(), reinterpret_cast&lt;double*&gt;(x_p.data()));\n\n fft(N / 2, x_p.data());\n\n // Extract the N-point FFT of the real signal from the results \n std::vector&lt;std::complex&lt;double&gt;&gt; X(N);\n X[0] = x_p[0].real() + x_p[0].imag();\n auto twiddle_step = std::polar(1.0, -2.0 * M_PI / N);\n auto twiddle_current = twiddle_step;\n for (size_t k = 1; k &lt; N / 2; ++k)\n {\n auto Wk = twiddle_current;\n // Extract the FFT of the even components\n auto A = std::complex&lt;double&gt;(\n (x_p[k].real() + x_p[N / 2 - k].real()) / 2,\n (x_p[k].imag() - x_p[N / 2 - k].imag()) / 2);\n\n // Extract the FFT of the odd components\n auto B = std::complex&lt;double&gt;(\n (x_p[N / 2 - k].imag() + x_p[k].imag()) / 2,\n (x_p[N / 2 - k].real() - x_p[k].real()) / 2);\n\n // Sum the results and take advantage of symmetry\n X[k] = A + Wk * B;\n X[k + N / 2] = A - Wk * B;\n\n twiddle_current *= twiddle_step;\n }\n\n return X;\n}\n</code></pre>\n\n<p>Using <code>std::copy</code> was faster than a manual loop, and not storing the twiddles was also faster. Of course I used the fast twiddle factor generation scheme (without resets this time as per the comments, of course that's easy to put back in). Avoiding the copy altogether would obviously be better, but then the input data will be turned into its FFT instead of leaving it read-only, it's not a drop-in replacement.</p>\n\n<p>Extracting the Real FFT takes a significant portion of the total time by the way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:46:08.320", "Id": "439773", "Score": "0", "body": "Is there a way that doesn't involve preprocessor tricks to make this cross platform compatible? I'd prefer to avoid using the preprocessor although it's not completely out of the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:59:55.080", "Id": "439776", "Score": "1", "body": "@tjwrona1992 I added an alternative. You could try one of the other permutation algorithms to avoid this problem altogether." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T18:00:15.287", "Id": "439777", "Score": "0", "body": "Thanks this all looks like very useful advice! I'll try to take advantage of some of it and let you know how it goes. Out of curiosity, how did you know the compiler didn't factor out the duplicated code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T18:05:39.483", "Id": "439780", "Score": "3", "body": "@tjwrona1992 by proof-reading the assembly code, painful as it was" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T18:11:07.477", "Id": "439782", "Score": "0", "body": "Do you know where I can find examples of other permutation algorithms to do the bit reversal?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T18:27:03.573", "Id": "439786", "Score": "0", "body": "@tjwrona1992 some are described in [Bit Reversal on\nUniprocessors](https://www.hpl.hp.com/techreports/93/HPL-93-89.pdf)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T01:11:35.857", "Id": "439829", "Score": "0", "body": "That last part goes way over my head but is definitely very interesting. I'm sure I will be revisiting this when I have more experience! I do have one question about the bit reversal though. Is there any way to do it without the hardcoded 64? Wouldn't this break if it were compiled in a 32 bit environment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T01:16:45.463", "Id": "439830", "Score": "2", "body": "@tjwrona1992 yes good point, would you accept working with `uint32_t`? It can be made size-adaptive but at the cost of more verbosity.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T01:19:22.573", "Id": "439831", "Score": "0", "body": "Hmmm... when I actually use this I don't think I will need 100% maximum efficiency for it to still be very useful so I would prefer to be size adaptive as long as it is more efficient than the implementation I have in the question as asked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T03:05:40.020", "Id": "439840", "Score": "0", "body": "Also even with the cumulative error if you just iteratively calculate the twiddle factors, with any reasonably sized FFT will it make the results noticeably off if you don't correct for it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T03:19:36.993", "Id": "439841", "Score": "0", "body": "@tjwrona1992 it's a visible difference if you print the numbers to 10 digits or so (at the size used in the benchmark), if you're OK with that you could also look into doing the whole thing with `float`, the memory savings alone would already make it faster and with SSE there are further benefits" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T15:10:48.337", "Id": "439902", "Score": "0", "body": "For a cross platform / both 32 and 64 bit solution would there be any issues using the `bitset` style way of doing things with `std::bitset<sizeof(size_t) * 8>` for the size? This seems to work for me and is faster than the implementation I originally had and I don't see why this wouldn't work in any situation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T15:17:39.780", "Id": "439905", "Score": "0", "body": "@tjwrona1992 I don't think the `bitset` version even needs bitness-adaptiveness, having it still be 64 bit on a 32 bit platform wouldn't break it (unlike the 64bit intrinsic which just doesn't exist in 32bit mode)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T15:23:20.390", "Id": "439906", "Score": "0", "body": "Yeah I guess that's true, but if its adaptive maybe it'll continue to work when computers support 128 bits sometime in the distant future hahaha" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T23:11:20.587", "Id": "439966", "Score": "0", "body": "BTW I just tried a different algorithm that is more cache-aware and it ran in 0.6 million µs (not even a very fancy one), but it also gave totally different results (not just a matter of scaling). IDK why. But, clearly this is nowhere near how fast it could be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T23:23:12.980", "Id": "439967", "Score": "0", "body": "When you say cache aware do you mean just caching the twiddle factor calculations so if you run it a second time it doesn't need to recalculate them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T23:29:24.247", "Id": "439968", "Score": "0", "body": "@tjwrona1992 I mean avoiding most of the huge passes over the entire array, by not going stage-by-stage, for example like using a depth-first order or Stockham (which also avoids the bit reversing stuff)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T23:31:52.693", "Id": "439971", "Score": "0", "body": "Oh man, that sounds like something I should really learn about. Do you have any example code? I'll start Googling around. Thanks again for all the good advice!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T21:20:12.980", "Id": "440087", "Score": "0", "body": "I've managed to come up with an iterative implementation of the Stockham FFT but it only marginally improved the runtime. It does however look a lot cleaner. When you say depth first are you referring to using a recursive approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T21:27:19.543", "Id": "440088", "Score": "0", "body": "@tjwrona1992 that's one option, in principle it should be possible to do it iteratively, I'm not sure how to work out the index arithmetic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T21:29:48.950", "Id": "440089", "Score": "0", "body": "I guess what I'm confused about is how would a depth first traversal speed things up in this situation? Don't the same number of calculations still need to be performed either way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T21:57:39.973", "Id": "440094", "Score": "0", "body": "@tjwrona1992 yes but the difference is that the results of the small stages are often immediately reused when they are still cached, instead of computing them all at once which basically guarantees that most of them have been pushed out of the cache by the time they are used" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T22:52:46.997", "Id": "440102", "Score": "0", "body": "Alright I'll look into a depth first approach, but I've already tried recursion and that seemed to actually perform worse so I'd have to figure out an iterative approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T23:19:11.730", "Id": "440286", "Score": "0", "body": "I agree that extracting the Real FFT takes a significant portion of the total time, but it still seems faster than simply adding a 0 valued complex part to the real input and running it through the complex FFT." } ], "meta_data": { "CommentCount": "24", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:39:33.080", "Id": "226329", "ParentId": "226323", "Score": "19" } }, { "body": "<p>You should be able to work inplace by utilizing the fact that std::complex has a predefined layout. Therefore you can actually cast between an array of double and an array of (half as many) complex numbers.</p>\n\n<pre><code>std::vector&lt;std::complex&lt;double&gt;&gt; a(10);\ndouble *b = reinterpret_cast&lt;double *&gt;(a.data());\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>To be more clear I would write</p>\n\n<pre><code>span&lt;std::complex&lt;double&gt;&gt; x_p(reinterpret_cast&lt;std::complex&lt;double&gt;*&gt;(x.data()), x.size() / 2);\n</code></pre>\n\n<p>This works in both ways. To enable safe and modern features you should use a span object. Unfortunately <code>std::span</code> is only available in C++20 so you should either write your own (which is a nice exercise) or have a look at <code>abseil::span</code> or <code>gsl::span</code>.</p>\n\n<p>The code to implement those is rather minimal. With that you can remove two copies from your code</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T18:01:43.980", "Id": "439779", "Score": "0", "body": "Are you saying replace `vector` with `span`? I haven't used `span` before. I'll look into it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T18:22:14.630", "Id": "439784", "Score": "1", "body": "No, A span is non-owning. But rather than copying the data into `x_p` you should create a `span` that reinterprests the data in `x` as an array of `std::complex`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T23:09:00.133", "Id": "439819", "Score": "0", "body": "Ahh I see, maybe I will implement another one that does it in place like that. But I would also like to have the option to do it out of place as well" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T01:34:24.183", "Id": "439833", "Score": "0", "body": "Do any compilers already support C++20? I didn't think it was officially released yet" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T06:45:12.033", "Id": "439850", "Score": "0", "body": "@tjwrona1992 have a look here: https://en.cppreference.com/w/cpp/compiler_support" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T00:56:32.923", "Id": "439975", "Score": "0", "body": "Is `reinterpret_cast` from `complex double*` to `double*` strict-aliasing UB, or does ISO C++ say that `complex T` and `T` are alias-compatible? Either way it's safe in Visual C++ which allows any/all aliasing and pointer-casting type punning. But I think the OP is trying to write portable code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T01:01:12.577", "Id": "439976", "Score": "2", "body": "@PeterCordes there is the [array-oriented access](https://en.cppreference.com/w/cpp/numeric/complex#Array-oriented_access) thing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T01:12:20.730", "Id": "439978", "Score": "0", "body": "@harold: interesting, yeah for `std::complex<double>` that does mean it's safe since C++11. The cppref wording for C++ seems to imply that it's also safe to do that in C11 with `_Complex double`, but [the cppref page for C](https://en.cppreference.com/w/c/numeric/complex) doesn't mention that. I didn't check the ISO standard." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T17:49:19.163", "Id": "226330", "ParentId": "226323", "Score": "4" } }, { "body": "<ul>\n<li><p>These lines:</p>\n\n<pre><code>size_t N_stage = static_cast&lt;size_t&gt;(std::pow(2, stage));\nsize_t W_offset = static_cast&lt;size_t&gt;(std::pow(2, stages - stage));\n</code></pre>\n\n<p>should not use floating-point math because they can be inaccurate. Instead use pure integer arithmetic:</p>\n\n<pre><code>size_t N_stage = static_cast&lt;size_t&gt;(1) &lt;&lt; stage;\nsize_t W_offset = static_cast&lt;size_t&gt;(1) &lt;&lt; (stages - stage);\n</code></pre></li>\n<li><p>Each iteration of your loop <code>for (size_t stage = 1; stage &lt;= stages; ++stage)</code> will linearly traverse the entire vector once. But this is not optimal if you consider the memory hierarchy. It would be a large change in your code, but you could rework the memory access pattern so that you transform increasingly larger blocks. This technique is known as a <a href=\"https://en.wikipedia.org/wiki/Cache-oblivious_algorithm\" rel=\"nofollow noreferrer\">cache-oblivious algorithm</a>.</p></li>\n<li><p>As a matter of personal taste, I would do <code>using std::vector</code> and <code>using std::complex</code> because they are referred to so many times in the code.</p></li>\n<li><p>Size 2 and size 4 DFTs have trivial integer twiddle factors (without irrationals), so you could special-case them to save some multiplications. You can use the formulas above to special-case your outer loop when <code>stage = 1</code> (length-2 DFT) and <code>stage = 2</code> (length-4 DFT). I have a <a href=\"https://www.nayuki.io/page/fast-fourier-transform-in-x86-assembly\" rel=\"nofollow noreferrer\">working example</a> on another page.</p>\n\n<p>The DFT of the length-2 complex vector [x0, x1] looks like this:</p>\n\n<pre><code>X0 = x0 + x1\nX1 = x0 - x1\n</code></pre>\n\n<p>The DFT of the length-4 complex vector [x0, x1, x2, x3] looks like this:</p>\n\n<pre><code>X0 = x0 + x1 + x2 + x3\nX1 = x0 - i*x1 - x2 + i*x3\nX2 = x0 - x1 + x2 - x3\nX3 = x0 + i*x1 - x2 - x*x3\n</code></pre>\n\n<p>If a complex number is represented as a pair of real numbers in rectangular form, then multiplication by <em>i</em> is just a matter of swapping the real/imaginary parts and negating the correct part - so no multiplication or addition is needed for this operation.</p></li>\n<li><p>The famous FFTW library has a bunch of speedup techniques, and there are articles you can find online that talk about how they work.</p></li>\n<li><p>Overall your <code>FFTRadix2()</code> looks quite similar to <a href=\"https://www.nayuki.io/page/free-small-fft-in-multiple-languages\" rel=\"nofollow noreferrer\">my</a> <a href=\"https://www.nayuki.io/res/free-small-fft-in-multiple-languages/FftComplex.cpp\" rel=\"nofollow noreferrer\">FftComplex.cpp</a> <code>Fft::transformRadix2()</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T21:31:22.347", "Id": "439953", "Score": "0", "body": "Thanks @Nayuki! There is a lot here so I will reply with a comment per bullet. I have done some refactoring already which took care of bullet 1." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T21:32:00.400", "Id": "439954", "Score": "0", "body": "bullet 2 is interesting and I'll have to do more research on that. I'm still fairly inexperienced when it comes to DSP algorithms, but I'm working my way through a book and learning a lot." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T21:32:12.497", "Id": "439955", "Score": "0", "body": "bullet 3 I agree, I will likely add using statements because it is a bit cumbersome haha" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T21:32:20.550", "Id": "439956", "Score": "0", "body": "bullet 4, could you possibly elaborate on this? I'm not sure I fully understand what you mean by this but it sounds interesting" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T21:33:10.190", "Id": "439957", "Score": "2", "body": "bullet 5, I actually stumbled across that library when I was part-way through writing mine and used it as a reference. It was VERY helpful! Thank you! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-26T20:20:07.333", "Id": "441230", "Score": "0", "body": "If you don't mind me asking, what is the reason for the `temp %= static_cast<unsigned long long>(n) * 2;` line in your Bluestein FFT implementation? I've been working on a Bluestein implementation of my own and I can't quite figure out why that line is necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-27T04:31:26.870", "Id": "441255", "Score": "0", "body": "@tjwrona1992 Regarding Bluestein, the modulo is useful because it makes floating-point trigonometry more accurate. Basically if you look at sin(0.1) versus sin(0.1 + 2*PI) when calculated on a computer, the former is more accurate due to finite floating-point precision. So I chose to do a reduction over integers (which is exact) before calling the trigonometric function." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T17:28:40.583", "Id": "226386", "ParentId": "226323", "Score": "8" } } ]
{ "AcceptedAnswerId": "226329", "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T16:19:35.740", "Id": "226323", "Score": "15", "Tags": [ "c++", "performance", "algorithm", "signal-processing", "complex-numbers" ], "Title": "Radix2 Fast Fourier Transform implemented in C++" }
226323
<p>I have an asp.net web api. I would like to log errors into a file. So I decided to use NLog. I already have UnhandledExceptionHandler so I added NLog as follows. I removed all the try/catch in order to log from a single point, just inside the handler. </p> <p>Would you please have a look at my code? Is it good enough?</p> <pre><code>using System; namespace Game.Handlers { public class UnhandledExceptionLogger : ExceptionLogger { private static Logger logger = LogManager.GetCurrentClassLogger(); public override void Log(ExceptionLoggerContext context) { var ex = context.Exception; string strLogText = FormatException(ex); var requestedURi = (string)context.Request.RequestUri.AbsoluteUri; var requestMethod = context.Request.Method.ToString(); var timeUtc = DateTime.Now; SqlErrorLogging sqlErrorLogging = new SqlErrorLogging(); ApiError apiError = new ApiError() { Message = strLogText, RequestUri = requestedURi, RequestMethod = requestMethod, TimeUtc = DateTime.Now }; //sqlErrorLogging.InsertErrorLog(apiError); //NLOG logger.Error(strLogText + Environment.NewLine + DateTime.Now); } private string FormatException(Exception ex, int depth = 0) { var indent = ""; if (depth &gt; 0) indent.PadRight(depth * 4); var sb = new StringBuilder(); IndentLine($"Source --- {ex.Source}"); IndentLine($"StackTrace --- {ex.StackTrace}"); IndentLine($"TargetSite --- {ex.TargetSite}"); if (ex.InnerException != null) { IndentLine("--- Inner Exception ---"); sb.Append(FormatException(ex.InnerException, depth + 1)); IndentLine("--- End Inner Exception ---"); } if (ex.Message != null) { IndentLine($"Message --- {ex.Message}"); } return sb.ToString(); void IndentLine(string s) { sb.Append(indent); sb.AppendLine(s); } } } } </code></pre> <p>Here is the sample NLog config:</p> <pre><code>&lt;nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;targets&gt; &lt;target name="logfile" xsi:type="File" fileName="${basedir}/MyLogs/${date:format=yyyy-MM-dd}-api.log" /&gt; &lt;target name="eventlog" xsi:type="EventLog" layout="${message}" log="Application" source=" GamePIN Api Services" /&gt; &lt;target name="database" type="Database" connectionString="Data Source=(localdb)\MSSQLLocalDB;Database=Game; Initial Catalog=GameAPI;MultipleActiveResultSets=True;"&gt; &lt;commandText&gt; insert into ExceptionLog ([TimeStamp],[Level],Logger, [Message], UserId, Exception, StackTrace) values (@TimeStamp, @Level, @Logger, @Message, case when len(@UserID) = 0 then null else @UserId end, @Exception, @StackTrace); &lt;/commandText&gt; &lt;parameter name="@TimeStamp" layout="${date}" /&gt; &lt;parameter name="@Level" layout="${level}" /&gt; &lt;parameter name="@Logger" layout="${logger}" /&gt; &lt;parameter name="@Message" layout="${message}" /&gt; &lt;parameter name="@UserId" layout="${mdc:user_id}" /&gt; &lt;parameter name="@Exception" layout="${exception}" /&gt; &lt;parameter name="@StackTrace" layout="${stacktrace}" /&gt; &lt;dbProvider&gt;System.Data.SqlClient&lt;/dbProvider&gt; &lt;/target&gt; &lt;/targets&gt; &lt;rules&gt; &lt;!-- I am adding my 3 logging rules here --&gt; &lt;logger name="*" minlevel="Error" writeTo="database" /&gt; &lt;logger name="*" minlevel="Error" writeTo="logfile" /&gt; &lt;logger name="*" minlevel="Error" writeTo="eventlog" /&gt; &lt;/rules&gt; &lt;/nlog&gt; </code></pre>
[]
[ { "body": "<p>The variable <code>ex</code> is not used anywhere else, so it can be in-lined.</p>\n\n<pre><code>string strLogText = FormatException(context.Exception);\n</code></pre>\n\n<p>The multiple calls to <code>DateTime.Now</code> will give different time stamps.</p>\n\n<p>Hold on to the timestamp in one variable early in the function and reuse that.</p>\n\n<p>It was already assigned here</p>\n\n<pre><code> var timeUtc = DateTime.Now;\n</code></pre>\n\n<p>so use that </p>\n\n<pre><code>//...\n\nApiError apiError = new ApiError()\n{\n Message = strLogText,\n RequestUri = requestedURi,\n RequestMethod = requestMethod,\n TimeUtc = timeUtc\n};\n\n//...\n</code></pre>\n\n<p>Given the variable name, the assumption is that the timestamp was meant to be UTC, which would mean that it should be using <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.datetime.utcnow?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>DateTime.UtcNow</code></a></p>\n\n<p>The SQL error logging <em>(though commented out)</em> can be encapsulated into its own function/concern</p>\n\n<pre><code>private void LogSQL(string message, HttpRequestMessage request, DateTime timestamp) {\n var requestedURi = (string)request.RequestUri.AbsoluteUri;\n var requestMethod = request.Method.ToString();\n SqlErrorLogging sqlErrorLogging = new SqlErrorLogging();\n ApiError apiError = new ApiError() {\n Message = message,\n RequestUri = requestedURi,\n RequestMethod = requestMethod,\n TimeUtc = timestamp\n };\n //sqlErrorLogging.InsertErrorLog(apiError);\n}\n</code></pre>\n\n<p>This can be abstracted out into its own service/concern if so desired</p>\n\n<p>The above and a few minor changes results in a refactoring of</p>\n\n<pre><code>public class UnhandledExceptionLogger : ExceptionLogger {\n private static readonly Logger logger = LogManager.GetCurrentClassLogger();\n\n public override void Log(ExceptionLoggerContext context) {\n DateTime timestamp = DateTime.UtcNow;\n string strLogText = FormatException(context.Exception); \n //SQL\n SqlLog(strLogText, context.Request, timestamp);\n //NLOG\n NLog(logger, strLogText, timestamp);\n }\n\n private void NLog(Logger logger, string message, DateTime timestamp) {\n var sb = new StringBuilder();\n sb.AppendLine(message);\n sb.AppendLine(timestamp);\n logger.Error(sb.ToString());\n }\n\n private void SqlLog(string message, HttpRequestMessage request, DateTime timestamp) {\n var requestedURi = (string)request.RequestUri.AbsoluteUri;\n var requestMethod = request.Method.ToString();\n SqlErrorLogging sqlErrorLogging = new SqlErrorLogging();\n ApiError apiError = new ApiError() {\n Message = message,\n RequestUri = requestedURi,\n RequestMethod = requestMethod,\n TimeUtc = timestamp\n };\n //sqlErrorLogging.InsertErrorLog(apiError);\n }\n\n private string FormatException(Exception ex, int depth = 0) {\n //... omitted for brevity\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T07:48:46.207", "Id": "439859", "Score": "1", "body": "Thank you @Nkosi, I wonder if managing errors from a single point like UnhandledExcepitonHandler is a good idea? As a result I removed all try/catch block in the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T08:11:28.100", "Id": "439865", "Score": "0", "body": "I suggest reading up on cross cutting concerns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T08:40:14.443", "Id": "439868", "Score": "0", "body": "Should I change timestamp to this `sb.AppendLine(timestamp.ToLongDateString());`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T07:57:55.300", "Id": "439990", "Score": "0", "body": "I think all the exceptions are not handled in UnhandledExceptionLogger. Would it be correct if I add logging also inside of GlobalExceptionHandler? What is your opinion?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T04:16:53.540", "Id": "226362", "ParentId": "226333", "Score": "1" } } ]
{ "AcceptedAnswerId": "226362", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T18:44:53.943", "Id": "226333", "Score": "2", "Tags": [ "c#", "logging", "asp.net-web-api" ], "Title": "Asp.net web API Nlog implementation with UnhandledExceptionHandler" }
226333
<p>I am trying to solve the question at</p> <p>:<a href="https://leetcode.com/problems/rotate-list/" rel="noreferrer">https://leetcode.com/problems/rotate-list/</a></p> <h2>Question:</h2> <blockquote> <p>Given a linked list, rotate the list to the right by k places, where k is non-negative.</p> <p>Example 1:</p> <ul> <li>Input: <code>1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;NULL</code>, <code>k = 2</code> </li> <li>Output: <code>4-&gt;5-&gt;1-&gt;2-&gt;3-&gt;NULL</code></li> </ul> <p>Explanation:</p> <ul> <li>rotate 1 steps to the right: <code>5-&gt;1-&gt;2-&gt;3-&gt;4-&gt;NULL</code> </li> <li>rotate 2 steps to the right: <code>4-&gt;5-&gt;1-&gt;2-&gt;3-&gt;NULL</code></li> </ul> </blockquote> <pre><code>//public class ListNode //{ // public int val; // public ListNode next; // public ListNode(int x) { val = x; } //} //k = number of places //head =Given Linked List public ListNode RotateRight(ListNode head, int k) { if (k &gt; 0 &amp;&amp; head != null) { ListNode tail = head, RotatedList = null, kthnode = head, kthPrevNode = head; int listLength = 0; while (tail != null) { listLength += 1; tail = tail.next; } k = k % listLength; if (k == 0 || listLength == 0) { return head; } for (int i = 0; i &lt; listLength - k; i++) { kthPrevNode = kthnode; kthnode = kthnode.next; } RotatedList = kthnode; kthPrevNode.next = null; while (kthnode.next != null) { kthnode = kthnode.next; } kthnode.next = head; return RotatedList; } return head; } } } </code></pre> <p>I have passed all test cases but I am looking to improve code efficiency and time complexity,Kindly let me know if there are any bad practices as well</p>
[]
[ { "body": "<blockquote>\n<pre><code> if (k &gt; 0 &amp;&amp; head != null) {\n ...\n return RotatedList;\n\n }\n\n return head;\n</code></pre>\n</blockquote>\n\n<p>would be clearer (and more consistent with the other special case) as</p>\n\n<pre><code> if (k &lt;= 0 || head == null) {\n return head;\n }\n\n ...\n return RotatedList;\n</code></pre>\n\n<p>(although really if <code>k &lt; 0</code> I think it should <code>throw new ArgumentOutOfRangeException(nameof(k))</code>).</p>\n\n<hr>\n\n<blockquote>\n<pre><code> ListNode tail = head,\n RotatedList = null,\n kthnode = head,\n kthPrevNode = head;\n</code></pre>\n</blockquote>\n\n<p>Most of these don't need to be declared so early. Declaring variables as late as possible (and, more generally, in the narrowest scope possible) helps to reduce cognitive load when maintaining the code.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> int listLength = 0;\n while (tail != null) {\n listLength += 1;\n tail = tail.next;\n }\n</code></pre>\n</blockquote>\n\n<p>This would be worth factoring out as a separate method <code>Length(ListNode head)</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> k = k % listLength;\n if (k == 0 || listLength == 0) {\n return head;\n }\n</code></pre>\n</blockquote>\n\n<p>This is sort-of buggy. If <code>listLength == 0</code> then <code>k % listLength</code> will throw an <code>ArithmeticException</code>. <em>However</em>, you can never reach here in that case, because <code>listLength == 0</code> is equivalent to <code>head == null</code>, and that was already handled in the first special case. To remove confusion, delete <code>|| listLength == 0</code>. If you want to validate that condition, insert <code>System.Diagnostics.Debug.Assert(listLength &gt; 0);</code> <em>before</em> the <code>%</code> line.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> for (int i = 0; i &lt; listLength - k; i++) {\n\n kthPrevNode = kthnode;\n\n kthnode = kthnode.next;\n\n }\n</code></pre>\n</blockquote>\n\n<p>It's not actually necessary to track two nodes here. The invariant is that <code>kthPrevNode.next == kthnode</code>, so it suffices to track <code>kthPrevNode</code>.</p>\n\n<p>Also, the blank lines seem excessive to me.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> RotatedList = kthnode;\n</code></pre>\n</blockquote>\n\n<p>It's conventional in C# that local variable names start with a lower case letter, so to avoid confusion I would rename <code>RotatedList</code> to <code>rotatedList</code> (or perhaps <code>rotatedHead</code>).</p>\n\n<hr>\n\n<p>There are only two things where I can see that the efficiency can be improved: one is eliminating <code>kthnode</code> in the loop, as commented above; the other would be to hang on to the last node when finding the length, so that you don't need to find it a second time in the last few lines. (That would imply changing the factored out method to return an <code>(int, ListNode)</code> tuple).</p>\n\n<p>As for time complexity, it's already optimal: linear time. Good job!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T19:55:34.303", "Id": "440080", "Score": "0", "body": "Thanks for the input,My Team lead always suggests to declare variables at top since most of the projects have huge number of lines and it would be easy for the developers to understand and maintain the code,I kind of curious is this a better practice for large programs" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T20:13:06.150", "Id": "440082", "Score": "0", "body": "@MANOJVARMA, as far as I'm concerned, declaring variables at the top is a necessary evil in JavaScript (for reasons I won't go into), but a bad idea in general. I wonder whether maybe there's a miscommunication: perhaps your team lead was talking about laying out a *class* with the *fields* in a predictable place? If a method is so long that you can't see where the variables you're using were declared, it's time to ask whether to refactor it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T23:57:20.053", "Id": "440109", "Score": "0", "body": "I am sorry if I confused you,I meant the layout of the class.Is it a good practice to declare all the fields at the top of the class which has few methods or can we declare the fields when ever they are required ,since we will be able to track them easily" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T20:33:08.483", "Id": "440271", "Score": "0", "body": "It's not uncommon for style guides to mandate an order of each type of member in a class. I think that's something where consistency within a project is the most important guide." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T12:43:44.320", "Id": "440346", "Score": "0", "body": "Could you please clarify how it is possible to track just one variable in the loop? It appears that you still need to know what is the previous value of the pointer somehow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T13:32:44.603", "Id": "440360", "Score": "0", "body": "@Ilkhd, you *only* need to know what the \"previous\" value is." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T20:03:32.353", "Id": "226337", "ParentId": "226334", "Score": "7" } }, { "body": "<ul>\n<li><p>Using an uppercase name for a variable is a bad practise; should be <code>rotatedList</code> or preferably <code>res</code> for result or something similar.</p></li>\n<li><p>Separate your instantiations with semicolons:</p></li>\n</ul>\n\n<pre class=\"lang-cs prettyprint-override\"><code> ListNode tail = head;\n ListNode rotatedList = null;\n ListNode kthnode = head;\n ListNode kthPrevNode = head;\n</code></pre>\n\n<ul>\n<li><p>Your naming of head and tail is confusing. Consider renaming them.</p></li>\n<li><p>Use <code>if (k &lt;= 0 || head == null) return ...;</code> rather than having a huge if embracing all the method.</p></li>\n<li><p>Use preincrements <code>listLength += 1;</code> <span class=\"math-container\">\\$\\to\\$</span> <code>++listLength;</code>. You can also name that variable just <code>length</code> (it's obvious we're talking about lists).</p></li>\n<li><p>Your variable <code>kthPrevNode</code> seems useless. You should remove it.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T20:04:11.380", "Id": "226338", "ParentId": "226334", "Score": "6" } }, { "body": "<h3>Performance optimization</h3>\n\n<blockquote>\n<pre><code>int listLength = 0;\nwhile (tail != null) {\n listLength += 1;\n tail = tail.next;\n}\n</code></pre>\n</blockquote>\n\n<p>Since <code>head != null</code> we can start listLength at 1 and keep our tail by checking <code>tail.next != null</code> rather than <code>tail != null</code>.</p>\n\n<pre><code>int listLength = 1;\nwhile (tail.next != null) {\n listLength += 1;\n tail = tail.next;\n}\n</code></pre>\n\n<p>Now we no longer have to search for <code>kthnode</code> because it's <code>tail</code>.</p>\n\n<blockquote>\n<pre><code>// no longer required\nwhile (kthnode.next != null) {\n kthnode = kthnode.next;\n}\nkthnode.next = head;\n</code></pre>\n</blockquote>\n\n<p>Instead, we can now append the old head to the tail.</p>\n\n<pre><code>tail.next = head;\n</code></pre>\n\n<h3>Misc</h3>\n\n<ul>\n<li>Since the challenge uses mathematical style variable names, such as <code>k</code>, I suggest to rename <code>listLength</code> to <code>n</code>.</li>\n<li>The challenge states <code>k</code> can be asserted non-negative, so I presume <code>k &gt; 0</code>. On the other hand, your method is public, so any input could be provided. The challenge does not specify how to handle 'wrong' input. Several ways to perform the argument checks have already been suggested in other answers. One other possibility is to use a sand-box. Left-rotations (<code>k &lt; 0</code>) are inversional equivalents of right-rotations. So the following relaxation on <code>k</code> deals with any right-rotation, even the ones specified as left-rotation: <code>k = (k % n + n) % n;</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T13:28:37.700", "Id": "439884", "Score": "0", "body": "I would follow C# best practices and use meaningful variable names rather than adhere to the challenge's mathematical style names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T13:29:24.070", "Id": "439885", "Score": "0", "body": "`k` must be non-negative does not me that `k > 0`. I see nothing that prevents `k = 0` in the challenge." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T14:51:44.517", "Id": "439900", "Score": "0", "body": "0 is both negative as positive, so non-negative means strict positive k > 0." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T21:42:43.633", "Id": "226347", "ParentId": "226334", "Score": "3" } }, { "body": "<p>There are not much to add to what have already been said about coding style and conventions.</p>\n\n<p>A little optimization on the input check could be that if <code>head.next == null</code> then you can leave early as well:</p>\n\n<pre><code> if (head == null || head.next == null || k &lt;= 0)\n return head;\n</code></pre>\n\n<p>Now it's known that there are at least two elements in the list, so calculating the length can be done as:</p>\n\n<pre><code> ListNode runner = head.next;\n int length = 2;\n\n while (runner.next != null)\n {\n runner = runner.next;\n length++;\n }\n</code></pre>\n\n<p>and with the <code>length</code> - the offset from the current head to the new head can be calculated:</p>\n\n<pre><code> int offset = length - k % length;\n if (offset == 0)\n return head;\n</code></pre>\n\n<p>and if <code>zero</code> it's time to leave without any changes.</p>\n\n<p>Remaining is to iterate down to the new head, but before that, the current tails next it set to point to head, so the list forms a loop:</p>\n\n<pre><code> runner.next = head;\n</code></pre>\n\n<p>Then loop to the new head:</p>\n\n<pre><code> runner = head;\n while (offset &gt; 1)\n {\n runner = runner.next;\n offset--;\n }\n</code></pre>\n\n<p>and at last the new head and tail are established:</p>\n\n<pre><code> head = runner.next;\n runner.next = null;\n\n return head;\n</code></pre>\n\n<hr>\n\n<p>Put together it could look like:</p>\n\n<pre><code>public ListNode RotateRightHH(ListNode head, int k)\n{\n if (head == null || head.next == null || k &lt;= 0)\n return head;\n\n ListNode runner = head.next;\n int length = 2;\n\n while (runner.next != null)\n {\n runner = runner.next;\n length++;\n }\n\n int offset = length - k % length;\n if (offset == 0)\n return head;\n\n runner.next = head;\n\n runner = head;\n while (offset &gt; 1)\n {\n runner = runner.next;\n offset--;\n }\n\n head = runner.next;\n runner.next = null;\n\n return head;\n}\n</code></pre>\n\n<p>What is done in the above differs not much from your version, but the use of a lot fewer variables and maybe some clearer names makes it - IMO - a more easy to follow picture of the method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T19:35:26.453", "Id": "440078", "Score": "1", "body": "Thanks for the input .This is much clear than my version" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T16:49:47.580", "Id": "226441", "ParentId": "226334", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T18:57:19.400", "Id": "226334", "Score": "7", "Tags": [ "c#", "programming-challenge", "linked-list" ], "Title": "Rotate List by K places" }
226334
<p>The requirement is to find the square root of a positive integer using binary search and the math property that square root of a number <code>n</code> is between <code>0</code> and <code>n/2</code>, and the required answer is "floored", meaning <code>mySqrt(8)</code> is to return <code>2</code>.</p> <p>Please comment on the efficiency, and if possible, the loop invariants in terms of correctness:</p> <pre><code>class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int Loop invariant: The answer is always in the range [low, high] inclusive, except possibly: 1) low == high == mid, and mid * mid == x and any of low, high, or mid can be returned as the answer. 2) if there is no exact answer and the floor is to be returned, then low &gt; high by 1. Since sq != x, so either low or high is set inside the loop. If low gets set and gets pushed up, it is pushed up too much. So when low &gt; high by 1, low - 1 is the answer and it is the same as high, because low &gt; high by 1. If high gets set and gets pushed down, high can be the correct answer. When low &gt; high, it is by 1, and high is the correct floor value to be returned. (since there is no perfect square root and the floor is required) 0 &lt;= low &lt;= answer &lt;= high &lt;= n//2 + 1 where answer is floor(sqrt(x)) to be found, except if low &gt; high and the loop will exit. Each loop iteration always makes the range smaller. If the range is empty at the end, low is &gt; high by 1, and high is the correct floored value, and low is the ceiling value, so high is returned. """ low = 0; high = x//2 + 1; while (low &lt;= high): mid = low + (high - low) // 2; sq = mid * mid; if (sq == x): return mid; elif (sq &gt; x): high = mid - 1; # sq exceeds target, so mid cannot be the answer floored, but when high is set to mid - 1, then it can be the answer else: low = mid + 1; # (here sq &lt; x, and mid might be the answer floored, so when low is set to mid + 1, then low might be too big, while high is correct) return high; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T07:47:05.647", "Id": "439858", "Score": "0", "body": "Please do not update the code in your question after receiving 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": "<ul>\n<li><p>Your comments on the elif / else part are too long to be just after the statements</p></li>\n<li><p>Don't use semicolons (;) in Python.</p></li>\n<li><p>This is a refactored version of the code</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import math\n\nclass Solution(object):\n def mySqrt(self, x):\n \"\"\"\n :type x: int\n :rtype: int\n\n Returns floor(sqrt(x))\n \"\"\"\n low = 0\n high = x//2 + 1\n\n \"\"\"\n It is proved that 0 &lt;= sqrt(x) &lt;= x/2, so\n we run a dichotomic in [0, x/2] to find floor(sqrt(x))\n\n Loop analysis:\n * Initialization: low = 0 and high = x/2 + 1 \n * Termination: |high-low| is reduced each iteration,\n as shown in lines high = mid - 1 and low = mid + 1.\n * Invariant: low &lt;= floor(sqrt(x)) &lt;= high.\n Let mid be (low + high)/2.\n - If mid^2 &lt;= x &lt; (mid+1)^2,\n then mid is floor(sqrt(x)) and just return it.\n - If mid^2 &gt; x, search for values smaller than mid.\n - Otherwise, if mid^2 &lt; x, search within higher values.\n \"\"\"\n while (low &lt;= high):\n mid = (low + high) // 2\n sq = mid * mid\n sq_next = (mid+1)*(mid+1)\n if (sq &lt;= x &lt; sq_next):\n return mid\n elif (sq &gt; x):\n high = mid - 1\n else:\n low = mid + 1\n\nfor i in range(1, 26):\n assert(math.floor(math.sqrt(i)) == Solution().mySqrt(i))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T20:28:30.787", "Id": "439798", "Score": "0", "body": "I suppose if it is Python, it can be `mid = (low + high) // 2` because there is infinite precision arithmetics... but it just depends whether you want it first to overflow (either 32 bit or 64 bit int) to become `bignum`, and then divided by 2 to make it back to a 32 bit or 64 bit int" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T21:04:17.177", "Id": "439805", "Score": "1", "body": "@太極者無極而生 Take a look to the new answer; now there is no need for returning high or low after the loop, so it is easier to reason about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T21:19:42.413", "Id": "439806", "Score": "0", "body": "you are using $$mid^2$$ and $$ (mid+1)^2 $$ to check for the answer and return and no need to consider how `low` or `high` gets set... interesting... it looks like it can make it simpler loop invariants" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T21:26:23.493", "Id": "439807", "Score": "0", "body": "how come you assert from 1 to 26 instead of from 1 to some larger number like... 5000 or a million" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T21:32:42.933", "Id": "439810", "Score": "0", "body": "@太極者無極而生 Code is proved to be correct mathematically, so you can check up to any number you want. Checked up to \\$1000000\\$ and it works (surely, you can try up to any number you want)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T21:36:43.377", "Id": "439811", "Score": "0", "body": "uh-huh. If there is loop invariant that the range is always getting smaller, then it is more peace of mind. Sometimes there is code out there that set `high = mid` and the range might not be smaller. And in some case, the range just stops there and doesn't change at all, so I might worry that for some number 5000 or some weird number, the `// 2` will reach a condition that it becomes infinite loop. If the range keeps on getting smaller for sure, then there is no such worry." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T21:40:28.093", "Id": "439812", "Score": "0", "body": "quote: (see TAOCP, Volume 3, section 6.2.1) that binary search was first published in 1946 but the first published binary search without bugs was in 1962. (and another overflow bug in 2006 for `mid`)... 60 years has a special meaning in Asia calendar... it is one cycle" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T21:50:46.600", "Id": "439813", "Score": "0", "body": "it is interesting that your solution is \"guaranteed solved\" inside the loop" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T19:48:57.683", "Id": "439941", "Score": "0", "body": "Baecause your method never accesses the gields or the other methods of the object you might want to decorate the methods with @staticmethod and remove 'self' from the method signature." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T20:20:30.167", "Id": "226341", "ParentId": "226340", "Score": "7" } } ]
{ "AcceptedAnswerId": "226341", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T20:10:16.570", "Id": "226340", "Score": "4", "Tags": [ "python", "algorithm", "mathematics", "binary-search" ], "Title": "Compute the square root of a positive integer using binary search" }
226340
<p>Here's my solution for Euler Problem 3:</p> <blockquote> <p>The prime factors of 13195 are 5, 7, 13 and 29.</p> <p>What is the largest prime factor of the number 600851475143 ?</p> </blockquote> <p>I'm using the Euler problems to learn some basics of C++. Are there any C++ &quot;conventions&quot; I'm missing, or any languages features I could use to get a better understanding of C++?</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &quot;fibonacci.h&quot; #include &lt;limits&gt; int get_prime_above(int i); bool is_prime(int number); bool has_decimals(float number); int main() { // What number are we getting the prime factors for? long target_number = 600851475143; // Holds the prime factors. std::vector&lt;int&gt; primes; // No point dividing by 1, it's a useless factor in this context. int current_prime = get_prime_above(1); while (target_number &gt; 1) { // Does the target divide by the prime evenly? long result = target_number % (long) current_prime; if (result != 0) { // If not, move on to the next prime. current_prime = get_prime_above(current_prime); continue; } // If it does, push the prime primes.push_back(current_prime); // Change the target number to what ever is left to work out target_number = (long) target_number / (long) current_prime; // And reset the prime. current_prime = get_prime_above(1); } // Sort and reverse the primes, // so the highest will be at index 0 std::sort(primes.begin(), primes.end()); std::reverse(primes.begin(), primes.end()); std::cout &lt;&lt; &quot;Largest prime: &quot; + std::to_string(primes[0]) &lt;&lt; std::endl; } /** * Get the next prime number above i. * @param i * @return */ int get_prime_above(int i = 1) { // Current number we're checking. int current_number = 0; while (current_number &lt; std::numeric_limits&lt;int&gt;::max()) { // If it's lower than what the user wants, just keep incrementing. if (current_number &lt;= i) { current_number++; continue; } // If it's prime, return it. if (is_prime(current_number)) { return current_number; } current_number++; } throw std::runtime_error(&quot;Couldn't find a prime within the int maximum value&quot;); } /** * Is the given number a prime? * @param number * @return bool */ bool is_prime(int number) { // Loop all the numbers between (not inclusive of) 1 and number // as we know that 1 and number will always have no decimal. // If number is 7, it would loop 2..6 for (int tmp = number - 1; tmp &gt; 1; tmp--) { // Divide the number float result = ((float) number / (float) tmp); // If the result has decimals, it doesn't divide equally // so return false. if (!has_decimals(result)) { return false; } } // All the in between numbers had decimals, so it's a prime. return true; } /** * Is this number a decimal? * If converting the float to an int and back again changes the value, * then the int conversion removed some decimals. * @param number * @return bool */ bool has_decimals(float number) { return number != (float) (int) number; } </code></pre>
[]
[ { "body": "<ul>\n<li><p><code>while (current_number &lt; std::numeric_limits&lt;int&gt;::max()) {</code> Good that you discovered numeric limits, but there is no point using it here. Just check up to <span class=\"math-container\">\\$\\sqrt{n}\\$</span> should be fine.</p></li>\n<li><p>Your <code>is_prime</code> function depends on floats, which is not a good idea. This is a simpler implementation, checking whether the modulus is 0 or not (this is done with operator <code>%</code>).</p></li>\n</ul>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>bool is_prime(int n) {\n if (n == 1) return false;\n for (int i = 2; i * i &lt;= n; ++i) {\n if (n % i == 0) {\n return false;\n }\n } \n return true;\n}\n</code></pre>\n\n<ul>\n<li>Your algorithm is quite slow, like for the function get_prime_above. Check this answer: <a href=\"https://codereview.stackexchange.com/questions/74587/project-euler-3-in-java?rq=1\">Project Euler #3 in Java</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T00:47:11.827", "Id": "439827", "Score": "0", "body": "a) 1 is not prime. It should return `false` in that case. b) Why check `n==2` if you do `n%i` with `i=2` next? c) the logic seems inverted `n%i==0` should return `false`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T02:30:24.080", "Id": "439837", "Score": "0", "body": "Wrote it too quickly. My bad." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T21:13:48.233", "Id": "226344", "ParentId": "226343", "Score": "1" } }, { "body": "<p>I tried this in VS2019 and I needed to <code>#include &lt;string&gt;</code> in order to compile. </p>\n\n<p>Then I get a warning for the line </p>\n\n<blockquote>\n<pre><code>long product_of_primes = 600851475143;\n</code></pre>\n</blockquote>\n\n<p>which says</p>\n\n<blockquote>\n <p>truncation from __int64 to long</p>\n</blockquote>\n\n<p>which means that <code>long</code> is not enough to hold that number. Since it's positive, I changed that to <code>unsigned long long</code>.</p>\n\n<p>For the remaining review, I'll go through your code from top to bottom, trying to understand it. Whenever I find something, I'll point it out.</p>\n\n<hr>\n\n<p>If you change</p>\n\n<blockquote>\n<pre><code> // Holds the prime factors.\n std::vector&lt;int&gt; primes;\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code>std::vector&lt;int&gt; prime_factors;\n</code></pre>\n\n<p>you can get rid of the comment and the variable becomes self-explaining.</p>\n\n<hr>\n\n<p>The method</p>\n\n<blockquote>\n<pre><code>int get_prime_above(int i = 1)\n</code></pre>\n</blockquote>\n\n<p>IMHO should not support a default value. As you see in your code, you're calling it with</p>\n\n<blockquote>\n<pre><code>int current_prime = get_prime_above(1);\n</code></pre>\n</blockquote>\n\n<p>and seeing a call with the default value</p>\n\n<pre><code>int current_prime = get_prime_above();\n</code></pre>\n\n<p>would not make sense to the reader.</p>\n\n<p>Another open question is: which prime above <code>i</code> will the method return? Just any? The next? At this point of understanding and from the comment, I'd propose the name</p>\n\n<pre><code>next_prime_after(int i)\n</code></pre>\n\n<p>At the same time, I'd change the parameter <code>i</code> to <code>minimum</code>.</p>\n\n<hr>\n\n<p>I stumbled over the line</p>\n\n<blockquote>\n<pre><code>while (target_number &gt; 1) {\n</code></pre>\n</blockquote>\n\n<p>because I was expecting some other number increasing towards that target. However, your code reduces <code>target_number</code> to become 1. Given that <code>target_number</code> is a product of prime numbers, I would call it <code>product_of_primes</code> instead. Again, you can now remove the comment for that variable.</p>\n\n<hr>\n\n<p>Again, you need a comment to explain what a variable means:</p>\n\n<blockquote>\n<pre><code>// Does the target divide by the prime evenly?\nlong result = product_of_primes % (long)current_prime;\n</code></pre>\n</blockquote>\n\n<p>Note that the comment asks a yes/no question, which is why I would expect a boolean. However, the <code>result</code> is a <code>long</code>. Also, the cast to <code>(long)</code> seems redundant. My proposal:</p>\n\n<pre><code>bool is_divisor = 0 == product_of_primes % current_prime;\n</code></pre>\n\n<p>This also changes the conditional statement to</p>\n\n<pre><code>if (!is_divisor) {\n</code></pre>\n\n<p>so the comment here is redundant, so it can be removed:</p>\n\n<pre><code>// If not, move on to the next prime.\ncurrent_prime = next_prime_after(current_prime);\n</code></pre>\n\n<hr>\n\n<p>In order to simplify the branch we have now:</p>\n\n<pre><code>if (!is_divisor) {\n current_prime = next_prime_after(current_prime);\n continue;\n}\n</code></pre>\n\n<p>you can initialize <code>current_prime</code> to <code>1</code> and then call <code>next_prime_after()</code> at the beginning of the loop like this:</p>\n\n<pre><code>int current_prime = 1;\nwhile (product_of_primes &gt; 1) {\n current_prime = next_prime_after(current_prime);\n bool is_divisor = 0 == product_of_primes % current_prime;\n if (!is_divisor) continue;\n ...\n current_prime = 1\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>product_of_primes = (long)product_of_primes / (long)current_prime;\n</code></pre>\n</blockquote>\n\n<p>This IMHO has redundant casts and can be simplified to</p>\n\n<pre><code>product_of_primes = product_of_primes / current_prime;\n</code></pre>\n\n<blockquote class=\"spoiler\">\n <p> This, however, will change the result from <code>71</code> to the correct value expected by Project Euler to complete the challenge.</p>\n</blockquote>\n\n<hr>\n\n<blockquote>\n<pre><code>current_prime = 1;\n</code></pre>\n</blockquote>\n\n<p>IMHO, you don't need to restart at the beginning, since you'll not find prime factors lower than the one you already found.</p>\n\n<p>However, it will not change performance significantly.</p>\n\n<hr>\n\n<p>Instead of reversing</p>\n\n<blockquote>\n<pre><code>std::reverse(prime_factors.begin(), prime_factors.end());\n</code></pre>\n</blockquote>\n\n<p>you can simply get the last element of the vector</p>\n\n<pre><code>std::cout &lt;&lt; \"Largest prime: \" + std::to_string(prime_factors.back()) &lt;&lt; std::endl;\n</code></pre>\n\n<p>or (my preferred option in this case) sort in descending order</p>\n\n<pre><code>std::sort(prime_factors.begin(), prime_factors.end(), std::greater&lt;int&gt;());\n</code></pre>\n\n<p>---- <em>Dunno, the horizonal rulers stop working in this line</em></p>\n\n<p>Woah, this is ugly:</p>\n\n<blockquote>\n<pre><code>if (current_number &lt;= minimum) {\n current_number++;\n continue;\n</code></pre>\n</blockquote>\n\n<p>This can simply be replaced by</p>\n\n<pre><code>int current_number = minimum + 1;\n</code></pre>\n\n<p>And in consequence the loop can be re-written as</p>\n\n<pre><code>int next_prime_after(int minimum) {\n int current_number = minimum + 1;\n while (!is_prime(current_number)) {\n current_number++;\n }\n return current_number;\n}\n</code></pre>\n\n<hr>\n\n<p>In that same method, we probably get a performance benefit of a factor of 2 if you move to odd numbers. </p>\n\n<pre><code>int next_prime_after(int minimum) {\n int current_number = minimum + 1;\n current_number += minimum % 2; // ensure odd number\n while (!is_prime(current_number)) {\n current_number += 2;\n }\n return current_number;\n}\n</code></pre>\n\n<hr>\n\n<p>A had a WTF moment here:</p>\n\n<blockquote>\n<pre><code>float result = ((float)number / (float)tmp);\n// If the result has decimals, it doesn't divide equally\n// so return false.\nif (!has_decimals(result)) {\n</code></pre>\n</blockquote>\n\n<p>Why? Because you already did a proper divisability check somewhere else (cited from the original code):</p>\n\n<blockquote>\n<pre><code>// Does the target divide by the prime evenly?\nlong result = target_number % (long) current_prime;\n</code></pre>\n</blockquote>\n\n<p>That way, you can get rid of the whole method <code>has_decimals()</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>for (int tmp = number - 1; tmp &gt; 1; tmp--) {\n</code></pre>\n</blockquote>\n\n<p>When you learned dividing numbers in school, did you start by dividing an arbiotrary number like 56 by it's predecessor 55 to check if it is a prime factor? Certainly not. So let's not do it in your code as well. Go simple: check if 56 is divisable by 2.</p>\n\n<p>Oh, and BTW: if you can't divide 56 by 2, you can also not divide it by anything > 28, right? Make a huge performance impact of a factor ~10.</p>\n\n<pre><code>bool is_prime(int number) {\n for (int divisor = 2; divisor &lt; number/2; divisor++) {\n bool is_divisor = 0 == number % divisor;\n if (is_divisor) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>This could be reduced to <code>sqrt(2)</code> instead of number/2 if you think about it.</p>\n\n<p>Starting at 3 and testing odd numbers only will increase by another factor of 2:</p>\n\n<pre><code>bool is_prime(int number) {\n if (number % 2 == 0) return false;\n for (int divisor = 3; divisor &lt; number/2; divisor+=2) {\n bool is_divisor = 0 == number % divisor;\n if (is_divisor) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<hr>\n\n<p>For this Project Euler question, <code>int</code> prime factors see to be good enough. For general purpose factorization, you should consider at least <code>long</code>.</p>\n\n<hr>\n\n<h3>My final proposal for you</h3>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;string&gt;\n#include \"fibonacci.h\"\n#include &lt;limits&gt;\n\nint next_prime_after(long minimum);\nbool is_prime(long number);\n\nint main() {\n\n unsigned long long product_of_primes = 600851475143;\n std::vector&lt;int&gt; prime_factors;\n\n int current_prime = 1;\n while (product_of_primes &gt; 1) {\n current_prime = next_prime_after(current_prime);\n bool is_divisor = 0 == product_of_primes % current_prime;\n if (!is_divisor) continue;\n\n prime_factors.push_back(current_prime);\n product_of_primes = product_of_primes / current_prime;\n current_prime--;\n }\n\n std::sort(prime_factors.begin(), prime_factors.end(), std::greater&lt;int&gt;());\n std::cout &lt;&lt; \"Largest prime: \" + std::to_string(prime_factors[0]) &lt;&lt; std::endl;\n}\n\n/**\n * Get the next prime number above minimum.\n * @param minimum\n * @return\n */\nint next_prime_after(long minimum) {\n long current_number = minimum + 1;\n current_number += minimum % 2; // ensure odd number\n while (!is_prime(current_number)) {\n current_number += 2;\n }\n return current_number;\n}\n\n/**\n * Is the given number a prime?\n * @param number\n * @return bool\n */\nbool is_prime(long number) {\n if (number % 2 == 0) return false;\n for (long divisor = 3; divisor &lt; number/2; divisor+=2) {\n bool is_divisor = 0 == number % divisor;\n if (is_divisor) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<h3>Summary</h3>\n\n<p>I hope you agree with my proposals and see that the resulting code is</p>\n\n<ul>\n<li>easier to read</li>\n<li>bug fixed</li>\n<li>faster by a factor of ~100 (measured using <code>QueryPerformanceCounter()</code>)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T09:38:57.173", "Id": "439998", "Score": "0", "body": "Very thorough review! Thanks for taking the time to write it all up. All the points you make make perfect sense, and I'll implement them later on :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T00:35:02.257", "Id": "226353", "ParentId": "226343", "Score": "4" } }, { "body": "<pre><code> long target_number = 600851475143;\n</code></pre>\n\n<p>Others commented on the truncation issue here. Just to expand on how you should choose integral types.</p>\n\n<ol>\n<li>Use an unsigned integer type if you need\n\n<ol>\n<li>Two's-complement arithmetic or </li>\n<li>bit pattern representation</li>\n</ol></li>\n<li>Use the smallest signed fixed-size integer type from <code>&lt;cstdint&gt;</code> that will suffice if you are\n\n<ol>\n<li>Storing a lot of integers in a data structure or </li>\n<li>Trying to represent a value you wouldn't want to count yourself</li>\n</ol></li>\n<li>Inherit types from data structures to avoid mixing signed and unsigned types (<code>std::size_t</code>, <code>std::vector&lt;T, A&gt;::size_type</code>, etc).</li>\n<li>Use <code>int</code>.</li>\n</ol>\n\n<p>In this case, you've got a really large number you probably would never want to count, so use the smallest signed fixed integer type that can represent it.</p>\n\n<pre><code> std::int64_t target_number = 600851475143;\n</code></pre>\n\n<hr>\n\n<pre><code> int current_prime = get_prime_above(1);\n while (target_number &gt; 1) {\n</code></pre>\n\n<p>Minimize the scope of your variables.</p>\n\n<pre><code> for (int current_prime = 2; target_number &gt; 1; ) {\n</code></pre>\n\n<hr>\n\n<pre><code> std::sort(primes.begin(), primes.end());\n std::reverse(primes.begin(), primes.end());\n // access primes[0]\n</code></pre>\n\n<p>You wrote a slower version of <code>std::max_element</code>. Do you even need to keep a container of all prime factors? Would a single element representing the maximum prime factor be sufficient?</p>\n\n<hr>\n\n<pre><code> long target_number = 600851475143;\n\n std::vector&lt;int&gt; primes;\n int current_prime = get_prime_above(1);\n while (target_number &gt; 1) {\n long result = target_number % (long) current_prime;\n if (result != 0) {\n current_prime = get_prime_above(current_prime);\n continue;\n }\n\n primes.push_back(current_prime);\n target_number = (long) target_number / (long) current_prime;\n current_prime = get_prime_above(1);\n }\n</code></pre>\n\n<p>Looking at your algorithm, you end up duplicating a lot of work because of the reset on <code>current_prime</code>. Consider a target number of 125. You check all values until you find a divisible prime, in this case 2, 3, 4, and 5. You then reduce the target and throw away the work you did. So you check 2, 3, 4, and 5 again, reduce, then trash the work. And again for a third time. This ends up being quite wasteful. The fundamental theorem of arithmetic says that every integer greater than <span class=\"math-container\">\\$1\\$</span> either is a prime or can be represented as the product of prime numbers and it's representation is unique.</p>\n\n<p><span class=\"math-container\">$$\n1200 = 2^4 \\times 75 = 2^4 \\times 3^1 \\times 25 = 2^4 \\times 3^1 \\times 5^2\n$$</span></p>\n\n<p>In the above example, the remaining target will never be divisible by 2 once all factors of 2 are exhausted. You don't need to check it again. The same is true for 3, 4, and 5. Logically, instead of primality testing values, you can shortcut that and just do the divisibility test.</p>\n\n<pre><code> std::int64_t target_number = 600851475143;\n std::int64_t largest_factor = 0;\n\n for (std::int64_t candidate = 2; candidate * candidate &lt;= target_number; /* */ ) {\n if (target_number % candidate != 0) {\n ++candidate;\n continue;\n }\n\n target_number = target_number / candidate;\n largest_factor = candidate;\n }\n\n if (target_number &gt; largest_factor) {\n largest_factor = target_number;\n }\n\n std::cout &lt;&lt; \"Largest prime: \" &lt;&lt; largest_factor &lt;&lt; '\\n';\n</code></pre>\n\n<p>You can, of course, speed this up further using wheels to skip unnecessary division checks. The simplest is skipping all evens.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T06:00:55.630", "Id": "226403", "ParentId": "226343", "Score": "0" } } ]
{ "AcceptedAnswerId": "226353", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T20:59:05.883", "Id": "226343", "Score": "1", "Tags": [ "c++", "programming-challenge" ], "Title": "C++ For Euler Problem 3" }
226343
<p>This code is a result of a lot of help from this community. What does it do? It compares two excel sheets cell by cell and copies the differences into another excel file.</p> <p>I’m trying to modify the Code so it does the following:</p> <p>It goes to “Name” and then searches for that name is the other file. If it doesn’t find the file it just copies that entire row including all the columns to the report file (file that is created) In case it does find the name, then it compares all the columns of that row and if something different it shows the difference in report with color red.</p> <p>The pictures below show what I'm trying to achieve with this code </p> <p>Sheet1 <a href="https://i.stack.imgur.com/N3Mx1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N3Mx1.jpg" alt="enter image description here"></a></p> <p>Sheet2</p> <p><a href="https://i.stack.imgur.com/9HV5d.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9HV5d.jpg" alt="enter image description here"></a></p> <p>Report <a href="https://i.stack.imgur.com/RzqhR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RzqhR.jpg" alt="enter image description here"></a></p> <pre><code>Sub Compare2WorkSheets(ws1 As Worksheet, ws2 As Worksheet) Dim ws1row As Long, ws2row As Long, ws1col As Integer, ws2col As Integer Dim maxrow As Long, maxcol As Integer, colval1 As String, colval2 As String Dim Report As Workbook, difference As Long Dim row As Long, col As Integer Dim Arr1 As Variant, Arr2 As Variant, Arr3 As Variant, Rng As Range Dim tm As Double tm = Timer 'Application.ScreenUpdating = False 'Application.Calculation = xlCalculationManual 'Application.EnableEvents = False With ws1.UsedRange ws1row = .Rows.Count ws1col = .Columns.Count End With With ws2.UsedRange ws2row = .Rows.Count ws2col = .Columns.Count End With maxrow = ws1row maxcol = ws1col If maxrow &lt; ws2row Then maxrow = ws2row If maxcol &lt; ws2col Then maxcol = ws2col Debug.Print maxrow, maxcol Arr1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(maxrow, maxcol)).Formula Arr2 = ws2.Range(ws2.Cells(1, 1), ws2.Cells(maxrow, maxcol)).Formula ReDim Arr3(1 To UBound(Arr1, 1), 1 To UBound(Arr1, 2)) difference = 0 For col = 1 To maxcol For row = 1 To maxrow If Arr1(row, col) &lt;&gt; Arr2(row, col) Then difference = difference + 1 Arr3(row, col) = Arr1(row, col) &amp; "&lt;&gt; " &amp; Arr2(row, col) Else Arr3(row, col) = "" End If Next row Next col Debug.Print " Calc secs " &amp; Timer - tm If difference &gt; 0 Then Set Report = Workbooks.Add With Report.ActiveSheet .Range("A1").Resize(UBound(Arr3, 1), UBound(Arr3, 2)).Value = Arr3 .Columns("A:B").ColumnWidth = 25 Set Rng = .Range(Report.ActiveSheet.Cells(1, 1), Report.ActiveSheet.Cells(UBound(Arr3, 1), UBound(Arr3, 2))) End With With Rng .FormatConditions.Add Type:=xlCellValue, Operator:=xlGreater, Formula1:="=""""" '"""""""" .FormatConditions(Selection.FormatConditions.Count).SetFirstPriority With .FormatConditions(1) .Interior.Color = 255 .Font.Bold = True .Font.ColorIndex = 2 End With End With Debug.Print "Report Generated secs " &amp; Timer - tm End If 'Set Report = Nothing 'Application.ScreenUpdating = True 'Application.Calculation = xlCalculationAutomatic 'Application.EnableEvents = True MsgBox difference &amp; " cells contain different data! ", vbInformation, "Comparing Two Worksheets" End Sub </code></pre> <p>How do I run this code?</p> <p>I add the code into a module and then create a button and do the following.</p> <p>The first picture shows how I call the sub to compare the two sheets</p> <p><a href="https://i.stack.imgur.com/xqKI8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xqKI8.jpg" alt="enter image description here"></a></p> <p>The second pictures shows how I open up another file and compare two Excel files.</p> <p><a href="https://i.stack.imgur.com/TIUpA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TIUpA.jpg" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T23:48:34.417", "Id": "439973", "Score": "0", "body": "It is possible if the names are unique only. if the rows in question are as high as in your last question then it seems that is unlikely. Please comment back." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T06:15:21.677", "Id": "439985", "Score": "0", "body": "@Ahmed AU I want to compare by name( column H). Find the sheet which has more rows and start from the first row (Lenovo700), then loop through column H of sheet2 and find which row has Lenovo700 and then compare the first row __Sheet1__ with the row where we located the same NAME in __Sheet2__" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T07:25:45.773", "Id": "439989", "Score": "0", "body": "@ Ahmed AU as far I understand we should only modify the loops but can't seem to get it right" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T13:43:08.853", "Id": "440020", "Score": "1", "body": "Your logic seems clear that you want to find a Name and compare rows, but @AhmedAU question is still important: what happens if you the same name appearing many times in both sheets? For example, \"Lenovo700\" could appear 12 times on Sheet1 and 23 times on Sheet2. How can you decide if any row is unique if a name is repeated like that? One possibility is that a combination of Name and Country may create a unique entry. Your other post indicated that you could have over 10,000 rows, so it seems unlikely that there will be 10,000 unique names (though it's possible, if that is your situation)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T13:47:42.653", "Id": "440021", "Score": "0", "body": "@PeterT Thanks for explaining my point better than me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:27:45.043", "Id": "440036", "Score": "0", "body": "@PeterT sorry now I understand it. There are 200k rows but I ended up using the modified version from Ahmed AU which works really fast. The pictures above are just an example, The files that the code will be running have unique Names so there is no repeating names, it is only appearing once and that is the reason why I wanted to do the comparison based on column H (Names)" } ]
[ { "body": "<blockquote>\n <p>This answer assumes that all Names in the data are unique. There is no\n provision in this example to handle duplicate Names except to issue a\n note in the debug output.</p>\n</blockquote>\n\n<p>This answer will involve <code>Dictionaries</code>. Please review <a href=\"https://excelmacromastery.com/vba-dictionary/\" rel=\"nofollow noreferrer\">this website</a> for complete information on how and why they are an efficient way to store unique data. The short answer is that you can create a large dictionary by looking at a unique \"key\", which is a string that uniquely represents some data that you want to track. In your case, you've asserted that all of the Names are unique. Dictionaries exist for speedy access to any single entry -- no looping through 200k entries to find the one you want. Use your unique key string and you have near-instant access to the data associated with that key.</p>\n\n<p>For your situation, my example builds two <code>Dictionaries</code>, one for each set of data. The keys are the Names. The values associated with each key (Name) is the row number on which each Name is used. The row numbers will play a major role later on.</p>\n\n<p>As with the other Code Review for your previous version of code, I'll reiterate:</p>\n\n<ol>\n<li>Identify your function parameters <code>ByRef</code> or <code>ByVal</code></li>\n<li>Declare your variables as close to their first use as possible.</li>\n</ol>\n\n<p>As an example:</p>\n\n<pre><code>Dim arr1 As Variant\nDim arr2 As Variant\narr1 = BuildDataArrays(ws1, startRow:=2)\narr2 = BuildDataArrays(ws2, startRow:=2)\n</code></pre>\n\n<p>You'll see that there is a call to a <code>BuildDataArrays</code> function. That brings me to </p>\n\n<ol start=\"3\">\n<li>Functional Isolation. When your routine starts getting very long, that is the perfect time to begin breaking parts of the logic out into separate functions/subs. This is especially useful if you have repetitive logic where only the variable is different. This is the case for <code>BuildDataArrays</code>.</li>\n</ol>\n\n<p>Give this function a worksheet and optionally the starting row or column and it determines the range of available data, returning a memory-based array. Breaking out code into separate routines is very helpful because it makes your main logic easier to follow.</p>\n\n<pre><code>Private Function BuildDataArrays(ByRef ws As Worksheet, _\n Optional ByVal startRow As Long = 1, _\n Optional ByVal startCol As Long = 1) As Variant\n '--- assumes all rows and columns are valid data\n Dim lastRow As Long\n Dim lastCol As Long\n Dim dataArea As Range\n Dim data As Variant\n With ws\n lastRow = .Cells(.Rows.Count, startRow).End(xlUp).row\n lastCol = .Cells(startCol, .Columns.Count).End(xlToLeft).Column\n Set dataArea = .Cells(startRow, startCol).Resize(lastRow - startRow + 1, _\n lastCol - startCol + 1)\n data = dataArea\n End With\n BuildDataArrays = data\nEnd Function\n</code></pre>\n\n<ol start=\"4\">\n<li>Use <code>Dictionaries</code> to collect your data. As with the previous point, this is a perfect opportunity to isolate the logic in a separate function.</li>\n</ol>\n\n<p>The <code>BuildDataDictionary</code> function will accept your memory-based array and use the selected column of data as a unique key (currently defaulted to column \"I\").</p>\n\n<pre><code>Private Function BuildDataDictionary(ByRef data As Variant, _\n Optional ByVal keyColumn As Long = 8) As Dictionary\n Dim row As Long\n Dim name As String\n Dim names As Dictionary\n Set names = New Dictionary\n For row = LBound(data, 1) To UBound(data, 1)\n name = Trim$(data(row, keyColumn))\n If Len(name) &gt; 0 Then\n If Not names.Exists(name) Then\n '--- add the new name to the dictionary and save the row number\n names.Add name, row\n Else\n '--- if you get here, it means that the Name is NOT unique\n ' and you'll have to change your logic, or change the name\n Debug.Print \"ERROR: Duplicate name detected on \" &amp; _\n \" on row \" &amp; row &amp; \": '\" &amp; name &amp; \"'\"\n End If\n End If\n Next row\n Set BuildDataDictionary = names\nEnd Function\n</code></pre>\n\n<p>Next we'll build the resulting report data. According to your description, the report will consist of all data rows (each with a unique Name), with any differences noted in the data itself. In your original post, you are assuming that the larger of the two row counts for the sheets will be your output array. This isn't true.</p>\n\n<p>Consider that, by definition, all of the data from Sheet1 is unique (because each row's Name is unique). That means if you have 10 rows of data on Sheet1, your output data will have at least ten rows. It's possible that your data on Sheet2 also has ten rows of data, and only one of those rows repeats a Name on Sheet1. So your resulting report of data will have 19 rows.</p>\n\n<pre><code>Dim totalRows As Long\ntotalRows = ws1Names.Count\n\n'--- now add on the number of unique rows from the other sheet\nDim name As Variant\nFor Each name In ws2Names\n If Not ws1Names.Exists(name) Then\n '--- name is unique\n totalRows = totalRows + 1\n Else\n '--- name is not unique\n End If\nNext name\nDebug.Print \"There are \" &amp; totalRows &amp; \" unique Names between the sheets\"\n\n'--- now build a correctly sized output array\n' ASSUMES both arrays have the same number of columns!!\nDim reportData As Variant\nReDim reportData(1 To totalRows, 1 To UBound(arr1, 2))\n</code></pre>\n\n<p>Now that we're about to generate the report data, we have to consider how to make note of any errors encountered. For this I'm using a <code>Collection</code>, which is a simple way to generate a running list of items. In this case, for each difference I'm adding a string that notes the row and column of each difference in the data arrays. I can use this later on to highlight the difference cells.</p>\n\n<pre><code>'--- and create an object to list which cells are different\nDim diffCells As Collection\nSet diffCells = New Collection\n</code></pre>\n\n<p>After that, we simply move the data over to the report array, making note of any differences.</p>\n\n<pre><code>'--- we know that all Names are unique in sheet1, so move the all that\n' data from sheet1 into the report array\nDim row As Long\nDim col As Long\nDim ws1row As Long\nDim ws2row As Long\nrow = 1\nFor Each name In ws1Names\n If ws2Names.Exists(name) Then\n '--- this row will have a difference because the Names match!\n ' so get the rows for each sheet that match the name\n ws1row = ws1Names(name)\n ws2row = ws2Names(name)\n For col = 1 To UBound(reportData, 2)\n If arr1(ws1row, col) = arr2(ws2row, col) Then\n reportData(row, col) = arr1(ws1row, col)\n Else\n '--- note the different values in the cell and add the\n ' row and column to the difference list\n reportData(row, col) = arr1(ws1row, col) &amp; \" &lt;&gt; \" &amp; _\n arr2(ws2row, col)\n diffCells.Add CLng(row) &amp; \",\" &amp; CLng(col)\n End If\n Next col\n Else\n '--- this is a unique row, so a straight copy of all columns\n For col = 1 To UBound(reportData, 2)\n reportData(row, col) = arr1(row, col)\n Next col\n End If\n row = row + 1\nNext name\n\n'--- the remaining data are the unique rows that exist in sheet2\n' the \"row\" variable count is continued in this loop\nFor Each name In ws2Names\n If Not ws1Names.Exists(name) Then\n '--- this is a unique row, so a straight copy of all columns\n ws2row = ws2Names(name)\n For col = 1 To UBound(reportData, 2)\n reportData(row, col) = arr2(ws2row, col)\n Next col\n row = row + 1\n End If\nNext name\n</code></pre>\n\n<p>The final step is to output the report data. In my example, I am not creating a new workbook, but only creating a new worksheet. You can un-comment some code lines there to change it back for your purposes.</p>\n\n<pre><code>If diffCells.Count &gt; 0 Then\n Dim report As Workbook\n Dim reportWS As Worksheet\n 'Set report = Workbooks.Add 'un-comment to report to a new workbook\n 'Set reportWS = report.ActiveSheet 'un-comment to report to a new workbook\n Set reportWS = ThisWorkbook.Sheets.Add 'comment to report to a new workbook\n\n '--- copy the resulting report to the worksheet\n Dim reportArea As Range\n Set reportArea = reportWS.Range(\"A1\").Resize(UBound(reportData, 1), UBound(reportData, 2))\n With reportArea\n .Value = reportData\n .Columns(\"A:B\").ColumnWidth = 25\n\n '--- now highlight the cells that are different\n Dim rowcol As Variant\n Dim parts() As String\n For Each rowcol In diffCells\n parts = Split(rowcol, \",\")\n With .Cells(CLng(parts(0)), CLng(parts(1)))\n .Font.Bold = True\n .Font.ColorIndex = 3\n End With\n Next rowcol\n End With\n Debug.Print \"Report Generated secs \" &amp; Timer - tm\nEnd If\n</code></pre>\n\n<p>Here is the whole code module in one block:</p>\n\n<pre><code>Option Explicit\n\nSub test1()\n Compare2WorkSheets Sheet1, Sheet2\nEnd Sub\n\nSub Compare2WorkSheets(ByRef ws1 As Worksheet, ByRef ws2 As Worksheet)\n Dim tm As Double\n tm = Timer\n\n 'Application.ScreenUpdating = False\n 'Application.Calculation = xlCalculationManual\n 'Application.EnableEvents = False\n\n '--- establish the data in the arrays, skip the header row\n Dim arr1 As Variant\n Dim arr2 As Variant\n arr1 = BuildDataArrays(ws1, startRow:=2)\n arr2 = BuildDataArrays(ws2, startRow:=2)\n\n '--- buidl a dictionary of Names for each worksheet\n Dim ws1Names As Dictionary\n Dim ws2Names As Dictionary\n Set ws1Names = BuildDataDictionary(arr1)\n Set ws2Names = BuildDataDictionary(arr2)\n\n '--- we don't know how many rows the report will be, so compare\n ' names between the two sheets to find out. it's basically\n ' the sum of the number of unique names between the sheets\n Dim totalRows As Long\n totalRows = ws1Names.Count\n\n '--- now add on the number of unique rows from the other sheet\n Dim name As Variant\n For Each name In ws2Names\n If Not ws1Names.Exists(name) Then\n '--- name is unique\n totalRows = totalRows + 1\n Else\n '--- name is not unique\n End If\n Next name\n Debug.Print \"There are \" &amp; totalRows &amp; \" unique Names between the sheets\"\n\n '--- now build a correctly sized output array\n ' ASSUMES both arrays have the same number of columns!!\n Dim reportData As Variant\n ReDim reportData(1 To totalRows, 1 To UBound(arr1, 2))\n\n '--- and create an object to list which cells are different\n Dim diffCells As Collection\n Set diffCells = New Collection\n\n '--- we know that all Names are unique in sheet1, so move the all that\n ' data from sheet1 into the report array\n Dim row As Long\n Dim col As Long\n Dim ws1row As Long\n Dim ws2row As Long\n row = 1\n For Each name In ws1Names\n If ws2Names.Exists(name) Then\n '--- this row will have a difference because the Names match!\n ' so get the rows for each sheet that match the name\n ws1row = ws1Names(name)\n ws2row = ws2Names(name)\n For col = 1 To UBound(reportData, 2)\n If arr1(ws1row, col) = arr2(ws2row, col) Then\n reportData(row, col) = arr1(ws1row, col)\n Else\n '--- note the different values in the cell and add the\n ' row and column to the difference list\n reportData(row, col) = arr1(ws1row, col) &amp; \" &lt;&gt; \" &amp; _\n arr2(ws2row, col)\n diffCells.Add CLng(row) &amp; \",\" &amp; CLng(col)\n End If\n Next col\n Else\n '--- this is a unique row, so a straight copy of all columns\n For col = 1 To UBound(reportData, 2)\n reportData(row, col) = arr1(row, col)\n Next col\n End If\n row = row + 1\n Next name\n\n '--- the remaining data are the unique rows that exist in sheet2\n ' the \"row\" variable count is continued in this loop\n For Each name In ws2Names\n If Not ws1Names.Exists(name) Then\n '--- this is a unique row, so a straight copy of all columns\n ws2row = ws2Names(name)\n For col = 1 To UBound(reportData, 2)\n reportData(row, col) = arr2(ws2row, col)\n Next col\n row = row + 1\n End If\n Next name\n\n Debug.Print \" Calc secs \" &amp; Timer - tm\n If diffCells.Count &gt; 0 Then\n Dim report As Workbook\n Dim reportWS As Worksheet\n 'Set report = Workbooks.Add 'un-comment to report to a new workbook\n 'Set reportWS = report.ActiveSheet 'un-comment to report to a new workbook\n Set reportWS = ThisWorkbook.Sheets.Add 'comment to report to a new workbook\n\n '--- copy the resulting report to the worksheet\n Dim reportArea As Range\n Set reportArea = reportWS.Range(\"A1\").Resize(UBound(reportData, 1), UBound(reportData, 2))\n With reportArea\n .Value = reportData\n .Columns(\"A:B\").ColumnWidth = 25\n\n '--- now highlight the cells that are different\n Dim rowcol As Variant\n Dim parts() As String\n For Each rowcol In diffCells\n parts = Split(rowcol, \",\")\n With .Cells(CLng(parts(0)), CLng(parts(1)))\n .Font.Bold = True\n .Font.ColorIndex = 3\n End With\n Next rowcol\n End With\n Debug.Print \"Report Generated secs \" &amp; Timer - tm\n End If\n 'Application.ScreenUpdating = True\n 'Application.Calculation = xlCalculationAutomatic\n 'Application.EnableEvents = True\n\n If diffCells.Count &gt; 0 Then\n Debug.Print diffCells.Count &amp; \" cells contain different data!\"\n Else\n Debug.Print \"No differences found between the sheets.\"\n End If\nEnd Sub\n\nPrivate Function BuildDataArrays(ByRef ws As Worksheet, _\n Optional ByVal startRow As Long = 1, _\n Optional ByVal startCol As Long = 1) As Variant\n '--- assumes all rows and columns are valid data\n Dim lastRow As Long\n Dim lastCol As Long\n Dim dataArea As Range\n Dim data As Variant\n With ws\n lastRow = .Cells(.Rows.Count, startRow).End(xlUp).row\n lastCol = .Cells(startCol, .Columns.Count).End(xlToLeft).Column\n Set dataArea = .Cells(startRow, startCol).Resize(lastRow - startRow + 1, _\n lastCol - startCol + 1)\n data = dataArea\n End With\n BuildDataArrays = data\nEnd Function\n\nPrivate Function BuildDataDictionary(ByRef data As Variant, _\n Optional ByVal keyColumn As Long = 8) As Dictionary\n Dim row As Long\n Dim name As String\n Dim names As Dictionary\n Set names = New Dictionary\n For row = LBound(data, 1) To UBound(data, 1)\n name = Trim$(data(row, keyColumn))\n If Len(name) &gt; 0 Then\n If Not names.Exists(name) Then\n '--- add the new name to the dictionary and save the row number\n names.Add name, row\n Else\n '--- if you get here, it means that the Name is NOT unique\n ' and you'll have to change your logic, or change the name\n Debug.Print \"ERROR: Duplicate name detected on \" &amp; _\n \" on row \" &amp; row &amp; \": '\" &amp; name &amp; \"'\"\n End If\n End If\n Next row\n Set BuildDataDictionary = names\nEnd Function\n</code></pre>\n\n<blockquote>\n <p><strong>EDIT:</strong> added an example on how to call the routine from a button click</p>\n</blockquote>\n\n<p>It seems that you're adding an ActiveX command button to your worksheet. In this case, the <code>CommandButton1_Click()</code> method will be executed in the Sheet1 module. Take the code above with the <code>Compare2WorkSheets</code> routine and paste it into a regular code module. Then, in your sheet1 module, fix up your button-click code like this:</p>\n\n<pre><code>Option Explicit\n\nPrivate Sub CommandButton1_Click()\n Dim myWorkbook1 As Workbook\n Dim myWorkbook2 As Workbook\n\n '--- if Sheet1 is contained in the workbook where the code is running, use this\n Set myWorkbook1 = ThisWorkbook\n\n '--- if Sheet1 is in a different -- but already open -- workbook, use this\n Set myWorkbook1 = Workbooks(\"the-already-open-workbook-filename.xlsx\")\n\n '--- if Sheet1 is in a different -- but unopened -- workbook, use this\n Set myWorkbook1 = Workbooks.Open(\"the-workbook-filename-to-open.xlsx\")\n\n '--- you can make the same decisions for setting myWorkbook2\n Set myWorkbook2 = Workbooks.Open(\"C:\\Temp\\testreport1.xlsx\")\n\n\n Compare2WorkSheets myWorkbook1.Worksheets(\"Sheet1\"), myWorkbook2.Worksheets(\"Sheet1\")\n\n myWorkbook1.Close\n myWorkbook2.Close\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T17:57:38.453", "Id": "440240", "Score": "0", "body": "thank you for this incredible answer . I read the description and learned a lot. Until now I wasn't able to make it run. I usually just use a button and call the sub. I added the part on how I run the code in question above. Until now I don't know how to do that with your code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T19:42:32.823", "Id": "440259", "Score": "0", "body": "@MiriamList - there are a couple issues: 1) you're trying to execute your VBA code from a non-macro workbook named `File1.xlsx'`, if this is a temporary workbook for testing, that's okay but you can't save your macro code in it, and 2) in your parameter `Workbooks(\"testcompare1.xlsm\").Worksheets(\"Sheet1\")`, this assumes that the workbook named \"testcompare1.xlsm\" is already open in Excel. The call will fail if its not open. To fix this, create another variable (such as `myWorkbook2`) and set it using `Workbooks.Open`, then use that as a parameter. It should work then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T19:56:40.480", "Id": "440262", "Score": "0", "body": "yes the file was just and example to show you. I just wanted to ask for some help on how to run your code from above or how to add the sub and the functions from your code to the button." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T20:10:44.790", "Id": "440265", "Score": "0", "body": "@MiriamList - please see if the added code answers your question" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T07:54:28.507", "Id": "440315", "Score": "0", "body": "I followed your code. so I added a module and then put the active button on the first sheet and I wanted to compare sheet1 with sheet2 of the same excel file. When I run the code I'm getting __Error while compiling custom type not defined__ at Private Function **BuildDataDictionary(ByRef data As Variant, _\n Optional ByVal keyColumn As Long = 8) As Dictionary**" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T12:46:04.930", "Id": "440348", "Score": "0", "body": "At the same link from the post above, look at section 15: [Troubleshooting the Dictionary](https://excelmacromastery.com/vba-dictionary/#Troubleshooting_the_Dictionary). You are likely missing the library reference to the Microsoft Scripting Runtime." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T13:57:43.313", "Id": "440364", "Score": "0", "body": "@ PeterT I used the first method to run the code by just saying the module and then running it by going to macros. I enabled “Microsoft Scripting Runtime”.. Unfortunately I’m getting an error under Sub test1() saying that variable is not defined (Sheet1 gets Highlighted)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T14:23:21.383", "Id": "440369", "Score": "0", "body": "So you need to replace `Sheet1` and maybe even `Sheet2` with whatever worksheets you want to compare. Remember that the parameters are `Worksheet` objects, and not worksheet names. So you can use `ThisWorkbook.Sheets(\"yoursheetname\")` or anything else that gives you a worksheet object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T15:36:50.613", "Id": "440383", "Score": "0", "body": "I made the code run I couldn't check the results because after creating another sheet and putting the compared files there the loading cursor appears and it stays like that If I click \"Not responding\" message shows up" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T16:40:37.287", "Id": "440404", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/97690/discussion-between-petert-and-miriam-list)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T15:52:02.437", "Id": "440528", "Score": "0", "body": "I don't know if you get notifications when you write in chat. I wrote on the chat room" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T16:18:23.347", "Id": "440531", "Score": "0", "body": "I didn't get a notification, responded in chat" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-25T16:31:15.983", "Id": "440996", "Score": "0", "body": "can you maybe have a look at my new post. it is the final part to the problem you helped me solve [https://codereview.stackexchange.com/questions/226784/find-list-of-names-in-other-sheet-and-copy-them]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-26T00:31:03.853", "Id": "441027", "Score": "0", "body": "@miriamlist try making the same post on stack overflow. Since your code isn't working, that's the right place for it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-26T15:24:35.090", "Id": "441159", "Score": "0", "body": "can we just make the code so doesn't create a new sheet and paste the data there. It would be great if we can modify the code so it creates a new Excel File and pastes the data there" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-26T19:49:55.993", "Id": "441224", "Score": "0", "body": "There are already a few comments in my solution that show you what to \"uncomment\" and what to \"comment\" in order to create a new Excel file. If you do that, the report results will be reported to the new workbook on the new sheet. The only thing you may have to add is to `report.SaveAs Filename:=\"newfilename.xlsx\"` and `report.Close`if you want to do that." } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T21:25:09.813", "Id": "226460", "ParentId": "226346", "Score": "3" } } ]
{ "AcceptedAnswerId": "226460", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-17T21:19:20.900", "Id": "226346", "Score": "4", "Tags": [ "vba", "excel" ], "Title": "Compare two Excel sheets by Cell Content" }
226346
<p>Problem statement is as follows</p> <blockquote> <p>Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), find the minimum number of rooms required.</p> <p>For example, given [(30, 75), (0, 50), (60, 150)], you should return 2.</p> </blockquote> <p>This is supposed to be an <em>easy</em> challenge but it was not the case for me. </p> <p>Here is my solution in JavaScript</p> <pre><code>// Given an array of time intervals (start, end) for classroom lectures (possibly overlapping), // find the minimum number of rooms required. // For example, given [(30, 75), (0, 50), (60, 150)], you should return 2. exports.roomsRequired = function roomsRequired(lectureIntervals) { function Room() {return {busy: []};} let rooms = []; lectureIntervals.forEach(lectureInterval =&gt; { let roomFound = false; rooms.forEach(room =&gt; { let roomBusyInLectureHours = false; room.busy.forEach(reserved =&gt; { if (lectureInterval[0] &gt; reserved[0] &amp;&amp; lectureInterval[0] &lt; reserved[1]) roomBusyInLectureHours = true; if (lectureInterval[1] &gt; reserved[0] &amp;&amp; lectureInterval[1] &lt; reserved[1]) roomBusyInLectureHours = true; if (reserved[0] &gt; lectureInterval[0] &amp;&amp; reserved[0] &lt; lectureInterval[1]) roomBusyInLectureHours = true; if (reserved[1] &gt; lectureInterval[0] &amp;&amp; reserved[1] &lt; lectureInterval[1]) roomBusyInLectureHours = true; }); if (!roomBusyInLectureHours) { room.busy.push(lectureInterval); roomFound = true; } }); if (!roomFound) { let room = new Room(); room.busy.push(lectureInterval); rooms.push(room); } }); return rooms; }; </code></pre> <p>The only test case I have so far</p> <pre><code>let rooms = exports.roomsRequired([[30, 75], [0, 50], [60, 150]]); for (let i = 0; i &lt; rooms.length; i++) { console.log(rooms[i].busy) } </code></pre> <p>Which prints</p> <pre><code>[ [ 30, 75 ] ] [ [ 0, 50 ], [ 60, 150 ] ] </code></pre> <p>I am aware that I am not returning the number of rooms, but that is essentially the number of rows seen, so for example in the case above it is <code>2</code> as expected. </p> <p>My question is, can this code be much shorter? I suspect I am missing something obvious being this challenge easy.</p> <p>Pseudo code of my implementation would be something like this</p> <pre><code>For Each Interval: For Each Room in Rooms: For Each IntervalWithinThatRoom: Check If IntervalWithinThatRoom overlaps with Interval If No Overlaps Found Push Interval to Room If Interval Not pushed to any Room Create new Room Push Interval to Room Push new Room to Rooms </code></pre> <p><strong>Edit - Unit Tests I have</strong></p> <pre><code>expect(roomsRequired.roomsRequired([[30, 75], [0, 50], [60, 150]]).length).eq(2); expect(roomsRequired.roomsRequired([[5, 7], [0, 9], [5, 9]]).length).eq(3); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T01:41:50.593", "Id": "439835", "Score": "0", "body": "You want it shorter? Use `a`, `b`, `c`, ... as variable names, remove spaces and newlines. I think I know what you mean, but can you phrase it more precisely?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T12:37:03.943", "Id": "439880", "Score": "0", "body": "Helps to test code first, Two problems , A: The question states \"...find the minimum number...\" yet your function returns an array of rooms, not a number? B: how many rooms needed to concurrency host times `[[5, 7], [0, 9], [5, 9]]` your function returns an array of 2 rooms, however the times all overlap and thus require 3 room to be concurrent. Your overlap logic is at fault (guess from a quick look). Unfortunately questions need working code to be reviewed... :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T14:32:10.660", "Id": "439894", "Score": "0", "body": "@Blindman67 You are abs right, thank you. I fixed it (I think). I know it returns an array and I am fine with it, I slightly modified the problem statement in that regard, as I noted in my question. `I am aware that I am not returning the number of rooms, but that is essentially the number of rows seen`\n\nWhat I am trying to ask is, is there a way to do it shorter in terms of time complexity, not source code length. @ThomasWeller" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T23:29:38.347", "Id": "439969", "Score": "1", "body": "Searching for \"rooms\" on this site brought me to [this question](https://codereview.stackexchange.com/questions/221927/given-time-intervals-find-the-minimum-number-of-conference-rooms-required), which looks very similar and has an interestingly simple solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T21:47:51.677", "Id": "527863", "Score": "0", "body": "I think you can simplify by using a priority queue which will always keep the first available meeting room at the beginning of the queue: from queue import PriorityQueue\n\n\ndef num_rooms(intervals):\n a = sorted(intervals)\n\n q = PriorityQueue()\n q.put(a[0][1])\n\n for m in a[1:]:\n min_q = q.get()\n\n if m[0] < min_q:\n q.put(min_q)\n\n q.put(m[1])\n\n return q.qsize()" } ]
[ { "body": "<p>I know that my approach may not add much value, but I would like to share it with you.</p>\n\n<p>Detecting room hours overlapping with this logic is correct, but it is hard to read and understand:-</p>\n\n<pre><code>if (lectureInterval[0] &gt; reserved[0] &amp;&amp; lectureInterval[0] &lt; reserved[1]) roomBusyInLectureHours = true;\nif (lectureInterval[1] &gt; reserved[0] &amp;&amp; lectureInterval[1] &lt; reserved[1]) roomBusyInLectureHours = true;\nif (reserved[0] &gt; lectureInterval[0] &amp;&amp; reserved[0] &lt; lectureInterval[1]) roomBusyInLectureHours = true;\nif (reserved[1] &gt; lectureInterval[0] &amp;&amp; reserved[1] &lt; lectureInterval[1]) roomBusyInLectureHours = true;\n</code></pre>\n\n<p>I think following the approach below will make it more readable and understandable:-</p>\n\n<pre><code>let [reservedStart, reservedEnd] = reserved, [lectureStart, lectureEnd] = lectureInterval;\nlet busyHours = [...new Array(reservedEnd - reservedStart)].map((v, i)=&gt; reservedStart+i);\nlet lectureHours = [...new Array(lectureEnd - lectureStart)].map((v, i)=&gt; lectureStart+i);\nroomBusyInLectureHours = busyHours.filter(hour =&gt; lectureHours.includes(hour)).length &gt; 0;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-24T18:07:54.243", "Id": "440908", "Score": "1", "body": "Welcome to Code Review. Your answer would be improved by explaining exactly what you changed and why it is an improvement. There is no need to reproduce all of the code if you have only changed a small bit; doing so only makes it harder to see what you have done." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-24T19:38:38.410", "Id": "440918", "Score": "0", "body": "@VisualMelon Thanks for your comment, answer is edited accordingly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-08T09:54:45.977", "Id": "460383", "Score": "0", "body": "I disagree that this solution is more readable or understandable plus it performs badly and uses more memory. One good thing is the destruction assignments in the first line (although it should be split into two separate `let` statements). The construction of the `busyHours` and `lectureHours` uses more memory, is difficult to understand and is duplicated code.A (well commented) function would help a lot. Also `lectureHours` is unnecessary just to use `includes`, which performs badly compared with just two comparisons (`hour => lectureStart <= hour && hour <= lectureEnd`)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-24T00:37:38.713", "Id": "226723", "ParentId": "226354", "Score": "3" } }, { "body": "<p>Shouldn't you check by <code>&gt;=</code> and <code>&lt;=</code> if the time is equal for two intervals? Currently you're not checking for conflicts.</p>\n<p><code>[0,30],[0,30]</code> for example can not be done on the same room.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-28T21:29:44.800", "Id": "248571", "ParentId": "226354", "Score": "1" } } ]
{ "AcceptedAnswerId": "226723", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T01:09:53.837", "Id": "226354", "Score": "6", "Tags": [ "javascript", "programming-challenge" ], "Title": "Find minimum number of rooms required" }
226354
<p>This code snippet shows 2 common patterns I see a lot in Python that I don't really like:</p> <ol> <li>Arbitrarily-named, narrowly-scoped recursive function</li> <li>Inappropriate data type (in this case, an array <code>ans</code> to store 1 float) used purely for its mutability and scope, to store side-effects from some other scope</li> </ol> <pre class="lang-py prettyprint-override"><code># Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maximumAverageSubtree(self, root: TreeNode) -&gt; float: ans = [0] def helper(node): if not node: return 0, 0 left_sum, left_count = helper(node.left) right_sum, right_count = helper(node.right) ans[0] = max(ans[0], (left_sum + right_sum + node.val) / (left_count + right_count + 1)) return left_sum + right_sum + node.val, left_count + right_count + 1 helper(root) return ans[0] </code></pre> <p><code>ans</code> has to be an array, even though we just want to store one scalar value, because if we tried to use a float it would not be visible inside <code>helper</code>. This seems like an ugly shortcut to me.</p> <p>And the other pattern I don't like is defining <code>helper</code> just so we can do recursion with additional return values for logic, then return <code>helper</code>'s side effects. Is it normal to define short, sort of "throwaway" functions like this?</p>
[]
[ { "body": "<h2>Non-Local Variables</h2>\n\n<p><code>ans</code> is visible (for reading) inside of <code>helper</code>. It just can't be changed, although its contents can be modified.</p>\n\n<p>So yes, <code>ans = [0]</code> is an ugly hack. You don't need it. What you need in its place is <code>nonlocal</code>.</p>\n\n<pre><code>def maximumAverageSubtree(self, root: TreeNode) -&gt; float:\n ans = 0\n\n def helper(node):\n nonlocal ans # &lt;--- Refer to ans in outer (but not global) scope\n\n if not node:\n return 0, 0\n\n left_sum, left_count = helper(node.left)\n right_sum, right_count = helper(node.right)\n\n ans = max(ans, (left_sum + right_sum + node.val) / (left_count + right_count + 1))\n\n return left_sum + right_sum + node.val, left_count + right_count + 1\n\n helper(root)\n\n return ans\n</code></pre>\n\n<h2>Arbitrary-named, narrowly-scoped recursive function</h2>\n\n<p>In this case, you're going to need to get used to it.</p>\n\n<p>Instead of creating a new function, which is visible outside the <code>maximumAverageSubtree</code> function, this <code>helper</code> is only useful to this function. It does not need to exposed to the outside, so it makes sense to hide it inside.</p>\n\n<p>This is a common paradigm in Python. Decorators use this all the time. For example, a <code>@timed</code> decorator has an internal <code>wrapper()</code> function.</p>\n\n<pre><code>def timed(func):\n\n def wrapper(*argv, **kwargs):\n start_time = time.perf_counter()\n result = func(*argv, **kwargs)\n end_time = time.perf_counter()\n print(func.__name__, \"took\", end_time - start_time, \"seconds\")\n return result\n\n return wrapper\n</code></pre>\n\n<p>The function shouldn't be arbitrarily named; its name should reflect its purpose. Here, we are wrapping a call to another function, so <code>wrapper()</code> makes sense.</p>\n\n<p>Above, you have a <code>helper()</code> function. That probably could be named better. Maybe <code>process_subtree(node)</code>. But it is \"scoped\" inside <code>maximumAverageSubtree()</code>, so its name doesn't need to repeat that level of detail.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T20:06:16.613", "Id": "439943", "Score": "1", "body": "I wasn't aware of `nonlocal`, I like that a lot. Like `global` without all the namespace pollution. Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T04:56:19.473", "Id": "226364", "ParentId": "226358", "Score": "2" } }, { "body": "<p>No need for a hack or nonlocal variable, return the maximum average:</p>\n\n<pre><code>class Solution:\n def maximumAverageSubtree(self, root: TreeNode) -&gt; float:\n\n def helper(node):\n if not node:\n return 0, 0, 0\n\n left_max_avg, left_sum, left_count = helper(node.left)\n right_max_avg, right_sum, right_count = helper(node.right)\n\n this_sum = left_sum + right_sum + node.val\n this_count = left_count + right_count + 1\n this_avg = this_sum / this_count\n\n this_max_avg = max(left_max_avg, this_max_avg, right_max_avg )\n\n return this_max_avg, this_sum , this_count\n\n max_avg, _, _ = helper(root)\n\n return max_avg\n</code></pre>\n\n<p>Or, in this case you could use a class instance variable:</p>\n\n<pre><code>class Solution:\n def maximumAverageSubtree(self, root: TreeNode) -&gt; float:\n\n def helper(node):\n if not node:\n return 0, 0\n\n left_sum, left_count = helper(node.left)\n right_sum, right_count = helper(node.right)\n this_sum = left_sum + right_sum + node.val\n this_count = left_count + right_count + 1\n\n self.ans = max(self.ans, this_sum / this_count)\n\n return this_sum , this_count\n\n self.ans = 0\n helper(root)\n return self.ans\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T19:57:20.243", "Id": "439942", "Score": "0", "body": "Is it acceptable to define an object property outside of `__init__`, or should they always first be declared inside `__init__`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T21:06:10.330", "Id": "439948", "Score": "0", "body": "Generally, it's good to put it in __init__. If you expect to call maximumAverageSubtree more than once, self.ans would have to be reinitialized every call. Using @AJNeufelds's answer with `nonlocal` or returning the max avg as in my first answer is a better approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T08:55:40.853", "Id": "439994", "Score": "0", "body": "Should probably be `if not node: return float('-inf'), 0, 0`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T07:35:54.037", "Id": "226367", "ParentId": "226358", "Score": "1" } } ]
{ "AcceptedAnswerId": "226364", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T03:00:18.520", "Id": "226358", "Score": "3", "Tags": [ "python", "algorithm", "python-3.x" ], "Title": "LeetCode #1120 Maximum Average Subtree (Python)" }
226358
<p>Hi folks: I posted a SO (<a href="https://stackoverflow.com/questions/57541246/optimizing-vba-function-loop">https://stackoverflow.com/questions/57541246/optimizing-vba-function-loop</a>) and was told to ask here.</p> <p>I am starting to think that rather than relay on excel as my data repository, I should create a separate class that holds a variant array that I can then query must faster??</p> <p>Anyway... here's my question. I hope someone can help. I agree that searching arrays may be faster but I need this data available across all functions of this sheet.</p> <p>I am in need to optimizing some VBA which currently works functionally.</p> <p>Given columns of sequential Dates (column B) and Times (column C), and Given a time window (T1 and T2), return a range of rows in which dates and times fall within T1 and T2. For example, I want MIN and MAX price between those two times. </p> <p>The goal is to build Open/High/Low/Close charts for Excel candlestick charts and the data source has over 260,000 rows of data.</p> <p>I currently have the following code that </p> <pre><code>Dim priceRange As Range startRowNum = GetFirstRow(StartTime) &lt;&lt; THIS TAKE 10 SECONDS endRowNum = GetLastRow(endTime) &lt;&lt; THIS TAKE 10 SECONDS Set priceRange = Range(Cells(startRowNum, 4), Cells(endRowNum, 4)) targetRange.Offset(0, 2).Value = Application.WorksheetFunction.Max(priceRange) targetRange.Offset(0, 3).Value = Application.WorksheetFunction.Min(priceRange) </code></pre> <p>To find the first row... </p> <pre><code>Function GetFirstRow(T As Date) As Long 'Starts at FirstRow and returns the first row where the time is greater than T1. Dim currentRow As Long Dim CompareTime As Date Dim CompareDate As Date currentRow = 4 'Start at row4 due to headers. Do While (IsDate(Cells(currentRow, 2))) CompareDate = Cells(currentRow, 2) CompareTime = Cells(currentRow, 3) marketTime = CompareDate + CompareTime If (marketTime &gt;= T) Then Exit Do currentRow = currentRow + 1 Loop GetFirstRow = currentRow End Function </code></pre> <p>GetLastRow is very similar.</p> <p><strong>My issue is that the GetFirstRow function has to process 49,000 (yes, forty nine thousand) rows, and it takes about 10 seconds.</strong>... so it takes "minutes" to complete this run.</p> <p>Can someone help me optimize this?</p> <p>Note I Need the date since market data starts the night before. If this is what is slowing me down, I can filter that as I import the data?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T05:41:57.890", "Id": "439847", "Score": "2", "body": "You should use SQLto query data. Ususally the data is stored in a database, but you can missuse excel for that. Depending on your needs, you can use excel-vba ot ms-Access or ssms to [query the range](https://docs.microsoft.com/en-us/previous-versions/tn-archive/ee692882(v=technet.10)). Just reference the range in the From-Clause of query." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T15:47:51.527", "Id": "439915", "Score": "0", "body": "Thanks. Yes of course SQL is fast at queries... but not at creating candlestick charts :). I'm stuck with Excel... looking for a way to optimize. I'm looking to arrays but still can't figure out how to create a public array shared by all functional in a worhseet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T15:53:59.150", "Id": "439917", "Score": "1", "body": "But you can lookup`GetFirstRow`and`GetLastRow`with sql." } ]
[ { "body": "<p>You are doing twice the work by having a function to get the starting row and a second function get the last row. Passing the starting row into the <code>GetLastRow()</code> function would be more efficient. </p>\n\n<p>I prefer to have a single function return the range object. Using the <code>WorkshetFunction.Match()</code> is far more efficient then iterating over the cells. </p>\n\n<h2>Results</h2>\n\n<p><a href=\"https://i.stack.imgur.com/1oIt1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1oIt1.png\" alt=\"Immediate Window Results\"></a></p>\n\n<h2>getDateRange:Function</h2>\n\n<pre><code>'Enumerations to clarify column data content\nPublic Enum DataColumns\n dcStocks = 1\n dcDates\n dcTimes\n dcValues\nEnd Enum\n\n' https://docs.microsoft.com/en-us/office/vba/api/excel.worksheetfunction.match\nFunction getDateRange(ByVal StartDateTime As Date, ByVal EndDateTime As Date) As Range\n Const LargestValueGreaterThanOrEqualTo As Long = -1\n Const FirstExactMatch As Long = 0\n Const LagestValueLessThanOrEqualTo As Long = 1\n\n Dim Target As Range\n With ThisWorkbook.Worksheets(1)\n Set Target = .Range(\"A4:Z4\", .Cells(.Rows.Count, dcDates).End(xlUp))\n End With\n\n Dim dates\n Dim RangeStart As Long, RangeEnd As Long\n Dim SearchValue As Double\n SearchValue = StartDateTime - 1\n On Error Resume Next\n RangeStart = WorksheetFunction.Match(SearchValue, Target.Columns(dcDates), LagestValueLessThanOrEqualTo)\n On Error GoTo 0\n\n If RangeStart = 0 Then Exit Function\n Dim r As Long\n Dim StartFlag As Boolean\n Dim DateTime As Date\n\n With Target\n For r = RangeStart To .Rows.Count\n DateTime = .Cells(r, dcDates).Value + .Cells(r, dcTimes).Value\n If DateTime &gt;= StartDateTime And Not StartFlag Then\n RangeStart = r\n StartFlag = True\n End If\n\n If DateTime &gt; EndDateTime Then\n RangeEnd = r - 1\n Exit For\n End If\n Next\n\n If r &gt; .Rows.Count Then RangeEnd = .Rows.Count\n\n Set getDateRange = .Rows(RangeStart &amp; \":\" &amp; RangeEnd)\n End With\nEnd Function\n</code></pre>\n\n<h2>Worksheet Test Preparation</h2>\n\n<pre><code>Sub Prep()\n Const RowCount As Long = 260000\n 'https://codereview.stackexchange.com/questions/226360/vba-loop-optimization\n Dim codes, dates, stocks, times, Values\n Dim d As Date, t As Date\n codes = Array(\"ACB\", \"AYI\", \"A2B\", \"ABP\", \"ABL\", \"AEG\", \"ABT\", \"AJC\", \"AKG\", \"AX8\", \"AX1\", \"ACS\", \"ACQ\", \"ACF\", \"ACR\", \"ACW\", \"AIV\")\n\n ReDim stocks(1 To RowCount, 1 To 1)\n ReDim dates(1 To RowCount, 1 To 1)\n ReDim times(1 To RowCount, 1 To 1)\n ReDim Values(1 To RowCount, 1 To 1)\n Dim r As Long, r2 As Long\n d = #1/1/2010#\n For r = 1 To RowCount - 48\n d = d + 1\n For r2 = 0 To 47\n t = TimeSerial(0, r2 * 30, 0)\n stocks(r + r2, 1) = codes(WorksheetFunction.RandBetween(0, UBound(codes)))\n dates(r + r2, 1) = d\n times(r + r2, 1) = t\n Values(r + r2, 1) = Int((Rnd * 100) + 1) + Rnd\n Next\n r = r + r2 - 1\n Next\n Range(\"A4\").Resize(RowCount) = stocks\n Range(\"B4\").Resize(RowCount) = dates\n Range(\"C4\").Resize(RowCount) = times\n Range(\"D4\").Resize(RowCount) = Values\nEnd Sub\n</code></pre>\n\n<h2>Test</h2>\n\n<pre><code>Sub Main()\n Dim Results(5) As String * 25\n Const TestCount As Long = 10\n Dim n As Long\n Results(0) = \"Date Range\"\n Results(1) = \"StartDateTime\"\n Results(2) = \"EndDateTime\"\n Results(3) = \"MinPrice\"\n Results(4) = \"MaxPrice\"\n Results(5) = \"Time\"\n Debug.Print Results(0), Results(1), Results(2), Results(3), Results(4), Results(5)\n For n = 1 To TestCount\n Test\n Next\nEnd Sub\n\nSub Test()\n Dim Results(5) As String * 25\n\n Dim t As Double: t = Timer\n Dim Target As Range\n Dim d As Date, StartDateTime As Date, EndDateTime As Date\n\n StartDateTime = WorksheetFunction.RandBetween(#1/2/2010#, #8/30/2024#)\n EndDateTime = StartDateTime + TimeSerial(WorksheetFunction.RandBetween(1, 24) - 1, WorksheetFunction.RandBetween(1, 2) * 60, 0) + WorksheetFunction.RandBetween(1, 60) - 1\n\n Set Target = getDateRange(StartDateTime, EndDateTime)\n\n Dim MinPrice As Double, MaxPrice As Double\n MinPrice = WorksheetFunction.Min(Target.Columns(4))\n MaxPrice = WorksheetFunction.Min(Target.Columns(4))\n\n Results(0) = Target.Address\n Results(1) = StartDateTime\n Results(2) = EndDateTime\n Results(3) = MinPrice\n Results(4) = MaxPrice\n Results(5) = Round(Timer - t, 2)\n Debug.Print Results(0), Results(1), Results(2), Results(3), Results(4), Results(5)\n Target.Select\nEnd Sub\n</code></pre>\n\n<h2>CandleStick Chart</h2>\n\n<p>The dataset in the image shows that you need to know the Open, High, Low, and Close for each day to create the Chart. Considering there are over 200 K rows, I presume that you will also need to filter by stock. If this is true then I would take a different approach. </p>\n\n<p><a href=\"https://i.stack.imgur.com/WnBSR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WnBSR.png\" alt=\"CandleStick Chart Image\"></a></p>\n\n<p>I would have a dictionary that stores a sub-dictionary for each stock that stores a dictionary for each day that stores an arraylist to store the values.</p>\n\n<h2>Create Array From Data Structure and Write it To New Sheet</h2>\n\n<pre><code>Dim CandleStickData\n\nReDim CandleStickData(1 To RowCount, 1 To 6)\nr = 0\nFor Each StockKey In StockMap\n Set DateMap = StockMap(StockKey)\n For Each DateKey In DateMap\n Set ValueList = DateMap(DateKey)\n r = r + 1\n rowData = ValueList.ToArray\n CandleStickData(r, 1) = StockKey\n CandleStickData(r, 2) = DateKey\n CandleStickData(r, 3) = rowData(0)\n CandleStickData(r, 4) = WorksheetFunction.Max(rowData)\n CandleStickData(r, 5) = WorksheetFunction.Min(rowData)\n CandleStickData(r, 6) = rowData(UBound(rowData))\n Next\nNext\n\nWorksheets.Add\nRange(\"A1:F1\").Value = Array(\"Stock\", \"Date\", \"Open\", \"High\", \"Low\", \"Close\")\nRange(\"A2\").Resize(RowCount, 6).Value = CandleStickData\nDebug.Print Round(Timer - t)\n</code></pre>\n\n<p>I did a quick mock up and it took 21 seconds to load 259,967 rows of data into the dictionaries and ArrayList and just 11 seconds to build a new Array and write it to a worksheet. After the data has been processed, it would be a simply matter of getting the date range and updating the chart table. Changing the stocks or chart data should take no more than 1 tenth of a second.</p>\n\n<p><a href=\"https://i.stack.imgur.com/RH3SS.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RH3SS.gif\" alt=\"enter image description here\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T13:17:04.357", "Id": "440175", "Score": "0", "body": "Wow that is awesome. 'Never thought about returning a range. THANK YOU. FYI: 200,000 rows are all for one stock so will need to call getDateRange() for each increment (like 15 minutes). I also LOVE the idea of passing in the starting row of the previous iteration so reduce the amount of data to go thru as we progress thru the chart. This is awesome and I need to look deeper into you suggestions. THANK YOU!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T17:54:11.610", "Id": "440238", "Score": "0", "body": "Creating a Candlestick table from the data-set would take about 40 secs. Having 1 record per Candlestick would increase the performance by +15x and the storage capacity by 15x (assuming 15 records per Candlestick). Updating the table weekly would take far less time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T17:55:51.313", "Id": "440239", "Score": "0", "body": "I recommend using a scrollbar as opposed to the mouse wheel. You would have to use WinApi calls to hook the mouse wheel." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T02:43:42.057", "Id": "440298", "Score": "0", "body": "TinMan: Would you be willing to consult for an hour? 'Willing to pay :) If so, my temporary throw-away email, valid for the next few days is...TempAug20Ed@gmail" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T06:52:14.223", "Id": "226406", "ParentId": "226360", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T04:04:34.120", "Id": "226360", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "VBA loop optimization" }
226360
<p>A simple interactive Python script for organizing messy folders on the computer, supports macOS and linux but not windows. The mini-program has the following features:</p> <ul> <li>Creation of Alpha-numeric (A-Z / 0-9) folders according to available set of letters present in the folder given in the path and move folders/files into relevant newly created folders.</li> <li>Creation of Type specific folders (Audio, Video ...) and move files in relevant type folders.</li> <li>Run directly from shell or from Python interpreter.</li> <li>Interactive.</li> </ul> <p>It is intended to add more features to the code and maybe perform further optimizations / updates in the future, here's my implementation in Python, I hope this is to your liking, any suggestions for improvements/features to add/problems encountered while using the code are more than welcome. Program works perfectly well, no bugs found so far however, you might want to test it before use on a folder containing test files so you can get used to it.</p> <pre><code>#!/usr/bin/env python import os import string import shutil import random def thank_user(): """Print a thank you message and end program.""" print(5 * ' ' + 10 * '=') print('Thank you for using file organizer.') print(5 * ' ' + 10 * '=') exit() def get_folder_contents(path): """Return folder contents.""" while not os.path.exists(path): path = input('Invalid path, please enter a valid path or q to exit: ').rstrip() if path == 'q': thank_user() os.chdir(path) return [file for file in os.listdir(path) if file != '.DS_Store'] def welcome_user(): """Print a welcome message.""" print(5 * ' ' + 10 * '=') print('Welcome to file organizer.') print(5 * ' ' + 10 * '=') action = input('Do you wish to continue? y/n: ') while action != 'y' and action != 'n': print(f'Invalid command {action}') action = input('Do you wish to continue? y/n: ') if action == 'n': thank_user() if action == 'y': pass def create_alpha_num_folders(path): """Create alpha-numeric folders for first characters present in files of the given path .""" folder_contents = get_folder_contents(path) if not folder_contents: print(f"0 files found in {str(path).split('/')[-1]}") print(105 * '=') thank_user() chars_to_produce = set([item[0].upper() for item in folder_contents]) invalid_folders = [folder for folder in folder_contents if folder in string.ascii_uppercase or folder in string.digits] if invalid_folders: print(f'Found the following {len(invalid_folders)} folders named from A - Z/ 1 - n:') for invalid_folder in invalid_folders: print(invalid_folder) while invalid_folders: action = input(f'Enter q to exit. Do you want to to rename the {len(invalid_folders)}' f' invalid folder(s)? y/n/q: ') if action == 'q' or action == 'n': print('Creating A - Z / 1 - n folders unsuccessful.') thank_user() if action == 'y': confirm = input(f'Are you sure, do you want to rename {len(invalid_folders)} invalid folders? y/n: ') while not confirm == 'y' and not confirm == 'n': print(f'Invalid command {confirm}') confirm = input(f'Are you sure, do you want to rename {len(invalid_folders)} ' f'invalid folders? y/n: ') if confirm == 'y': count = random.randint(10 ** 6, 10 ** 7) for filename in invalid_folders: new_name = filename + '_' + str(count) os.rename(filename, new_name) print(f'Changed {len(invalid_folders)} folder name(s) successful.') break if confirm == 'n': thank_user() else: print(f'Invalid command {action}') for char in sorted(chars_to_produce): os.mkdir(char) print(f'Creation of folder {char} successful.') print(105 * '=') def get_supported_formats(): """Return supported formats.""" formats = { 'AUDIO': ['aif', 'cda', 'mid', 'midi', 'mp3', 'mpa', 'ogg', 'wav', 'wma', 'wpl'], 'COMPRESSED': ['arj', 'deb', 'pkg', 'rar', 'rpm', 'tar.gz', 'z', 'zip'], 'DISC': ['bin', 'dmg', 'iso', 'toast', 'vcd'], 'DATA': ['csv', 'dat', 'db', 'dbf', 'log', 'mdb', 'sav', 'sql', 'tar', 'xml'], 'EXECUTABLE': ['apk', 'bat', 'bin', 'cgi', 'pl', 'com', 'exe', 'gadget', 'jar', 'wsf'], 'FONT': ['fnt', 'fon', 'otf', 'ttf'], 'IMAGE': ['ai', 'bmp', 'gif', 'ico', 'jpeg', 'jpg', 'png', 'ps', 'psd', 'svg', 'tif', 'tiff'], 'INTERNET': ['asp', 'aspx', 'cer', 'cfm', 'css', 'htm', 'html', 'js', 'jsp', 'part', 'php', 'rss', 'xhtml'], 'PRESENTATION': ['key', 'odp', 'pps', 'ppt', 'pptx'], 'PROGRAMMING': ['c', 'class', 'cpp', 'cs', 'h', 'java', 'sh', 'swift', 'vb', 'py'], 'SPREADSHEET': ['ods', 'xlr', 'xls', 'xlsx'], 'SYSTEM': ['bak', 'cab', 'cfg', 'cpl', 'cur', 'dll', 'dmp', 'drv', 'icns', 'ini', 'lnk', 'msi', 'sys', 'tmp'], 'VIDEO': ['3g2', '3gp', 'avi', 'flv', 'h264', 'm4v', 'mkv', 'mov', 'mp4', 'mpg', 'mpeg', 'rm', 'swf', 'vob', 'wmv', 'webm'], 'WORD_PROCESSOR': ['doc', 'docx', 'odt', 'pdf', 'rtf', 'tex', 'txt', 'wks', 'wps', 'wpd'], 'SUBTITLES': ['srt', 'sub', 'sbv'], 'UNCLASSIFIED': [] } return formats def get_extension_type(extension): """Return extension type ex: mp3 --&gt; AUDIO.""" formats = get_supported_formats() possible_extensions = tuple(ext for ext, exts in formats.items() if extension.lower() in exts) if not possible_extensions: return ('UNCLASSIFIED',) return possible_extensions def get_file_extension(filename): """Return file extension""" return filename.split('.')[-1].lower() def get_folder_extensions(path): """Return all folder extensions.""" folder_contents = get_folder_contents(path) return set([get_file_extension(filename) for filename in folder_contents]) def create_folders(path): """Create alpha-numeric folders or type specific folders in the given path.""" folder_contents = get_folder_contents(path) print(f"Current folder: {str(path).split('/')[-1]}") print(f'Folder contents ({len(folder_contents)}) items:') print(105 * '=') if not folder_contents: print(f"0 files found in {str(path).split('/')[-1]}") print(105 * '=') thank_user() for number, filename in enumerate(sorted(folder_contents), 1): if os.path.isdir(filename): print(f'{number}. Folder: {filename}') if os.path.isfile(filename): print(f'{number}. File: {filename}') print(105 * '=') action1 = input(f'Enter q to exit. Do you want to group the {len(folder_contents)}' f' items above Alpha-numerically (A-Z / 0-9) or by type? a/t/q: ') while action1 != 'a' and action1 != 't' and action1 != 'q': print(f'Invalid command {action1}') action1 = input(f'Enter q to exit. Do you want to group the {len(folder_contents)}' f' items above Alpha-numerically (A-Z / 0-9) or by type? a/t/q: ') if action1 == 'a': action2 = input(f"Enter q to exit. Are you sure, do you want to create Alpha-numeric (A-Z / 0-9) folders in " f"{str(path).split('/')[-1]}? y/n/q: ") while action2 != 'y' and action2 != 'n' and action2 != 'q': print(f'Invalid command {action2}') action2 = input( f"Enter q to exit. Are you sure, do you want to create Alpha-numeric (A-Z / 0-9) folders in " f"{str(path).split('/')[-1]}? y/n/q: ") if action2 == 'n' or action2 == 'q': print('Creation of new Alpha-numeric (A-Z / 0-9) folders unsuccessful.') thank_user() if action2 == 'y': create_alpha_num_folders(path) return 'alpha' if action1 == 't': folder_extensions = get_folder_extensions(path) new_folders = set([get_extension_type(extension) for extension in folder_extensions]) new_folder_names = [folder_name for folder_names in new_folders for folder_name in folder_names] print('New type folders to create: ') for number, name in enumerate(sorted(new_folder_names), 1): print(number, name) action2 = input(f"Enter q to exit. Are you sure do you want to create the {len(new_folder_names)} folders" f" above in {str(path).split('/')[-1]}? y/n/q: ") while action2 != 'y' and action2 != 'n' and action2 != 'q': print(f'Invalid command {action2}') action2 = input(f"Enter q to exit. Are you sure do you want to create the {len(new_folder_names)} folders" f" above in {str(path).split('/')[-1]}? y/n/q: ") if action2 == 'y': for folder in sorted(new_folder_names): try: os.mkdir(folder) print(f'Creation of {folder} folder successful.') except FileExistsError: print(f'Filename {folder} already exists.') print(f'Creation of {folder} folder unsuccessful.') return 'type' if action2 == 'n' or action2 == 'q': print(f'Creation of {len(new_folder_names)} folders unsuccessful.') thank_user() if action1 == 'q': print('Creation of new folders unsuccessful.') thank_user() def organize_files(path): """Move files and folders into new organized relevant folders.""" folder_types = create_folders(path) if folder_types == 'alpha': new_folder_contents = get_folder_contents(path) files_to_move = [folder for folder in new_folder_contents if folder not in string.ascii_uppercase and folder not in string.digits] new_alpha_folders = [folder for folder in new_folder_contents if folder in string.ascii_uppercase or folder in string.digits] print(f"Current folder: {str(path).split('/')[-1]}") print(f'Folder contents to be moved ({len(files_to_move)}) items:') print(105 * '=') for number, filename in enumerate(sorted(files_to_move), 1): if os.path.isdir(filename): print(f'{number}. Folder: {filename}') if os.path.isfile(filename): print(f'{number}. File: {filename}') print(105 * '=') action = input(f'Enter q to exit. Are you sure, do you want to organize the {len(files_to_move)} files above' f' to Alpha-numeric (A-Z / 0-9) folders? y/n/q: ') while action != 'q' and action != 'y' and action != 'n': print(f'Invalid command {action}') action = input( f'Enter q to exit. Are you sure, do you want to organize the {len(files_to_move)} files above' f' to Alpha-numeric (A-Z / 0-9) folders? y/n/q: ') if action == 'q' or action == 'n': print(f'Organization of {len(files_to_move)} Alpha-numerically (A-Z / 0-9) unsuccessful.') thank_user() if action == 'y': for filename in files_to_move: for folder_name in new_alpha_folders: if filename.startswith(folder_name.lower()) or filename.startswith(folder_name): shutil.move(filename, folder_name) print(f'Moving successful ... {filename} to {folder_name}') if folder_types == 'type': new_folder_contents = get_folder_contents(path) files_to_move = [folder for folder in new_folder_contents if folder not in get_supported_formats()] new_type_folders = [folder for folder in new_folder_contents if folder in get_supported_formats()] print(f"Current folder: {str(path).split('/')[-1]}") print(f'Folder contents to be moved ({len(files_to_move)}) items:') print(105 * '=') for number, filename in enumerate(sorted(files_to_move, key=get_file_extension), 1): if os.path.isdir(filename): print(f'{number}. Folder: {filename}') if os.path.isfile(filename): print(f'{number}. File: {filename}') print(105 * '=') action = input(f'Enter q to exit. Are you sure, do you want to organize the {len(files_to_move)} files above' f' into type specific folders? y/n/q: ') while action != 'y' and action != 'n' and action != 'q': print(f'Invalid command {action}') action = input( f'Enter q to exit. Are you sure, do you want to organize the {len(files_to_move)} files above' f' into type specific folders? y/n/q: ') if action == 'n' or action == 'q': print(f'Organization of {len(files_to_move)} by type unsuccessful.') thank_user() if action == 'y': for filename in files_to_move: file_type = get_extension_type(get_file_extension(filename)) for folder_name in new_type_folders: if file_type[0] == folder_name: shutil.move(filename, folder_name) print(f'Moving successful ... {filename} to {folder_name}') thank_user() if __name__ == '__main__': welcome_user() path_to_folder = input('Please enter a valid path or q to exit: ').rstrip() if path_to_folder == 'q': thank_user() organize_files(path_to_folder) </code></pre>
[]
[ { "body": "<p>The methods are too long. Strive to make smaller and more specific methods. This will improve the readability of you code, and it will allow you to reuse code. For example on a lot of places you ask the user to confirm his action. This is done with a call to the input method in a while loop until correct input is entered and then if-else statment, where you are checking the result. Wouldn't it be easier if you create a method like so:</p>\n\n<pre><code>def confirm_action(message):\n confirm = input(message)\n while confirm != 'y' and confirm != 'n':\n confirm = input(message)\n return confirm == 'y'\n</code></pre>\n\n<p>Now you can use only if conditon and a method call to get the user confirmation. Also if tomorrow for example, you want to quit the program on the 5th wrong confirm, you have to do it only on 1 place not on 100. <br />\nThere is a wrong logical condition in create_alpha_num_folders method.</p>\n\n<pre><code>while not confirm == 'y' or confirm == 'n':\n</code></pre>\n\n<p>must be </p>\n\n<pre><code>while not (confirm == 'y' or confirm == 'n'):\n</code></pre>\n\n<p>Avoid naming variables like \"action1\", \"action2\" (found in increate_folders method). An example of better names are action_input and action_confirm <br />\nAvoid returning things like 'alpha', it doesn't describe what is the intention and it's easy to braek the consistency. If I'm writing another module, which uses yours I can easily return 'Alpha' which will result in error. Better use <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a> <br/>\nTry avoid nesting a lot of if statements and loops. It becames hard to read. <br />\nTry creating some modules or classes. This will allow you to group similar methods and state(think of it like global variable in your module). <br />\nIn my opinion it's better to create array with valid inputs and use it to check whever an input is valid. For example the user confirm method can be done in the following way:</p>\n\n<pre><code>def confirm_action(message):\n valid_inputs = ['y', 'n']\n confirm = input(message)\n while confirm not in valid_inputs:\n confirm = input(message)\n return confirm == 'y'\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T08:59:33.247", "Id": "226371", "ParentId": "226363", "Score": "1" } } ]
{ "AcceptedAnswerId": "226371", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T04:43:47.300", "Id": "226363", "Score": "5", "Tags": [ "python", "python-3.x", "file", "file-system" ], "Title": "Interactive folder files organizer (Alpha-numeric and type) for macOS / Linux in Python" }
226363
<h1>Preliminary</h1> <p>I need to read a binary file constructed by writing a <code>Struct</code> to it with Python. So I decided to write a simple wrapper using <code>struct</code> module.</p> <h1>Code</h1> <pre><code>import struct class structure: def __init__ ( self, little_endian = True ): self._little_endian = little_endian self._table = dict() #stores field name, its format and value self._pack = list() #stores field names in order fields must be read def add_field( self, field_name, field_format ): if field_name in self._table.keys(): print "WARNING :: Field with name '%s' already exists in this structure" % field_name elif field_format == "": print "WARNING :: Format cannot be an empty string" else: self._table[ field_name ] = { "format" : field_format, "value" : None } self._pack.append( field_name ) #maybe error handling is required here def get_value( self, field_name ): try: return self._table[ field_name ][ "value" ] except KeyError: print "WARNING :: There is no such field named '%s' in this structure" % field_name return None def get_format_string( self ): f_str = "" for key in self._pack: f_str += self._table[ key ][ "format" ] if (self._little_endian == True): f_str = "&lt;" + f_str else: f_str = "&gt;" + f_str return f_str def get_size( self ): return struct.calcsize( self.get_format_string() ) def fill( self, file_ptr ): result = struct.Struct( self.get_format_string() ).unpack( file_ptr.read( self.get_size() ) ) for (i,key) in enumerate(self._pack): self._table[ key ][ "value" ] = result[ i ] def show( self ): print "General info:" print "%20s = %s" % ( "Format string", self.get_format_string() ) print "%20s = %d" % ( "Size (bytes)", self.get_size() ) print "Value:" for key in self._pack: print "%20s = " % key, self._table[ key ][ "value" ] </code></pre> <h1>Usage</h1> <p>Usage is straightforward. I used the real binary produced by OWON oscilloscope here so some of the values might look strange (consist non-printable characters).</p> <pre><code>import structure s = structure.structure( little_endian=True ) s.add_field( "header", "10s" ) s.add_field( "serial", "14s" ) s.add_field( "string", "18s" ) s.add_field( "trig_time", "f" ) s.add_field( "float1", "f" ) s.add_field( "float2", "f" ) with open( "./data/trigger.bin" ) as f: s.fill( f ) s.show() </code></pre> <h3>Output</h3> <pre><code>General info: Format string = &lt;10s14s18sfff Size (bytes) = 54 Value: header = SPBS01e� serial = SDS60621715234 string = trig_time = 99.0 float1 = 3.41239206136e-06 float2 = 0.001953125 </code></pre> <hr> <p>As always any suggestions, ideas and critics are appreciated.</p>
[]
[ { "body": "<p>A major drawback of this design is that you <strong>cannot reuse a single instance of <code>structure.structure</code> to read multiple records</strong>. Instead of <code>s.fill(file_ptr)</code>, consider making a method <code>s.read(f)</code> that returns an <code>OrderedDict</code> of the deserialized data. (By the way, mentioning \"pointer\" in a parameter name isn't very Pythonic.) Note that that would also replace your <code>.get_value()</code> method with a dictionary lookup, which can be dealt with more idiomatically. (Or, at least implement dict-compatible iteration and subscripting in your <code>structure</code> class.)</p>\n\n<p>Switching to a reusable <code>.read()</code> method would also eliminate a point of awkwardness in your code, which is that <code>._table</code> is a <strong>dict of dicts</strong>, each having a <code>\"format\"</code> and a <code>\"value\"</code>.</p>\n\n<p>In your implementation of <code>.fill()</code>, why not call <strong><code>.unpack_from(file_ptr)</code></strong> instead of <code>.unpack( file_ptr.read( self.get_size() ) )</code>?</p>\n\n<p>A <strong>more natural default endianness</strong> would be either big-endian (because that is the standard Network Byte Order) or host byte order (because that is a non-opinionated choice that also happens to be the path of least resistance).</p>\n\n<p>Whatever you design, it should accommodate the opposite operation — serializing data to a file.</p>\n\n<p>Consider allowing a <code>structure</code> to contain nested <code>structure</code>s as fields.</p>\n\n<p>The <code>.show()</code> method should probably be <code>.__str__()</code> instead.</p>\n\n<p>I'm not convinced of the benefit of <strong>requiring multiple calls to <code>.add_field()</code> to set up the <code>structure</code></strong>. I'd prefer to have the constructor accept the field specification as a list of 2-tuples. Not only would the calling code be cleaner, but the implementation of the <code>structure</code> class would be simpler as well if it is immutable.</p>\n\n<p>I'm not a fan of your <strong>printed warnings</strong>. Utility code, such as this, has absolutely no business contaminating <code>sys.stdout</code>, and ideally shouldn't print to <code>sys.stderr</code> either. An end user would be completely clueless about what to do about these \"warnings\". A programmer would also be puzzled about where these warnings came from (if it's a large program) and what actually happened as a consequence. Rather, you should decide to either tolerate these situations gracefully or raise exceptions. In my opinion…</p>\n\n<ul>\n<li>\"Field with name … already exists\" should raise an <code>ArgumentError</code>.</li>\n<li>\"Format cannot be an empty string\" should be tolerated (or perhaps an assertion failure).</li>\n<li>\"There is no such field\" would be eliminated altogether based on my suggestion to return an <code>OrderedDict</code>. If you had to offer a <code>.get_value()</code> method, then you should just let the <code>KeyError</code> propagate.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T07:58:19.290", "Id": "439861", "Score": "0", "body": "Nice answer! I will go through it gradually. First question: Why do you say I cannot reuse a single instance for reading multiple records? More over, I DO it in my algorithm successfully (at least I don't see any inconsistencies). What is a problem I call `s.fill( f )` several times? Or am I missing something?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T08:01:30.630", "Id": "439862", "Score": "0", "body": "Well, you can `.fill()` the `structure` again, but then you would lose the data that was previously read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T08:09:46.050", "Id": "439863", "Score": "0", "body": "Ah. Of course. In this sense you right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T08:10:25.050", "Id": "439864", "Score": "0", "body": "Good catch on `unpack_from` method. I missed it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T07:45:24.203", "Id": "226368", "ParentId": "226365", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T06:32:42.297", "Id": "226365", "Score": "2", "Tags": [ "python", "python-2.x", "serialization" ], "Title": "An imitation of reading a C Struct from binary file in python 2.7" }
226365
<p>I want to implement a persistent queue for file system operations (copy, delete, move) that needs to be process and thread safe. The module will be used by a daemon (called <code>qcp</code>) which can accept <code>Tasks</code> from multiple clients. It must also be possible to process several queued elements in parallel. </p> <p>I am new to python and looking for general advice (even the nitpicky kind) on python best practices and on object-oriented programming in general. I am especially curious if my implementation of <code>Task.from_json()</code> as <code>@staticmethod</code> is appropriate. I wasn't sure about this because it conditionally instantiates subclasses of <code>Task</code> rather than a plain <code>Task</code>.</p> <h2>tasks.py</h2> <pre><code>from pathlib import Path from typing import Union, Optional import shutil import os import json import sqlite3 import logging Pathish = Union[Path, str] class Task: """Abstract class for qcp Tasks. Should not be instantiated directly.""" def __init__(self) -&gt; None: self.type = 0 def run(self) -&gt; None: """Run the Task""" pass @staticmethod def from_dict(x, validate: bool = False) -&gt; "Task": """Create a Task of the appropriate subclass from a python dict""" task_type = x["type"] if task_type == -1: return KillTask() elif task_type == 0: return Task() elif task_type == 1: return EchoTask(x["msg"]) elif task_type == 2: return FileTask(x["src"], validate=validate) elif task_type == 3: return DeleteTask(x["src"], validate=validate) elif task_type == 4: return CopyTask(x["src"], x["dst"], validate=validate) elif task_type == 5: return MoveTask(x["src"], x["dst"], validate=validate) elif task_type == 6: raise NotImplementedError else: raise ValueError def __repr__(self) -&gt; str: return 'NULL' def __eq__(self, other) -&gt; bool: return self.__dict__ == other.__dict__ def __ne__(self, other) -&gt; bool: return self.__dict__ != other.__dict__ class KillTask(Task): """Kill the qcp server""" def __init__(self) -&gt; None: self.type = -1 super().__init__() def run(self) -&gt; None: raise NotImplementedError def __repr__(self) -&gt; str: return 'KILL' class EchoTask(Task): """Log a message""" def __init__(self, msg: str) -&gt; None: super().__init__() self.msg = msg self.type = 1 def run(self) -&gt; None: print(self.msg) def __repr__(self) -&gt; str: return f'Echo: "{self.msg}"' class FileTask(Task): """Abstract class for all file-based tasks""" def __init__(self, src: Pathish, validate: bool = True) -&gt; None: super().__init__() self.validate = validate self.src = Path(src).as_posix() self.type = 2 if validate: self.__validate__() def __validate__(self) -&gt; None: if not Path(self.src).exists(): raise FileNotFoundError(f'{self.src} does not exist') elif not (Path(self.src).is_dir() or Path(self.src).is_file()): raise TypeError(f'{self.src} is neither a file nor directory') class DeleteTask(FileTask): """Delete a file""" def __init__(self, src: Pathish, validate: bool = True) -&gt; None: super().__init__(src=src, validate=validate) self.type = 3 def run(self) -&gt; None: os.unlink(self.src) def __repr__(self) -&gt; str: return f'DEL {self.src}' class CopyTask(FileTask): """Copy a file""" def __init__(self, src: Pathish, dst: Pathish, validate: bool = True) -&gt; None: super().__init__(src=src, validate=False) self.dst = Path(dst).as_posix() self.type = 4 self.validate = validate if validate: self.__validate__() def __repr__(self) -&gt; str: return f'COPY {self.src} -&gt; {self.dst}' def __validate__(self) -&gt; None: super().__validate__() if Path(self.dst).exists(): raise FileExistsError def run(self) -&gt; None: self.__validate__() shutil.copy(self.src, self.dst) class MoveTask(CopyTask): """Move a file""" def __init__(self, src: Pathish, dst: Pathish, validate: bool = True) -&gt; None: super().__init__(src=src, dst=dst, validate=validate) self.type = 5 def run(self) -&gt; None: super().__validate__() shutil.move(self.src, self.dst) def __repr__(self) -&gt; str: return f'MOVE {self.src} -&gt; {self.dst}' class TaskQueueElement: """An enqueued Task""" task = None #: A Task status = None #: Status of the queued Task priority = None #: Priority of the queued Task def __init__(self, task: Task, priority: 1) -&gt; None: self.task = task self.priority = priority def __lt__(self, other) -&gt; bool: return self.priority &lt; other.priority def __gt__(self, other) -&gt; bool: return self.priority &gt; other.priority def __eq__(self, other) -&gt; bool: return self.__dict__ == other.__dict__ def __ne__(self, other) -&gt; bool: return self.__dict__ != other.__dict__ class TaskQueue: """A prioritzed queue for tasks""" def __init__(self, path: Pathish = 'qcp.db') -&gt; None: """ Instantiate a TaskQueue :param path: Path to store the persistent queue :type path: Path or str """ self.con = sqlite3.connect(path, isolation_level="EXCLUSIVE") self.path = Path(path) cur = self.con.cursor() cur.execute(""" CREATE TABLE IF NOT EXISTS tasks ( priority INTEGER, task TEXT, status INTEGER, owner INTEGER ) """) self.con.commit() @property def n_total(self) -&gt; int: """Count of all tasks in queue (including failed and completed)""" cur = self.con.cursor() return cur.execute("SELECT COUNT(1) from tasks").fetchall()[0][0] @property def n_pending(self) -&gt; int: """Number of pending tasks""" cur = self.con.cursor() return cur.execute("SELECT COUNT(1) FROM tasks WHERE status = 0").fetchall()[0][0] @property def n_running(self) -&gt; int: """Count of currently running tasks""" cur = self.con.cursor() return cur.execute("SELECT COUNT(1) FROM tasks WHERE status = 1").fetchall()[0][0] @property def n_done(self) -&gt; int: """count of completed tasks""" cur = self.con.cursor() return cur.execute("SELECT COUNT(1) from tasks WHERE status = 2").fetchall()[0][0] @property def n_failed(self) -&gt; int: """count of completed tasks""" cur = self.con.cursor() return cur.execute("SELECT COUNT(1) from tasks WHERE status = -1").fetchall()[0][0] def put(self, task: "Task", priority: Optional[int] = None) -&gt; None: """ Enqueue a task :param task: Task to be added to the queue :type task: Task :param priority: (optional) priority for executing `task` (tasks with lower priority will be executed earlier) :type priority: int """ cur = self.con.cursor() cur.execute( "INSERT INTO tasks (priority, task, status) VALUES (?, ?, ?)", (priority, json.dumps(task.__dict__), 0) ) self.con.commit() def pop(self) -&gt; "Task": """ Retrieves Task object and sets status of Task in database to "in progress" (1) :raises AlreadyUnderEvaluationError: If trying to pop a tasks that is already being processed (i.e. if a race condition occurs if the queue is processed in parallel) """ cur = self.con.cursor() cur.execute("SELECT _ROWID_ from tasks WHERE status = 0 ORDER BY priority LIMIT 1") oid = cur.fetchall()[0][0].__str__() self.mark_running(oid, id(self)) cur.execute("SELECT owner, task FROM tasks WHERE _ROWID_ = ?", oid) record = cur.fetchall()[0] if record[0] != id(self): raise AlreadyUnderEvaluationError task = Task.from_dict(json.loads(record[1])) task.oid = oid return task def peek(self) -&gt; "Task": """ Retrieves Task object without changing its status in the queue """ cur = self.con.cursor() cur.execute("SELECT * from tasks ORDER BY priority LIMIT 1") record = cur.fetchall()[0] oid = record[0].__str__() task = Task.from_dict(json.loads(record[1]), validate=False) task.oid = oid return task def print(self, n: int = 10) -&gt; None: """ Print an overview of the queue :param n: number of tasks to preview :type n: int """ assert isinstance(n, int) and n &gt; 0 cur = self.con.cursor() cur.execute("SELECT status, task from tasks ORDER BY priority LIMIT ?", (str(n), )) records = cur.fetchall() for record in records: print(f"[{record[0]}] {Task.from_dict(json.loads(record[1]))}") def mark_pending(self, oid: int) -&gt; None: """ Mark the operation with the _ROWID_ `oid` as "pending" (0) :param oid: ID of the task to mark :type oid: int """ cur = self.con.cursor() cur.execute("UPDATE tasks SET status = 0, owner = NULL where _ROWID_ = ?", (oid, )) self.con.commit() def mark_running(self, oid: int, owner: int) -&gt; None: """Mark the operation with the _ROWID_ `oid` as "running" (1). The "owner" Id is to ensure no two processes are trying to execute the same operation :param oid: ID of the task to mark :type oid: int :param owner: Id of the process that is handling the operation :type owner: int """ cur = self.con.cursor() cur.execute("UPDATE tasks SET status = 1, owner = ? where _ROWID_ = ?", (owner, oid)) self.con.commit() def mark_done(self, oid: int) -&gt; None: """ Mark the operation with the _ROWID_ `oid` as "done" (2) :param oid: ID of the task to mark :type oid: int """ cur = self.con.cursor() cur.execute("UPDATE tasks SET status = 2, owner = NULL where _ROWID_ = ?", (oid, )) self.con.commit() def mark_failed(self, oid: int) -&gt; None: """ Mark the operation with the _ROWID_ `oid` as "failed" (-1) :param oid: ID of the task to mark :type oid: int """ cur = self.con.cursor() cur.execute("UPDATE tasks SET status = -1, owner = NULL where _ROWID_ = ?", (oid, )) self.con.commit() def run(self) -&gt; None: """Execute all pending tasks""" if self.n_pending &lt; 1: logging.getLogger().warn("Queue is empty") while self.n_pending &gt; 0: op = self.pop() op.run() self.mark_done(op.oid) class AlreadyUnderEvaluationError(Exception): """This Task is already being processed by a different worker""" pass </code></pre> <h2>A demo in pytest</h2> <pre><code>import tasks import pytest def test_TaskQueue(tmp_path): """TaskQueue can queue and execute tasks""" src = tmp_path.joinpath("foo") src.touch() q = tasks.TaskQueue(tmp_path.joinpath("qcp.db")) q.put(tasks.CopyTask(src, tmp_path.joinpath("copied_file"))) q.run() assert tmp_path.joinpath("copied_file").is_file() q.put(tasks.MoveTask(tmp_path.joinpath("copied_file"), tmp_path.joinpath("moved_file"))) q.run() assert not tmp_path.joinpath("copied_file").is_file() assert tmp_path.joinpath("moved_file").is_file() q.put(tasks.DeleteTask(tmp_path.joinpath("moved_file"))) q.run() assert not tmp_path.joinpath("moved_file").is_file() assert src.is_file() </code></pre> <p>p.s.: I am aware that I am importing <code>logging</code> for a single log call, but I plan to include more extensive logging in the future</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T16:34:48.277", "Id": "439920", "Score": "0", "body": "`-> \"Task\"` works with quotes in place?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T17:07:15.467", "Id": "439926", "Score": "0", "body": "Yes but i think its a fairly recent thing, see https://stackoverflow.com/questions/46458470/should-you-put-quotes-around-type-annotations-in-python" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T17:22:48.943", "Id": "439928", "Score": "0", "body": "Ok, thanks. Sometimes, Python is a bit messy, I think. Not pythonic. Looks more like a workaround than a good solution." } ]
[ { "body": "<p>Overall your code is pretty clean.</p>\n\n<h2>Abstract class</h2>\n\n<p>There are a few different ways to do this. You can explicitly use the <code>abc</code> stuff, but the simpler thing to do is in your abstract methods (e.g. <code>run</code>), raise a <code>NotImplementedError</code> - at the <code>Task</code> level, not just <code>KillTask</code>. Then classes like <code>KillTask</code> that are effectively abstract children simply omit the implementation.</p>\n\n<h2>Enums</h2>\n\n<p>Python needs help when it comes to the type system. It's good that you're using type hints. You can help it out a little more by using a formal enum for the numbers in <code>from_dict</code>. Read here - <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/enum.html</a></p>\n\n<h2>Prepared statements</h2>\n\n<p>The series of functions beginning with <code>n_pending</code> should really only be one function. This is the perfect use case for prepared statements. Make that <code>status</code> number a parameter.</p>\n\n<h2>Don't conflate purpose</h2>\n\n<p><code>TaskQueue.print</code> really does two things - a fetch and a print. You should probably separate these.</p>\n\n<h2>sqlite autocommit</h2>\n\n<p>From the brief Google I did, sqlite operates in autocommit mode by default. I don't think any of the commits you've done are necessary.</p>\n\n<h2>Implicit cursors</h2>\n\n<p>It shouldn't be necessary to explicitly get those cursors. You can iterate on the return value of <code>fetchall</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T03:25:34.943", "Id": "226398", "ParentId": "226369", "Score": "2" } } ]
{ "AcceptedAnswerId": "226398", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T07:49:15.157", "Id": "226369", "Score": "3", "Tags": [ "python", "python-3.x", "object-oriented" ], "Title": "A persistent file system operations queue using sqlite and JSON text fields" }
226369
<p>I am trying to improve my coding skills in Java by taking existing code, studying it, and adding on to it. In this code example, I took code from <a href="https://codereview.stackexchange.com/questions/100917/connect-four-game-in-java">Connect Four game in Java</a> and edited it. The most major edit I created for the game was that I created a GUI for this game. From looking at the code, are there any suggestions on how I can improve my coding ability in Java?</p> <pre><code>import java.util.stream.Collectors; import java.util.stream.IntStream; import java.awt.event.*; import javax.swing.*; import java.util.*; /**This program uses GUI, including a JTextField. Both javax.swing.* and java.awt.event.* need to be imported in this program. *This program also uses java.util.* */ public class ConnectFour { private static final char[] players = new char[] { 'X', 'O' }; private final int width, height; private int lastCol = -1, lastTop = -1; private GUI gui=new GUI(); //The GUI class needs to be used in the ConnectFour class to have GUI for this game. final char[][] grid; public ConnectFour(int width, int height) { this.width = width; this.height = height; this.grid = new char[height][]; for (int h = 0; h &lt; height; h++) { Arrays.fill(this.grid[h] = new char[width], '.'); } } public String toString() { return IntStream.range(0, this.width) .mapToObj(Integer::toString) .collect(Collectors.joining()) + "\n" + Arrays.stream(this.grid) .map(String::new) .collect(Collectors.joining("\n")); } /** * Prompts the user for a column, repeating until a valid * choice is made. */ public void chooseAndDrop(char symbol) { //This string variable is used by a label to give details on whether a user entered a valid column number or not. String columnInfo=""; do { /**The chooseAndDrop GUI will update two labels to display important information to the user(s). * It will tell the user(s) whether Player X or Player O is supposed to play and also if a * valid column number was entered by the users. */ gui.chooseAndDropGUI(symbol, columnInfo); int col = gui.readPlayerInputForProcessing(); columnInfo=""; if (! (0 &lt;= col &amp;&amp; col &lt; this.width)) { /**If a user entered a column number that is outside of the accepted range, * the columnInfo variable is updated to tell the user to pick a column * in the accepted range. */ columnInfo="Column must be between 0 and " + (this.width - 1); continue; } for (int h = this.height - 1; h &gt;= 0; h--) { if (this.grid[h][col] == '.') { this.grid[this.lastTop=h][this.lastCol=col] = symbol; return; } } /**If a user entered in a column number and that column is already full, * the columnInfo variable is updated to tell the user to pick a different column. */ columnInfo="Column "+col+" is full."; }while (true); } /** * Detects whether the last chip played was a winning move. */ public boolean isWinningPlay() { char sym = this.grid[this.lastTop][this.lastCol]; String streak = String.format("%c%c%c%c", sym, sym, sym, sym); return contains(this.horizontal(), streak) || contains(this.vertical(), streak) || contains(this.slashDiagonal(), streak) || contains(this.backslashDiagonal(), streak); } /** * The contents of the row containing the last played chip. */ private String horizontal() { return new String(this.grid[this.lastTop]); } /** * The contents of the column containing the last played chip. */ private String vertical() { StringBuilder sb = new StringBuilder(this.height); for (int h = 0; h &lt; this.height; h++) { sb.append(this.grid[h][this.lastCol]); } return sb.toString(); } /** * The contents of the "/" diagonal containing the last played chip * (coordinates have a constant sum). */ private String slashDiagonal() { StringBuilder sb = new StringBuilder(this.height); for (int h = 0; h &lt; this.height; h++) { int w = this.lastCol + this.lastTop - h; if (0 &lt;= w &amp;&amp; w &lt; this.width) { sb.append(this.grid[h][w]); } } return sb.toString(); } /** * The contents of the "\" diagonal containing the last played chip * (coordinates have a constant difference). */ private String backslashDiagonal() { StringBuilder sb = new StringBuilder(this.height); for (int h = 0; h &lt; this.height; h++) { int w = this.lastCol - this.lastTop + h; if (0 &lt;= w &amp;&amp; w &lt; this.width) { sb.append(this.grid[h][w]); } } return sb.toString(); } private static boolean contains(String haystack, String needle) { return haystack.indexOf(needle) &gt;= 0; } public static void main(String[] args) { int height = 6, width = 8, moves = height * width; ConnectFour board = new ConnectFour(width, height); /**The emptyChar char is used for the first time the function label_That_Tells_Player_What_Columns_They_Can_Pick_Or_Tells_Them_Who_Won_Function *is called. This is because no specific char value is needed for the first time this function is called. Due to the number in the first parameter, *this function sets the text of a label to tell the user(s) the acceptable range an inputed column number is supposed to be in. */ char emptyChar=' '; board.gui.label_That_Tells_Player_What_Columns_They_Can_Pick_Or_Tells_Them_Who_Won_Function(2,width,emptyChar); //Since the board does not already exist, the last parameter is set to false to create a new empty board. board.gui.createBoard(width, height, board, false); for (int player = 0; moves-- &gt; 0; player = 1 - player) { char symbol = players[player]; board.chooseAndDrop(symbol); //Since the board already does exist, the last parameter is set to true to update the existing board. board.gui.createBoard(width, height, board, true); if (board.isWinningPlay()) { /**The symbol char is used for the second time the function label_That_Tells_Player_What_Columns_They_Can_Pick_Or_Tells_Them_Who_Won_Function *is called. Due to the number in the first parameter, this function will tell which player won. The symbol of the player who *won (X or O) is stored in the symbol char. Therefore, the symbol char is used to tell which player won. */ board.gui.label_That_Tells_Player_What_Columns_They_Can_Pick_Or_Tells_Them_Who_Won_Function(1,width,symbol); return; } } /**The empty char is used for the third time the function label_That_Tells_Player_What_Columns_They_Can_Pick_Or_Tells_Them_Who_Won_Function *is called. This is because no specific char value is needed for the third time this function is called. Due to the number in the first parameter, *this function sets the text of a label to tell the user(s) that nobody has won. */ board.gui.label_That_Tells_Player_What_Columns_They_Can_Pick_Or_Tells_Them_Who_Won_Function(0,width,emptyChar); } } //This class GUI is used to create GUI for the game. class GUI{ private static JFrame jframe; //This variable is used to create a JFrame window. private static List&lt;JLabel&gt; boardLabels; //This list is used to store a group of labels related to the board's graphics. private static JLabel labelDisplayingWhosTurnItIs; private static JLabel labelTellingDetailsRegardingColumns; private static JLabel labelThatTellsPlayerWhatColumnsTheyCanPickOrTellsThemWhoWon; private final int defaultLabelWidth=100; private final int defaultLabelHeight=100; private final int lengthyLabelsWidth=400; //This width is used for labels that have a long width private final int defaultTextFieldWidth=200; private final int defaultTextFieldHeight=50; //The initial x coordinate for each label in the board's graphics is multiplied by this value to add spacing among each label in the board's graphics. private final int xScaling=50; //The initial y coordinate for each label in the board's graphics is multiplied by this value to add spacing among each label in the board's graphics. private final int yScaling=50; //After being multiplied, the x coordinate is added with xOffset to translate it to the right a little bit. private final int xOffset=50; //After being multiplied, the y coordinate is added with yOffset to translate it up a little bit. private final int yOffset=100; //The two variables below are used to set the size of the JFrame. private final int screenXSize=500; private final int screenYSize=900; //When a user presses the Enter key inside the text field, this variable is set to true. private static boolean inputReadyForProcessing=false; //This is the text field where input is entered by the player. private static JTextField playerInput=new JTextField(""); public GUI() { /** A basic GUI window is created, and variables are initialized. * GUI elements are positioned in coordinates by setBounds * and are added to the JFrame window. */ jframe=new JFrame(); boardLabels=new ArrayList&lt;JLabel&gt;(); jframe.setVisible(true); jframe.setSize(screenXSize,screenYSize); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jframe.setLayout(null); jframe.setResizable(false); labelDisplayingWhosTurnItIs=new JLabel(""); labelDisplayingWhosTurnItIs.setBounds(150,550,defaultLabelWidth,defaultLabelHeight); labelTellingDetailsRegardingColumns=new JLabel(""); labelTellingDetailsRegardingColumns.setBounds(150,600,lengthyLabelsWidth, defaultLabelHeight); labelThatTellsPlayerWhatColumnsTheyCanPickOrTellsThemWhoWon=new JLabel(""); labelThatTellsPlayerWhatColumnsTheyCanPickOrTellsThemWhoWon.setBounds(150,750,lengthyLabelsWidth, defaultLabelHeight); playerInput.setBounds(125, 700, defaultTextFieldWidth, defaultTextFieldHeight); jframe.add(labelDisplayingWhosTurnItIs); jframe.add(labelThatTellsPlayerWhatColumnsTheyCanPickOrTellsThemWhoWon); jframe.add(labelTellingDetailsRegardingColumns); jframe.add(playerInput); /**An ActionListener is added to the text field variable. Whenever a player presses the Enter key inside this text field, * an action will be performed. In this case, inputReadyForProcessing is set to true, which will be useful in this program. */ playerInput.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { inputReadyForProcessing=true; } }); } //This function can both be used to create a new empty board and to update an existing board. public void createBoard(int width, int height, ConnectFour board, boolean updateExsistingBoard) { int indexOfLabel=0; for(int x=0; x&lt;width; x++) { for(int y=0; y&lt;height; y++) { /** Labels are set to the string variable slotLabelString. * This string variable adds a char to an empty string, which makes it * basically equal to a string version of the char. This variable * stores the value of a point in the grid array. This value is used * to set each label equal to its corresponding point in the grid array. * The grid array is used in the backbone for this program for basic * game logic. */ String slotLabelString=board.grid[y][x]+""; if(updateExsistingBoard) { //If the board already exists, just update the label's text. boardLabels.get(indexOfLabel).setText(slotLabelString); } else { //If the board does not already exist, create a new label. boardLabels.add(new JLabel(slotLabelString)); boardLabels.get(indexOfLabel).setBounds(x*xScaling+xOffset,y*yScaling+yOffset,defaultLabelWidth,defaultLabelHeight); } //Each label is added to the JFrame window. jframe.add(boardLabels.get(indexOfLabel)); indexOfLabel++; } } } //This function can change the text of a specific label. public void label_That_Tells_Player_What_Columns_They_Can_Pick_Or_Tells_Them_Who_Won_Function(int did_Someone_Win_One_For_Yes_Two_For_No_Other_For_Draw, int width, char symbol) { if (did_Someone_Win_One_For_Yes_Two_For_No_Other_For_Draw==1) { labelThatTellsPlayerWhatColumnsTheyCanPickOrTellsThemWhoWon.setText("Player " + symbol + " wins!"); } else if (did_Someone_Win_One_For_Yes_Two_For_No_Other_For_Draw==2) { labelThatTellsPlayerWhatColumnsTheyCanPickOrTellsThemWhoWon.setText("Use 0-" + (width - 1) + " to choose a column."); } else { labelThatTellsPlayerWhatColumnsTheyCanPickOrTellsThemWhoWon.setText("Game over, no winner."); } } /**This function is used to return the integer version of the string entered in the text field. *This function is called in the chooseAndDropGUI from the ConnectFour class. */ public int readPlayerInputForProcessing() { while(true) { int playerInputValue; /**If a player entered an input that is not a number, trying to convert it into an integer would result in errors. * Therefore, the try and catch method is used. */ try { playerInputValue=Integer.valueOf(playerInput.getText()); } catch(Exception err) { //If an error is caused, the program goes back to the beginning of the while loop. continue; } /**This if statement is intentionally not the first if statement in the function. *This allows the function to have some time to process if whether inputReadyForProcessing is equal to true or not. *This variable is equal to true only if an Enter key was pressed in the text field. Therefore, the playerInputValue *is only returned when a user presses the Enter key. Otherwise, the program goes back to the beginning of the while loop. */ if(!inputReadyForProcessing) { continue; } /** This variable is set back to its initial state, false. To make this variable true again, the Enter key will have to be * pressed inside the text field once again. This makes the program only return numerical input inside the text field only when * the Enter key is pressed inside the text field. */ inputReadyForProcessing=false; return playerInputValue; } } /** * This function is created to create the GUI aspects for the function chooseAndDropGUI in the ConnectFour class. */ public void chooseAndDropGUI(char symbol, String columnInfo) { labelDisplayingWhosTurnItIs.setText("\nPlayer " + symbol + " turn: "); labelTellingDetailsRegardingColumns.setText(columnInfo); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T19:16:18.910", "Id": "440073", "Score": "0", "body": "The official recommendation is to prefer JavaFX to Swing. Are you sure this is where you want to put your energy?" } ]
[ { "body": "<h2><a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">Separation of concerns</a></h2>\n\n<p>As you stated, the major edit in this iteration was adding a graphical presentation.The principle of Separation of concerns dictates (among other things) the <a href=\"https://en.wikipedia.org/wiki/Separation_of_content_and_presentation\" rel=\"nofollow noreferrer\">Separation of content and presentation</a>. So the proper design for this game would be to create a \"game engine\" that is responsible for the logic of the game and publishes an API. another API, the presentation API, would allow the same game engine to be plugged with different UI implementations. the <code>main()</code> method is usually the place where you construct the implementations (based on run time args, config files or the like) and make the necessary connections between the layers. </p>\n\n<p>However, this is not the case here. <code>ConnectFour</code> class initializes an instance of <code>GUI</code> and cannot work with any other UI. Furthermore, there are presentation aspects coded into the class. For example, the players' characters ('X' and 'O'), error messages (<code>columnInfo</code>)</p>\n\n<h2>Naming conventions</h2>\n\n<p><code>public void label_That_Tells_Player_What_Columns_They_Can_Pick_Or_Tells_Them_Who_Won_Function(int did_Someone_Win_One_For_Yes_Two_For_No_Other_For_Draw, int width, char symbol)</code></p>\n\n<p>not only this name violates Java's <a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"nofollow noreferrer\">camelCase naming convention</a>. it is simply a bad name for a function/method in any programming language. first of all, the method name describes a label but doesn't say <em>what is being done</em> to the label (is it reading or writing to/from the label?). second, a rule of thumb states that method (and variable and class) name should not exceed 20+ characters. longer names do not add clarity. that's for documentation in comments. </p>\n\n<p>regarding <code>did_Someone_Win_One_For_Yes_Two_For_No_Other_For_Draw</code> - you don't document the valid values of a variable in it's name. there are two better places to do that: 1) in comments, and 2) create an enum that restricts valid values and also gives meaningful names to each valid value.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T12:43:53.393", "Id": "226377", "ParentId": "226373", "Score": "2" } } ]
{ "AcceptedAnswerId": "226377", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T10:15:41.337", "Id": "226373", "Score": "1", "Tags": [ "java", "beginner", "swing", "connect-four" ], "Title": "Simple Connect Four Game With GUI added" }
226373
<p>The code is about an autonomous driving Rc car. In the first code I have created a function that imports a haar cascade for detecting a stop sign. The second code is the code that I run and test if the car can detect the stop sign and once doing so it should stop</p> <p>Problem: I having trouble importing/calling this s<em>elf.faces</em> into drive.py After importing I will just add an if.statement so the car stops the moment is detects the stop sign</p> <pre><code>import os import time import numpy as np from PIL import Image import glob import numpy as np import cv2 class BaseCamera: def run_threaded(self): return self.frame class Webcam(BaseCamera): def __init__(self, resolution=(120, 160), framerate=20): from picamera.array import PiRGBArray from picamera import PiCamera resolution = (resolution[1], resolution[0]) # initialize the camera and stream self.camera = PiCamera() # PiCamera gets resolution (height, width) self.camera.resolution = resolution self.camera.framerate = framerate self.rawCapture = PiRGBArray(self.camera, size=resolution) self.stream = self.camera.capture_continuous(self.rawCapture, format="rgb", use_video_port=True) # initialize the frame and the variable used to indicate # if the thread should be stopped self.frame = None self.on = True print('PiCamera loaded.. .warming camera') time.sleep(2) def run(self): f = next(self.stream) frame = f.array self.rawCapture.truncate(0) return frame def update(self): # keep looping infinitely until the thread is stopped for f in self.stream: # grab the frame from the stream and clear the stream in # preparation for the next frame self.frame = f.array self.rawCapture.truncate(0) # if the thread indicator variable is set, stop the thread if not self.on: break def shutdown(self): # indicate that the thread should be stopped self.on = False print('stoping PiCamera') time.sleep(.5) self.stream.close() self.rawCapture.close() self.camera.close() class PiCamera(BaseCamera): def __init__(self, resolution=(160, 120), framerate=20): import pygame import pygame.camera super().__init__() pygame.camera.init() l = pygame.camera.list_cameras() self.cam=pygame.camera.Camera(l[0],resolution,"RGB") self.resolution=resolution self.cam.start() self.framerate=framerate # initialize the frame and the variable used to indicate # if the thread should be stopped self.frame = None self.on = True self.faces= [] print('Webcam loaded.. .warming camera') time.sleep(2) def update(self): from datetime import datetime,timedelta import pygame.image while self.on: start=datetime.now() if self.cam.query_image(): face_cascade = cv2.CascadeClassifier('/home/pi/Downloads/stopsigns-master/stopsign_classifier.xml') snapshot = self.cam.get_image() snapshot1 = pygame.transform.scale(snapshot,self.resolution) self.frame=pygame.surfarray.pixels3d(pygame.transform.rotate(pygame.transform.flip(snapshot,True,False),90)) # detect=np.asarray(snapshot1) self.faces = face_cascade.detectMultiScale(self.frame, 1.3, 5) #print(self.faces) stop=datetime.now() s = 1 / self.framerate - (stop - start ).total_seconds() if s&gt;0: time.sleep(s) self.cam.stop() def run_threaded(self): return self.frame def shutdown(self): # indicate that the thread should be stopped self.on = False print('stoping WebCamera') time.sleep(.5) </code></pre> <p>Drive.py file</p> <pre><code>import os from docopt import docopt import donkeycar as dk from donkeypart_picamera import PiCamera from donkeypart_keras_behavior_cloning import KerasLinear from donkeypart_PCA9685_actuators import PCA9685, PWMSteering, PWMThrottle from donkeypart_tub import TubWriter from donkeypart_web_controller import LocalWebController from donkeypart_common import Timestamp def drive(cfg, model_path=None, use_chaos=False): """ """ V = dk.vehicle.Vehicle() clock = Timestamp() V.add(clock, outputs=['timestamp']) cam = PiCamera(resolution=cfg.CAMERA_RESOLUTION) V.add(cam, outputs=['cam/image_array'], threaded=True) mystring=cam.self.faces ctr = LocalWebController(use_chaos=use_chaos) V.add(ctr, inputs=['cam/image_array'], outputs=['user/angle', 'user/throttle', 'user/mode', 'recording'], threaded=True) # See if we should even run the pilot module. # This is only needed because the part run_condition only accepts boolean pilot_condition_part = MakeRunConditionBoolean() V.add(pilot_condition_part, inputs=['user/mode'], outputs=['run_pilot']) # Run the pilot if the mode is not user. kl = KerasLinear() if model_path: kl.load(model_path) V.add(kl, inputs=['cam/image_array'], outputs=['pilot/angle', 'pilot/throttle'], run_condition='run_pilot') state_controller = StateController() V.add(state_controller, inputs=['user/mode', 'user/angle', 'user/throttle', 'pilot/angle', 'pilot/throttle'], outputs=['angle', 'throttle']) steering_controller = PCA9685(cfg.STEERING_CHANNEL) steering = PWMSteering(controller=steering_controller, left_pulse=cfg.STEERING_LEFT_PWM, right_pulse=cfg.STEERING_RIGHT_PWM) throttle_controller = PCA9685(cfg.THROTTLE_CHANNEL) throttle = PWMThrottle(controller=throttle_controller, max_pulse=cfg.THROTTLE_FORWARD_PWM, zero_pulse=cfg.THROTTLE_STOPPED_PWM, min_pulse=cfg.THROTTLE_REVERSE_PWM) V.add(steering, inputs=['angle']) V.add(throttle, inputs=['throttle']) # add tub to save data inputs = ['cam/image_array', 'user/angle', 'user/throttle', 'user/mode', 'timestamp'] types = ['image_array', 'float', 'float', 'str', 'str'] # single tub tub = TubWriter(path=cfg.TUB_PATH, inputs=inputs, types=types) V.add(tub, inputs=inputs, run_condition='recording') # run the vehicle V.start(rate_hz=cfg.DRIVE_LOOP_HZ) class MakeRunConditionBoolean: def run(self, mode): if mode == 'user': return False else: return True class StateController: """ Wraps a function into a donkey part. """ def __init__(self): pass def run(self, mode, user_angle, user_throttle, pilot_angle, pilot_throttle): """ Returns the angle, throttle and boolean if autopilot should be run. The angle and throttles returned are the ones given to the steering and throttle actuators. """ if mode == 'user': #mystring=cam.faces print(user_angle[0]) return user_angle, user_throttle elif mode == 'local_angle': return pilot_angle, user_throttle else: return pilot_angle, pilot_throttle if __name__ == '__main__': args = docopt(__doc__) cfg = dk.load_config() drive(cfg, model_path=args['--model']) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T17:36:36.060", "Id": "439929", "Score": "2", "body": "I am actually pretty confused of what exactly you're asking. Does your code work as expected or not? If it's the latter, your question is unfortunately off-topic here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T17:44:50.947", "Id": "439932", "Score": "0", "body": "Im sorry but I still I think it belongs here. I having calling self.faces into drive.py" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T05:45:19.163", "Id": "439982", "Score": "0", "body": "Does or doesn't the code work as intended? Because it reads like you're having import problems. But it isn't entirely clear either way. If there are problems preventing this code to work as intended, fix those first. After that, feel free to come back and we'll help you do it in a better/cleaner way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T06:10:50.343", "Id": "439984", "Score": "0", "body": "@Mast the code works, however there are many other files that are included. I was trying to call that __self.faces__ from try.py inside drive.py" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T16:44:47.270", "Id": "226382", "Score": "1", "Tags": [ "python" ], "Title": "Import this function to another class in python" }
226382
<p>I am inserting elements into the map container. For this I am using the same statements multiple times in the below function. Is there any way I can write a generic function for this? So that even at the later point of time, when required, I can insert new elements.</p> <pre><code> bool EMRMgr::GetParams() { EmIOStruct emIOstructObj; WCHAR szValue[MAX_PATH] = { 0 }; DWORD dwDataSize = sizeof(szValue) / sizeof(WCHAR); long lRes = 0; McStorageType mcStorageTypeObj = McStorageType::eRegistry; std::wstring value; // First time I am using the below statements to insert elements into the map container mcIOstructObj.lpszValueName = (LPWSTR)ER_ID; memset(szValue, 0, MAX_PATH); mcIOstructObj.lpData = (LPBYTE)&amp;szValue[0]; lRes = m_cIOManager.ReadValue(mcStorageTypeObj, mcIOstructObj); value.clear(); if ((LPWSTR)mcIOstructObj.lpData == nullptr) { value.assign(L""); } else { value.assign((LPWSTR)mcIOstructObj.lpData); } m_fileParams.insert({ (std::wstring) ER_ID, value }); // Second time I am using the below statements to insert elements into the map container mcIOstructObj.lpszValueName = (LPWSTR)CPS; memset(szValue, 0, MAX_PATH); mcIOstructObj.lpData = (LPBYTE)&amp;szValue[0]; lRes = m_cIOManager.ReadValue(mcStorageTypeObj, mcIOstructObj); value.clear(); if ((LPWSTR)mcIOstructObj.lpData == nullptr) { value.assign(L""); } else { value.assign((LPWSTR)mcIOstructObj.lpData); } m_fileParams.insert({ (std::wstring) CPS, value }); return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T18:01:30.650", "Id": "439933", "Score": "0", "body": "Code Review is a place to review implemented, working code. As it currently stands, your question appears to indicate that you are seeking help for not yet implemented code, which is off-topic for Code Review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T22:13:40.923", "Id": "439959", "Score": "1", "body": "At least to me, it looks like this is code that is clumsy to use, but does function. Unless I'm missing something, its a fine candidate for code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T05:10:47.567", "Id": "440124", "Score": "0", "body": "Please review the code now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T05:30:54.287", "Id": "440127", "Score": "1", "body": "I have rolled back your changes. Once answers are made, you should not change the question in a way to invalidate any answer." } ]
[ { "body": "<p>There is missing code so I'm assuming that ER_ID and CPS are strings. If not, you can easily sub the data type.</p>\n\n<p>Since the only difference between the blocks of code is which string (or other data type) to use (ER_ID vs. CPS), you can make a member function of EMRMgr that has the same block of code but subbing the string to use with a parameter.</p>\n\n<p>Unless I've overlooked something, this should work.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>bool EMRMgr::DoTheThing(std::string str)\n {\n mcIOstructObj.lpszValueName = (LPWSTR)str;\n memset(szValue, 0, MAX_PATH);\n mcIOstructObj.lpData = (LPBYTE)&amp;szValue[0];\n lRes = m_cIOManager.ReadValue(mcStorageTypeObj, mcIOstructObj);\n value.clear();\n if ((LPWSTR)mcIOstructObj.lpData == nullptr)\n {\n value.assign(L\"\");\n }\n else\n {\n value.assign((LPWSTR)mcIOstructObj.lpData);\n }\n\n m_fileParams.insert({ (std::wstring) str, value });\n\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T06:12:18.980", "Id": "226405", "ParentId": "226383", "Score": "1" } } ]
{ "AcceptedAnswerId": "226405", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T16:51:47.583", "Id": "226383", "Score": "0", "Tags": [ "c++", "c++11" ], "Title": "Insert elements into a map container" }
226383
<p>Output should be an object ({cal: val}), with soonest possible time throughout all calendars recommended times from the data.</p> <p>My question is: is this approach over complicated and if so, what should be the proper way to solve that task?</p> <p><strong>Incoming data is an object:</strong></p> <pre><code>let data = [ { name: "A", calendars: { "1_A@group.calendar.google.com": { busy: ["2019-08-19T14:30:00.000Z"], free: [ { start: "2019-08-19T08:00:00.000Z", end: "2019-08-19T09:30:00.000Z" } ], recommended: "2019-08-19T01:00:00.000Z" }, "2_A@group.calendar.google.com": { busy: ["2019-08-19T14:30:00.000Z"], free: [ { start: "2019-08-19T12:30:00.000Z", end: "2019-08-19T14:00:00.000Z" } ], recommended: "2019-08-19T04:00:00.000Z" } } }, { name: "B", calendars: { "1_B@group.calendar.google.com": { busy: ["2019-08-19T14:30:00.000Z"], free: [ { start: "2019-08-19T12:30:00.000Z", end: "2019-08-19T14:00:00.000Z" } ], recommended: "2019-08-19T05:00:00.000Z" }, "2_B@group.calendar.google.com": { busy: ["2019-08-19T14:30:00.000Z"], free: [ { start: "2019-08-19T12:30:00.000Z", end: "2019-08-19T14:00:00.000Z" } ], recommended: "2019-08-19T02:00:00.000Z" } } } ]; </code></pre> <p><strong>Here is how I solved it:</strong> <a href="https://codesandbox.io/s/purple-rain-ecmcu?fontsize=14" rel="nofollow noreferrer">https://codesandbox.io/s/purple-rain-ecmcu?fontsize=14</a></p> <pre><code>function reduce(data) { return data.reduce((acc, cur, i) =&gt; { if (!acc.length || cur[1] &lt; acc[1]) { return [cur[0], new Date(cur[1])]; } else { return acc; } }, []); } data = Object.fromEntries([ reduce( data.map(provider =&gt; { let providerCalendars = Object.keys(provider.calendars); let providerRecommended = Object.values(provider.calendars).map( (calendar, i) =&gt; [ providerCalendars[i], new Date(calendar.recommended).getTime() ] ); return reduce(providerRecommended); }) ) ]); </code></pre>
[]
[ { "body": "<h3>Minor Changes</h3>\n\n<ul>\n<li>Method name <code>reduce</code> suggests a generic API method that would take a predicate and accumulator. Instead, it's very specific in returning a custom array and mapping a string to <code>Date</code>. I would call it <code>getCalendarByMinimumRecommendedTime</code> instead.</li>\n<li>Prefer the use of <code>const</code> over <code>let</code> for immutable data: <code>const providerCalendars</code> and <code>const providerRecommended</code>.</li>\n<li>The unused index parameter <code>i</code> can be omitted: <code>return data.reduce((acc, cur) =&gt; {</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T09:46:06.623", "Id": "439999", "Score": "0", "body": "Ok, thank you! But overall logics is right? I mean reduce method? Or it had to be something different?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T10:02:13.767", "Id": "440002", "Score": "0", "body": "To me it looks fine. Maybe someone knows a better alternative. The only possible issue I would have is that it operates on a custom array, where you need to know what is behind index 0 and what behind 1." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T18:42:08.750", "Id": "226390", "ParentId": "226384", "Score": "0" } } ]
{ "AcceptedAnswerId": "226390", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T17:07:40.000", "Id": "226384", "Score": "3", "Tags": [ "javascript", "datetime" ], "Title": "How to properly get values from multidimensional object" }
226384
<p>This was a part of one an assignment I found online and tried to solve it myself.</p> <p>The objective was to implement a Priority Queue using Min Heap and use Array as the underlying data structure to store the data.</p> <pre><code>public class ArrayHeapMinPQ&lt;T&gt; { private PriorityNode&lt;T&gt;[] items; private int INITIALCAPACITY = 4; private int capacity = INITIALCAPACITY; private int size = 0; private Set&lt;T&gt; itemSet; // Declaring a construtor to intialize items as an array of PriorityNodes public ArrayHeapMinPQ() { itemSet = new HashSet&lt;&gt;(); items = new PriorityNode[INITIALCAPACITY]; items[0] = new PriorityNode(null, -1); } /* * Adds an item with the given priority value. Throws an * IllegalArgumentException if item is already present */ @Override public void add(T item, double priority) { ensureCapacity(); // To ensure that duplicate keys are not being used in the queue if (itemSet.contains(item)) { throw new IllegalArgumentException(); } items[size + 1] = new PriorityNode(item, priority); size++; itemSet.add(item); upwardHeapify(items[size]); } /* * Returns true if the PQ contains the given item */ @Override public boolean contains(T item) { return itemSet.contains(item); } /* * Returns the minimum item. Throws NoSuchElementException if the PQ is * empty */ @Override public T getSmallest() { if (this.size == 0) throw new NoSuchElementException(); return items[1].getItem(); } @Override public T removeSmallest() { if (this.size == 0) throw new NoSuchElementException(); T toReturn = items[1].getItem(); items[1] = items[size]; items[size] = null; size -= 1; itemSet.remove(toReturn); downwardHeapify(); ensureCapacity(); return toReturn; } // TODO: Implementation of changePriority is pending /** * Changes the priority of the given item. Throws * NoSuchElementException if the element does not exists * @param item Item for which the priority would be changed * @param priority New priority for the item */ @Override public void changePriority(T item, double priority) { if (!itemSet.contains(item)) throw new NoSuchElementException(); for (int i = 1; i &lt;= this.size; i += 1) { if (item.equals(items[i].getItem())) { PriorityNode currentNode = items[i]; double oldPriority = currentNode.getPriority(); currentNode.setPriority(priority); if (priority &lt; oldPriority) { upwardHeapify(currentNode); } else { downwardHeapify(); } break; } } } /* Returns the number of items in the PQ */ @Override public int size() { return this.size; } /* * Helper function to retrieve left child index of the parent */ private int getLeftChildIndex(int parentIndex) { return 2 * parentIndex; } /* * Helper function to retrieve right child index of the parent */ private int getRightChildIndex(int parentIndex) { return 2 * parentIndex + 1; } /* * Helper function retrieve the parent index */ private int getParentIndex(int childIndex) { return childIndex / 2; } /* * Helper method to heapify the queue upwards */ private void upwardHeapify(PriorityNode last) { PriorityNode smallestNode = items[1]; // the last node which was inserted in the array PriorityNode lastNode = last; int latestNodeIndex = size; // The max could be that last node will need to switch the smallest node while (!lastNode.equals(smallestNode)) { // Get the parent node int parentNodeIndex = getParentIndex(latestNodeIndex); PriorityNode parentNode = items[parentNodeIndex]; // The function is working because the compareTo method is // comparing the priority and not the data in the item if (parentNode.compareTo(lastNode) &gt; 0) { // Swap the last node with its parent node swap(parentNodeIndex, latestNodeIndex); // Update the method variables latestNodeIndex = parentNodeIndex; lastNode = items[latestNodeIndex]; } // The priority of the parent is less than or equal to the parent else if (parentNode.compareTo(lastNode) &lt;= 0) { break; } } } private void downwardHeapify() { // assumption is that the top node is the largest node int currentIndex = 1; while(hasLeftChild(currentIndex)) { int leftChildIndex = getLeftChildIndex(currentIndex); int smallerChildIndex = leftChildIndex; if (hasRightChild(currentIndex)) { int rightChildIndex = getRightChildIndex(currentIndex); double leftChildPriority = items[leftChildIndex].getPriority(); double rightChildPriority = items[rightChildIndex].getPriority(); if (leftChildPriority &gt; rightChildPriority) { smallerChildIndex = rightChildIndex; } } if (items[currentIndex].getPriority() &lt; items[smallerChildIndex].getPriority()) { break; } else { swap(currentIndex, smallerChildIndex); } currentIndex = smallerChildIndex; } } private boolean hasLeftChild(int index) { return getLeftChildIndex(index) &lt; this.size + 1; } private boolean hasRightChild(int index) { return getRightChildIndex(index) &lt; this.size + 1; } /* * Helper function to the class to make sure that there is enough capacity * in the array for more elements */ private void ensureCapacity() { // there are two conditions to take care of // 1. Double the size // 2. Make the size half if the array is 3/4 empty double currentLoad = (double) this.size / (double) this.capacity; int newCapacity = capacity; if(this.size &gt; 1 &amp;&amp; currentLoad &lt; 0.25) { // Array is being downSized newCapacity = capacity / 2; items = Arrays.copyOf(items, newCapacity); } else if (currentLoad &gt;= 0.5 ) { // Doubling the size of the array newCapacity = capacity * 2; items = Arrays.copyOf(items, newCapacity); } capacity = newCapacity; } /* * Helper method to swap two nodes */ private void swap(int parentNodeIndex, int latestNodeIndex) { PriorityNode temp = items[parentNodeIndex]; items[parentNodeIndex] = items[latestNodeIndex]; items[latestNodeIndex] = temp; } public Integer[] toArray() { Integer[] toReturn = new Integer[items.length]; for (int i = 1; i &lt; items.length - 1; i++) { toReturn[i] = ((Double) items[i].getPriority()).intValue(); } return toReturn; } } </code></pre> <p>PriorityNode</p> <pre><code>public class PriorityNode&lt;T&gt; implements Comparable&lt;PriorityNode&gt; { private T item; private double priority; PriorityNode(T item, double priority) { this.item = item; this.priority = priority; } protected T getItem() { return this.item; } protected double getPriority() { return this.priority; } protected void setPriority(double priority) { this.priority = priority; } @Override public int compareTo(PriorityNode other) { if (other == null) { return -1; } return Double.compare(this.getPriority(), other.getPriority()); } @Override @SuppressWarnings("unchecked") public boolean equals(Object o) { if (o == null || o.getClass() != this.getClass()) { return false; } else { return ((PriorityNode) o).getItem().equals(this.getItem()); } } @Override public int hashCode() { return item.hashCode(); } } </code></pre> <p>I had to implement an interface and I have omitted that part in the code. In my opinion, the change priority function is running at <span class="math-container">\$O(n)\$</span> and I am not sure how can I improve the performance of it.</p> <p>I am looking for a discussion on the code in general and the performance of changePriority function.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T18:57:35.277", "Id": "439936", "Score": "0", "body": "Where does PriorityNode come from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T19:01:09.797", "Id": "439937", "Score": "0", "body": "Apologies! I forgot to add code for PriorityNode. Have added it to the main question" } ]
[ { "body": "<h2>General Review</h2>\n\n<p>Make all instance fields that are never reassigned <code>final</code>. From the comments you suggest some of these fields get reassigned later in the code. In this case, those fields should not be declared <em>final</em>.</p>\n\n<pre><code> private final PriorityNode&lt;T&gt;[] items;\n private final Set&lt;T&gt; itemSet;\n</code></pre>\n\n<p>Make constants static and readonly, and use underscores for readability.</p>\n\n<pre><code> private static final int INITIAL_CAPACITY = 4;\n private int capacity = INITIAL_CAPACITY;\n</code></pre>\n\n<p>Don't introduce unnecessary new lines. For instance, between class definition and instance variables. Zero or one new line would suffice.</p>\n\n<blockquote>\n<pre><code>public class ArrayHeapMinPQ&lt;T&gt; {\n\n\n private PriorityNode&lt;T&gt;[] items;\n</code></pre>\n</blockquote>\n\n<pre><code>public class ArrayHeapMinPQ&lt;T&gt; {\n private PriorityNode&lt;T&gt;[] items;\n</code></pre>\n\n<p>Don't write comments that state the obvious. It's polluting the source code. Write comments for when they would really make sense.</p>\n\n<blockquote>\n<pre><code> // Declaring a construtor to intialize items as an array of PriorityNodes\n public ArrayHeapMinPQ() {\n</code></pre>\n</blockquote>\n\n<p>Like public API comments (this is a good thing):</p>\n\n<blockquote>\n<pre><code> /*\n * Adds an item with the given priority value. Throws an\n * IllegalArgumentException if item is already present\n */\n @Override\n public void add(T item, double priority) {\n</code></pre>\n</blockquote>\n\n<p>Perform argument checks before changing the state of the instance. (And remove these comments that have zero added value)</p>\n\n<blockquote>\n<pre><code>public void add(T item, double priority) {\n ensureCapacity();\n\n // To ensure that duplicate keys are not being used in the queue\n if (itemSet.contains(item)) {\n throw new IllegalArgumentException();\n }\n</code></pre>\n</blockquote>\n\n<pre><code>public void add(T item, double priority) {\n if (itemSet.contains(item)) {\n throw new IllegalArgumentException();\n }\n ensureCapacity();\n</code></pre>\n\n<p>It is custom in Java to provide not just <code>add</code>, but also <code>offer</code> methods. <code>add</code> throws an exception, while <code>offer</code> returns a <code>boolean</code>. To accomodate multiple entrypoints, you should put the actual insertion of data in a private method.</p>\n\n<pre><code>private void insert(T item, double priority) {\n ensureCapacity();\n items[size + 1] = new PriorityNode(item, priority);\n size++;\n itemSet.add(item);\n upwardHeapify(items[size]);\n}\n</code></pre>\n\n<p>And then refactor <code>add</code>:</p>\n\n<pre><code> /*\n * Adds an item with the given priority value. Throws an\n * IllegalArgumentException if item is already present\n */\n @Override\n public void add(T item, double priority) {\n if (itemSet.contains(item)) {\n throw new IllegalArgumentException();\n }\n insert(item, priority);\n }\n</code></pre>\n\n<p>And introduce <code>offer</code>:</p>\n\n<pre><code> /*\n * Adds an item with the given priority value. Returns\n * False if item is already present\n */\n public boolean offer(T item, double priority) {\n if (itemSet.contains(item)) {\n return false;\n }\n insert(item, priority);\n return true;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T19:21:47.223", "Id": "439939", "Score": "2", "body": "Thank you so much for the great feedback and for helping me improve. The `offer` methods bit was completely new to me. I will certainly follow this advice in all my code hereupon.\n\nHighly appreciate you spending time in reading my code and giving me feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T08:58:42.187", "Id": "439995", "Score": "0", "body": "Wouldn't it be less duplicative for `add` to be `if (!offer(item, priority)) throw new IllegalArgumentException();`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T10:00:35.030", "Id": "440001", "Score": "0", "body": "@PeterTaylor Well, that's an option, but the way the Java classes internally work, is that the public methods call the private one: http://fuseyism.com/classpath/doc/java/util/concurrent/ArrayBlockingQueue-source.html." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T19:10:49.827", "Id": "440070", "Score": "1", "body": "Java does not have a `readonly` keyword. Constants are `public static final` (or whatever the correct access level is)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T22:11:13.887", "Id": "440453", "Score": "0", "body": "If I am declaring `items` to be final my code stops working. The variable `items` gets updated in the code later. Should I still try to work around to make it `final`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T04:47:26.407", "Id": "440468", "Score": "0", "body": "I didn't notice it got updated. If it gets updated, it should not be final." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T10:51:37.333", "Id": "440488", "Score": "0", "body": "Thanks. Have changed my program to make the variable non-final" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T19:12:06.697", "Id": "226391", "ParentId": "226387", "Score": "3" } } ]
{ "AcceptedAnswerId": "226391", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T17:44:35.560", "Id": "226387", "Score": "4", "Tags": [ "java", "complexity", "heap" ], "Title": "Min Heap Priority Queue" }
226387
<p>ViewController2 (source) Has several TextFields, each with their own switches.</p> <p>ViewController1 (destination) Has one TextView waiting for data to be sent to it from ViewController2 (source) But i need only the text from the TextFields that have their "switches" turned on.</p> <p>I can get it working individually with TextField1 when Switch1 is turned on, but I don't know how to combine the text from several ones once turned on.</p> <p>Example: If Switches for both TextField1 and TextField2 are turned on, then it should put the text form both of them into the single TextView on ViewController1</p> <p>Question How do I combine the text from several ones once turned on ? At time there could be only 1 switch turned on, or at times many switches turned on.</p> <p>My code that i am using so far</p> <p>ViewController2 (Source)</p> <pre><code> let defaults = UserDefaults.standard var switchON : Bool = false @IBAction func checkState(_ sender: AnyObject) { if Switch1.isOn{ switchON = true defaults.set(switchON, forKey: "switch1ON") } if Switch1.isOn == false{ switchON = false defaults.set(switchON, forKey: "switch1ON") } if Switch2.isOn{ switchON = true defaults.set(switchON, forKey: "switch2ON") } if Switch2.isOn == false{ switchON = false defaults.set(switchON, forKey: "switch2ON") </code></pre> <p>ViewController1(Destination)</p> <pre><code>override func viewDidLoad(){ super.viewDidLoad() // Do any additional setup after loading the view. // Select Comments ----------------------------------- if defaults.value(forKey: "switch1ON") != nil{ let switch1ON: Bool = defaults.value(forKey: "switch1ON") as! Bool if switch1ON == true{ let userDefaults = UserDefaults.standard Reference.text = userDefaults.value(forKey: "PredefinedText1") as? String } if defaults.value(forKey: "switch2ON") != nil{ let switch2ON: Bool = defaults.value(forKey: "switch2ON") as! Bool if switch2ON == true{ let userDefaults = UserDefaults.standard Reference.text = userDefaults.value(forKey: "PredefinedText2") as? String } // else if switch1ON == false{ // let userDefaults = UserDefaults.standard // Reference.text = userDefaults.value(forKey: "") as? String //} } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T22:33:48.217", "Id": "226392", "Score": "1", "Tags": [ "swift", "ios" ], "Title": "Combining the text from selected TextFields into 1 TextView - Conditionally" }
226392
CircuitPython is an open source derivative of the MicroPython programming language targeted towards the student and beginner.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T01:00:16.390", "Id": "226395", "Score": "0", "Tags": null, "Title": null }
226395
Symfony is a PHP framework developed by SensioLabs. Symfony 4 was released November 2017.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T01:02:05.190", "Id": "226397", "Score": "0", "Tags": null, "Title": null }
226397
<p>This is from <a href="https://leetcode.com/problems/missing-number/" rel="nofollow noreferrer">LeetCode</a>:</p> <blockquote> <p>Missing Number</p> <p>Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.</p> <p>Example 1:</p> <p>Input: [3,0,1]<br> Output: 2 </p> <p>Example 2:</p> <p>Input: [9,6,4,2,3,5,7,0,1]<br> Output: 8 </p> <p>Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?</p> </blockquote> <p>Code:</p> <pre><code>def missing_number(nums) nums.empty? ? 0 : nums.inject(:^)^(1..nums.length).inject(:^) end </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T04:36:28.547", "Id": "226400", "Score": "4", "Tags": [ "algorithm", "ruby" ], "Title": "Identifying the missing number in an array" }
226400
<p>The codes below get the rows of data until it reaches the total running quantity limit.</p> <p>Notice that the SQL uses sub-query. <code>select *, sum(Quantity) over (order by id) as RunningQty from #PurchaseOrderProducts</code>. I'm worried that the sub-query would get all the data from the table. Is there a way to improve the performance?</p> <pre><code>CREATE TABLE #PurchaseOrderProducts ( Id int, Product varchar(10), Quantity int ) INSERT INTO #PurchaseOrderProducts VALUES (1, 'Item A', 5) INSERT INTO #PurchaseOrderProducts VALUES (2, 'Item B', 1) INSERT INTO #PurchaseOrderProducts VALUES (3, 'Item C', 8) INSERT INTO #PurchaseOrderProducts VALUES (4, 'Item D', 2) INSERT INTO #PurchaseOrderProducts VALUES (5, 'Item E', 1) SELECT P.* FROM (select *, sum(Quantity) over (order by id) as RunningQty from #PurchaseOrderProducts ) P WHERE P.RunningQty - Quantity &lt; 12; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T06:35:10.247", "Id": "439988", "Score": "0", "body": "Have you checked the query plan?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T11:48:12.400", "Id": "440005", "Score": "0", "body": "You could add \"LIMIT 12\" to your subquery if your items respect quantity >= 1. This will bound your outer query performance. Note that this is a quite simple table manipulation even with a subquery it will be most likely optimised to be O(nlogn) so if a query as simple as this causes performance issues, then you have a design problem elsewhere." } ]
[ { "body": "<p>Assuming that <code>#PurchaseOrderProducts</code> is a realistic depiction of your real table but with less data (and that your real table is also a heap), then I get this plan.</p>\n\n<p><a href=\"https://i.stack.imgur.com/JnHXz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JnHXz.png\" alt=\"Query plan with code as written\"></a></p>\n\n<p>This is a pretty reasonable plan, where I wouldn't necessarily expect it to be that bad.</p>\n\n<p>There are a few things we could do to make this better, including:</p>\n\n<ol>\n<li>Batch-mode for rowstore is enabled (via hacks) in SQL Server 2016 if you include a CCI in your query, even if it isn't used. This can likely make the window function better. This gets me a batch-mode operator for everything but the table scan, and cleans up a lot of the aggregation. <a href=\"https://i.stack.imgur.com/KKywP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KKywP.png\" alt=\"rowstore batch mode\"></a></li>\n<li>Creating an appropriate index that your window function can use will help as well by removing the sort (the index maintains a sorted order). A clustered index on the <code>Id</code> column moves all of the cost onto the index scan. A non-clustered index on <code>Id</code> that <code>INCLUDE</code>s <code>Quantity</code> and <code>Product</code> (order didn't matter in my testing) does the same. You'll have to <code>INCLUDE</code> any columns you want in the output, however - otherwise it will just table scan, or if you force it to use the index it'll key lookup. That won't be great for performance. <a href=\"https://i.stack.imgur.com/wIeFd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wIeFd.png\" alt=\"clustered index scan\"></a> <a href=\"https://i.stack.imgur.com/lUaN9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lUaN9.png\" alt=\"nonclustered index scan\"></a><a href=\"https://i.stack.imgur.com/1C5K7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1C5K7.png\" alt=\"key lookup :(\"></a></li>\n</ol>\n\n<p>If we look at all of these side-by-side, we notice that the non-clustered without an <code>INCLUDE</code> is the worst by far, and the rest all look about the same.</p>\n\n<p><a href=\"https://i.stack.imgur.com/IrtVk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IrtVk.png\" alt=\"side-by-side\"></a></p>\n\n<p>You may notice that the batch-mode query is also using the non-clustered index; getting all of the plans side-by-side without indices is a pain. If you use the batch-mode hack without any indices then it will still have to sort the data, but it can do that in batch mode which will provide a nice performance bump. This is also good if you rely on the table being a heap elsewhere (e.g. parallel inserts, minimal logging, etc).</p>\n\n<p>You may also notice that the plans using the clustered index vs non-clustered index have no apparent difference (besides the index they use). This is because all of the columns in the table are selected in both queries, and all indices include all columns. You can get substantial performance and memory savings if you only need a subset of columns and have a good non-clustered index; this might be helpful for your real data if the temp table isn't representative.</p>\n\n<hr>\n\n<p>Query samples:</p>\n\n<p>Batch mode w/ rowstore table</p>\n\n<pre><code>DROP TABLE IF EXISTS #FakeCciForRowstoreBatchMode;\nCREATE TABLE #FakeCciForRowstoreBatchMode\n(\n __zzDontUseMe bit NULL,\n INDEX CCI CLUSTERED COLUMNSTORE\n);\n\nDROP TABLE IF EXISTS #PurchaseOrderProducts;\nCREATE TABLE #PurchaseOrderProducts\n(\n Id int,\n Product varchar(10),\n Quantity int\n);\n\nINSERT INTO #PurchaseOrderProducts\nVALUES\n( 1, 'Item A', 5 ),\n( 2, 'Item B', 1 ),\n( 3, 'Item C', 8 ),\n( 4, 'Item D', 2 ),\n( 5, 'Item E', 1 );\n\nSELECT P.Id,\n P.Product,\n P.RunningQty,\n P.Quantity\n FROM ( SELECT Id,\n Product,\n Quantity,\n SUM( Quantity ) OVER ( ORDER BY Id ) RunningQty\n FROM #PurchaseOrderProducts\n LEFT OUTER JOIN #FakeCciForRowstoreBatchMode\n ON 1 = 0 ) P\n WHERE P.RunningQty - P.Quantity &lt; 12;\n</code></pre>\n\n<p>Indices I created for #2 (plans generated using <code>INDEX</code> hints)</p>\n\n<pre><code>CREATE CLUSTERED INDEX whatever ON #PurchaseOrderProducts( Id ASC )\nCREATE NONCLUSTERED INDEX whatever2 ON #PurchaseOrderProducts( Id ASC ) INCLUDE( Quantity, Product )\nCREATE NONCLUSTERED INDEX whatever3 ON #PurchaseOrderProducts( Id ASC ) INCLUDE( Product, Quantity )\nCREATE NONCLUSTERED INDEX whatever4 ON #PurchaseOrderProducts( Id ASC )\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T14:50:42.497", "Id": "226626", "ParentId": "226401", "Score": "2" } } ]
{ "AcceptedAnswerId": "226626", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T04:54:54.987", "Id": "226401", "Score": "3", "Tags": [ "sql", "sql-server", "t-sql" ], "Title": "SQL Sub-query with running total optimization" }
226401
<p>I'm attempting to write an animation system on top of SFML, and I've come up with a design where I can wrap sf::Drawable objects into a RenderComponent class, and the RenderComponent class can be given an Animation object at any time, which will overwrite a previous animation if one exists. Here is what I'm looking for.</p> <ol> <li>Am I using the std::unique_ptr correctly/optimally?</li> <li>Should I be using a pointer to store the Animation?</li> <li>Is my method of settings the animation (with a variadic template) too complicated, and is there a better way?</li> <li>I would normally separate the code into header and implementation, but for the brevity, I am uploading it in pure headers. Ignore that please.</li> <li>Any general advice.</li> </ol> <p><strong>Here is the code:</strong></p> <p>Animation base class</p> <pre class="lang-cpp prettyprint-override"><code>class Animation { typedef std::chrono::high_resolution_clock hrc; private: std::chrono::time_point&lt;hrc&gt; m_now; protected: unsigned int m_us; // us for microseconds unsigned int m_endUs; void UpdateTime() { auto end = hrc::now(); auto diff = end - m_now; m_now = end; auto msDuration = std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(diff); m_us += (unsigned int)msDuration.count(); } public: Animation() { m_us = 0; m_now = hrc::now(); } bool finished() { return m_endUs &lt;= m_us; } virtual bool Update(sf::Sprite&amp; spr) = 0; }; </code></pre> <p>Animation child class</p> <pre class="lang-cpp prettyprint-override"><code>class FadeIn : public Animation { public: FadeIn(int ms) { m_endUs = ms * 1000; } // Updates the sprite based on the timeline, and returns if the animation is over virtual bool Update(sf::Sprite&amp; spr) { UpdateTime(); if (finished()) return true; sf::Color color = spr.getColor(); color.a = (int)((float)m_us / m_endUs * 255); spr.setColor(color); return false; } }; </code></pre> <p>Render Component</p> <pre class="lang-cpp prettyprint-override"><code>class RenderComponent { private: sf::Texture m_texDefault; std::unique_ptr&lt;Animation&gt; m_animationPtr; public: RenderComponent() { } RenderComponent(sf::Drawable* element, sf::Vector2u size) { sf::RenderTexture rt; rt.create((unsigned int)size.x, (unsigned int)size.y); rt.draw(*element); m_texDefault = rt.getTexture(); } template &lt;typename T, typename... Args&gt; void SetAnimation(Args... args) { m_animationPtr = std::make_unique&lt;T&gt;(args...); } void draw(sf::RenderTarget* target) { sf::Sprite sprite; sprite.setTexture(m_texDefault); // Handle animation and set pointer to null if done if (m_animationPtr) { if (m_animationPtr.get()-&gt;Update(sprite)) { m_animationPtr = nullptr; } sf::Color c = sprite.getColor(); } target-&gt;draw(sprite); } }; </code></pre> <p>A helper function</p> <pre class="lang-cpp prettyprint-override"><code>sf::Vector2u floatRectToVec2u(sf::FloatRect r) { sf::Vector2u vec; vec.x = (unsigned int)ceil(r.width); vec.y = (unsigned int)ceil(r.height); return vec; auto start = std::chrono::high_resolution_clock::now(); } </code></pre> <p>Main function</p> <pre class="lang-cpp prettyprint-override"><code>int main() { sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!"); sf::CircleShape shape(100.f); shape.setFillColor(sf::Color::Green); RenderComponent circle(&amp;shape, floatRectToVec2u(shape.getGlobalBounds())); circle.SetAnimation&lt;FadeIn&gt;(1000); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } window.clear(); circle.draw(&amp;window); window.display(); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-01T08:31:55.847", "Id": "442212", "Score": "0", "body": "(Too late, but) Welcome to Code Review! Nice first question." } ]
[ { "body": "<h1>Animation base class</h1>\n\n<blockquote>\n<pre><code>typedef std::chrono::high_resolution_clock hrc;\n</code></pre>\n</blockquote>\n\n<p>In modern C++, use an <em>alias-declaration</em>:</p>\n\n<pre><code>using hrc = std::chrono::high_resolution_clock;\n</code></pre>\n\n<p>It is arguably more readable.</p>\n\n<blockquote>\n<pre><code>std::chrono::time_point&lt;hrc&gt; m_now;\n\nunsigned int m_us; // us for microseconds\nunsigned int m_endUs;\n</code></pre>\n</blockquote>\n\n<p>The types and names of the last two members are not helpful. (By the way, <code>unsigned int</code> = <code>unsigned</code>.) And they should be <code>private</code>:</p>\n\n<pre><code>private:\n using time_point = std::chrono::high_resolution_clock::time_point;\n time_point m_now;\n\n using duration = std::chrono::high_resolution_clock::duration;\n duration m_time_elapsed;\n duration m_total_time;\n</code></pre>\n\n<p>The derived classes should have read-only access to <code>m_total_time</code>:</p>\n\n<pre><code>protected:\n auto total_time() const\n {\n return m_total_time; \n }\n</code></pre>\n\n<blockquote>\n<pre><code>void UpdateTime() {\n auto end = hrc::now();\n auto diff = end - m_now;\n m_now = end;\n auto msDuration = std::chrono::duration_cast&lt;std::chrono::microseconds&gt;(diff);\n m_us += (unsigned int)msDuration.count();\n}\n</code></pre>\n</blockquote>\n\n<p>This function is a bit complex because of the conversion between different types. They can be simplified:</p>\n\n<pre><code>void UpdateTime()\n{\n auto time = hrc::now();\n time_elapsed += time - m_now;\n m_now = time;\n}\n</code></pre>\n\n<blockquote>\n<pre><code>Animation() {\n m_us = 0;\n m_now = hrc::now();\n}\n</code></pre>\n</blockquote>\n\n<p>The constructor should provide a means to set the <code>m_total_time</code> member. And it should use member initializer clauses instead of assignment:</p>\n\n<pre><code>template &lt;class Rep, class Period&gt;\nexplicit Animation(const std::chrono::duration&lt;Rep, Period&gt;&amp; total_time)\n : m_now{hrc::now()}\n , m_time_elapsed{}\n , m_total_time{total_time} // std::chrono::duration supports conversion\n{\n}\n</code></pre>\n\n<p>(The support for different <code>duration</code>s is for convenience.)</p>\n\n<blockquote>\n<pre><code>bool finished() {\n return m_endUs &lt;= m_us;\n}\n</code></pre>\n</blockquote>\n\n<p>You are missing <code>const</code>.</p>\n\n<blockquote>\n<pre><code>virtual bool Update(sf::Sprite&amp; spr) = 0;\n</code></pre>\n</blockquote>\n\n<p>Good.</p>\n\n<h1>Animation child class</h1>\n\n<blockquote>\n<pre><code>FadeIn(int ms) {\n m_endUs = ms * 1000;\n}\n</code></pre>\n</blockquote>\n\n<p>Missing <code>explicit</code> &mdash; an integer is not logically a <code>FadeIn</code>. Type mismatch (you are using <code>unsigned</code> in the base class). With the design mentioned, just do this:</p>\n\n<pre><code>using Animation::Animation;\n</code></pre>\n\n<p>And the constructors will work as expected.</p>\n\n<blockquote>\n<pre><code>// Updates the sprite based on the timeline, and returns if the animation is over\nvirtual bool Update(sf::Sprite&amp; spr) {\n UpdateTime();\n if (finished()) return true;\n\n sf::Color color = spr.getColor();\n color.a = (int)((float)m_us / m_endUs * 255);\n spr.setColor(color);\n return false;\n}\n</code></pre>\n</blockquote>\n\n<p>Missing <code>override</code>. Don't use C-style casts. <code>float</code> may be too imprecise for this calculation. Don't put the whole <code>if</code> statement on a single line.</p>\n\n<p>The color algorithm should be in a separate function:</p>\n\n<pre><code>private:\n sf::Color get_color() const noexcept\n {\n auto color = spr.getColor();\n\n double ratio = static_cast&lt;double&gt;(m_time_elapsed) / m_total_time;\n color.a = static_cast&lt;int&gt;(ratio * 255);\n return color;\n }\n</code></pre>\n\n<p>Also, if overflow is not a concern, just multiply first and then divide to avoid the floating point. And then the function can be simplified:</p>\n\n<pre><code>virtual bool Update(sf::Sprite&amp; spr) override\n{\n UpdateTime();\n\n if (finished()) {\n return true;\n } else {\n spr.setColor(get_color());\n return false;\n }\n}\n</code></pre>\n\n<h1>Render Component</h1>\n\n<blockquote>\n<pre><code>RenderComponent() { }\nRenderComponent(sf::Drawable* element, sf::Vector2u size) {\n sf::RenderTexture rt;\n rt.create((unsigned int)size.x, (unsigned int)size.y);\n rt.draw(*element);\n m_texDefault = rt.getTexture();\n}\n</code></pre>\n</blockquote>\n\n<p>Good &mdash; except for the C-style casts:</p>\n\n<ul>\n<li><p>remove them if possible;</p></li>\n<li><p>otherwise, use <code>unsigned{size.x}</code> if possible;</p></li>\n<li><p>otherwise, use <code>static_cast</code>.</p></li>\n</ul>\n\n<blockquote>\n<pre><code>template &lt;typename T, typename... Args&gt;\nvoid SetAnimation(Args... args) {\n m_animationPtr = std::make_unique&lt;T&gt;(args...);\n}\n</code></pre>\n</blockquote>\n\n<p>You are missing perfect forwarding:</p>\n\n<pre><code>template &lt;typename T, typename... Args&gt;\nvoid SetAnimation(Args&amp;&amp;... args)\n{\n m_animationPtr = std::make_unique&lt;T&gt;(std::forward&lt;Args&gt;(args)...);\n}\n</code></pre>\n\n<blockquote>\n<pre><code>void draw(sf::RenderTarget* target) {\n sf::Sprite sprite;\n sprite.setTexture(m_texDefault);\n\n // Handle animation and set pointer to null if done\n if (m_animationPtr) {\n if (m_animationPtr.get()-&gt;Update(sprite)) {\n m_animationPtr = nullptr;\n }\n sf::Color c = sprite.getColor();\n }\n target-&gt;draw(sprite);\n}\n</code></pre>\n</blockquote>\n\n<p>Always turn warnings on &mdash; unused <code>c</code> variable should issue a warning. (I am pretty sure <code>sprite.getColor()</code> has any side effects.)</p>\n\n<h1>A helper function</h1>\n\n<blockquote>\n<pre><code>sf::Vector2u floatRectToVec2u(sf::FloatRect r) {\n sf::Vector2u vec;\n vec.x = (unsigned int)ceil(r.width);\n vec.y = (unsigned int)ceil(r.height);\n return vec;\n auto start = std::chrono::high_resolution_clock::now();\n}\n</code></pre>\n</blockquote>\n\n<p>This function is a pure math function, so should probably be <code>noexcept</code>. The name is a bit awkward &mdash; it does not mention <code>ceil</code> at all. Also, it seems that <code>ceil</code> should be <code>std::ceil</code>. And what does the last line do?</p>\n\n<p>If <code>sf::Vector2u</code> can be constructed with the coordinates, the code is simplified:</p>\n\n<pre><code>sf::Vector2u ceil_vector(sf::FloatRect r)\n{\n return {std::ceil(r.width), std::ceil(r.height)};\n}\n</code></pre>\n\n<h1>Main function</h1>\n\n<blockquote>\n<pre><code>int main()\n{\n sf::RenderWindow window(sf::VideoMode(200, 200), \"SFML works!\");\n sf::CircleShape shape(100.f);\n shape.setFillColor(sf::Color::Green);\n RenderComponent circle(&amp;shape, floatRectToVec2u(shape.getGlobalBounds()));\n circle.SetAnimation&lt;FadeIn&gt;(1000);\n\n while (window.isOpen())\n {\n sf::Event event;\n while (window.pollEvent(event))\n {\n if (event.type == sf::Event::Closed)\n window.close();\n }\n\n window.clear();\n circle.draw(&amp;window);\n window.display();\n }\n\n return 0;\n}\n</code></pre>\n</blockquote>\n\n<p>The main function looks nice. (I don't why you are explicitly specifying <code>100.f</code> here instead of <code>100</code>, but maybe there's a good reason.) <code>return 0;</code> is redundant for <code>main</code> and can be omitted. <code>event</code> can be declared in the inner loop with <code>for</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-01T08:04:20.663", "Id": "227258", "ParentId": "226402", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T06:00:54.617", "Id": "226402", "Score": "3", "Tags": [ "c++", "game", "animation", "sfml" ], "Title": "C++ SFML Animation System" }
226402
<p>I wrote a stack class in C++ using arrays of fixed width. Could anyone review my code ? I didn't comment on any of the functions, because I thought class itself is self explanatory. Is it a wrong approach or which kind of comments can I write?</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;iostream&gt; template &lt;class T&gt; class Stack { public: Stack(void); //ctor void push(const T&amp; item); T pop(void); void clear(void); T top(void) const; bool empty(void) const; bool full(void) const; void print(void) const; private: static const int MAX = 50; T list[MAX]; int topPtr; }; template &lt;class T&gt; Stack&lt;T&gt;::Stack(void) { this-&gt;topPtr = -1; } template &lt;class T&gt; void Stack&lt;T&gt;::push(const T&amp; item) { if(this-&gt;topPtr == this-&gt;MAX - 1) { std::cerr &lt;&lt; "Stack overflow. Can't push" &lt;&lt; '\n'; } else { this-&gt;topPtr += 1; this-&gt;list[topPtr] = item; } } template &lt;class T&gt; T Stack&lt;T&gt;::pop(void) { if(this-&gt;topPtr &lt; 0) { std::cerr &lt;&lt; "Stack is empty. Can't pop" &lt;&lt; '\n'; } else { T r_value = this-&gt;list[this-&gt;topPtr]; this-&gt;topPtr -= 1; return r_value; } } template &lt;class T&gt; void Stack&lt;T&gt;::clear(void) { this-&gt;topPtr = -1; } template &lt;class T&gt; T Stack&lt;T&gt;::top(void)const { if(this-&gt;topPtr &lt; 0) { std::cerr &lt;&lt; "Stack is empty. No top element." &lt;&lt; '\n'; } else { return this-&gt;list[topPtr]; } } template &lt;class T&gt; bool Stack&lt;T&gt;::empty(void) const { return (this-&gt;topPtr == -1); } template &lt;class T&gt; bool Stack&lt;T&gt;::full(void) const { return (this-&gt;topPtr == this-&gt;MAX -1); } template &lt;class T&gt; void Stack&lt;T&gt;::print(void) const { for (int i = this-&gt;topPtr; i &gt;= 0; i--) std::cout &lt;&lt; this-&gt;list[i] &lt;&lt; '\n'; } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Seems like a nice implementation! Here are my thoughts,</p>\n\n<ul>\n<li><p><code>this</code> is implicit. Consider removing <code>this</code>, i.e. use <code>topPtr</code> instead of <code>this-&gt;topPtr</code>. Similarly, <code>void</code> doesn't need to be used as an argument, consider removing <code>void</code>, i.e. <code>top()</code> instead of <code>top(void)</code>.</p></li>\n<li><p>Consider using <code>std::size_t</code> for <code>MAX</code>. Also, consider naming <code>MAX</code> as <code>MAX_SIZE</code> since it is slightly more descriptive. If using <code>std::size_t</code>, make sure not to subtract one from <code>MAX</code> to avoid overflow. Instead, when checking for equality, add one to the other side. </p></li>\n<li><p>It might be nicer to use a <code>T*</code> instead of an <code>int</code> for <code>topPtr</code>. <code>nullptr</code> could be used instead of <code>-1</code> initially for <code>topPtr</code>.</p></li>\n<li><p>For <code>print</code> consider passing a <code>std::ostream</code> object. This allows for decoupling and one could pass in a <code>std::ostringstream</code> instead of <code>std::cout</code> if desired.</p></li>\n<li><p>For <code>top</code> and <code>pop</code>, consider using <code>assert</code> instead <code>if/else</code>. An exception could also be used, but I think <code>assert</code> is a little nicer. To include a message, use something similar <code>assert(!empty() &amp;&amp; \"Stack is empty. Can't pop\");</code>. See <a href=\"https://en.cppreference.com/w/cpp/error/assert\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/error/assert</a>. Maybe add a comment about the requirements of these functions.</p></li>\n<li><p>Consider adding documentation for any public function. Include information such as what the function returns, requires, and modifies. For example, <code>top</code> requires there are element in the stack.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T12:36:25.990", "Id": "440008", "Score": "1", "body": "All good comments, the issue with `assert()` it won't do anything when compiled in what you would call \"Release\" mode." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T13:38:34.243", "Id": "440019", "Score": "0", "body": "Thank you @Milo Hartsoe for the comments. I removed `this`, changed `int MAX` to `std::size_t MAX_SIZE`, changed `int topPtr` to `T* topPtr` and introduced new variable `std::size_t size` to keep stack size, passed `std::ostream`object to `print` function. I guess all lead to a better structure." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T12:13:05.467", "Id": "226414", "ParentId": "226410", "Score": "2" } }, { "body": "<ul>\n<li><p><code>#include &lt;stdlib.h&gt;</code> is unnecessary.</p></li>\n<li><p>C++ is not Java. All those <code>this-&gt;</code> could be safely dropped.</p></li>\n<li><p><code>pop</code> does not return anything if the stack is empty. This invokes an undefined behavior.</p></li>\n<li><p>Do not print from such low level utility methods. Printing tells nothing to the caller. Use success/failure return value.</p></li>\n<li><p>C++ containers are expected (in fact, required, see 23.2.1 for details) to destroy elements in as they are removed.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T07:19:34.737", "Id": "440133", "Score": "0", "body": "Thank you for the suggestions. I changed the return type of `pop` to `void`, and removed `this` pointers. I want to ask can the content of a static array be removed? I made a search, but it looks like not possible." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T03:14:09.790", "Id": "226470", "ParentId": "226410", "Score": "2" } } ]
{ "AcceptedAnswerId": "226414", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T09:35:42.527", "Id": "226410", "Score": "4", "Tags": [ "c++", "stack" ], "Title": "Basic Stack in C++ Using Array" }
226410
<p>Here is my first attempt at creating a full Champions League Simulation, including drawing the groups and subsequent games and playing all matches. The code is very, very long and I am sure there must be a more concise way of writing it. </p> <p>One problem I could not get around was when drawing the groups not allowing a team from the same league to be in the same group and also ensuring that each team only appeared in one group.</p> <p>Below is the code, I have tried to use as little unnecessary code as possible but a lot of the functions have just one or two differences. Let me know what you think and if I can solve any problems or reduce the code. Thanks!</p> <pre><code>from typing import Any import math import random H_PARAMETER = 1.148698355 A_PARAMETER = 0.8705505633 class Team: def __init__(self, name, league, skill): self.name = name self.league = league self.skill = skill self.points = self.gf = self.ga = self.wins = self.draws = self.losses = self.mp = 0 self.kohg = self.koag = self.qfhg = self.qfag = self.sfhg = self.sfag = 0 self.kog = 0 # For knockout goals - so that they start from zero self.qfg = 0 # For quarter final goals - so that they start from zero self.sfg = 0 # For semi final goals - so that they start from zero self.fg = 0 # For final goals - so that they start from zero self.penalty = 0 # For penalty shootout in the final pot_1 = [] pot_2 = [] pot_3 = [] pot_4 = [] group_a = [] group_b = [] group_c = [] group_d = [] group_e = [] group_f = [] group_g = [] group_h = [] groups = [group_a, group_b, group_c, group_d, group_e, group_f, group_g, group_h] allocated_teams = [] qualified_for_knockouts = [] qualified_quarter_finals =[] qualified_semi_finals =[] qualified_final =[] match_1_teams = [] match_2_teams = [] match_3_teams = [] match_4_teams = [] match_5_teams = [] match_6_teams = [] match_7_teams = [] match_8_teams = [] match_teams = [match_1_teams, match_2_teams, match_3_teams, match_4_teams, match_5_teams, match_6_teams, match_7_teams, match_8_teams] quarter_final_1 = [] quarter_final_2 = [] quarter_final_3 = [] quarter_final_4 = [] quarter_finals =[quarter_final_1, quarter_final_2, quarter_final_3, quarter_final_4] semi_final_1 = [] semi_final_2 = [] semi_finals = [semi_final_1, semi_final_2] def group_selection(group): selection_1 = random.choice(pot_1) group.append(selection_1) pot_1.remove(selection_1) selection_2 = random.choice(pot_2) group.append(selection_2) pot_2.remove(selection_2) selection_3 = random.choice(pot_3) group.append(selection_3) pot_3.remove(selection_3) selection_4 = random.choice(pot_4) group.append(selection_4) pot_4.remove(selection_4) def generate_random_goals(delta_skill, parameter): if delta_skill == 0: raise ValueError goals = 0 lamb = parameter ** delta_skill z = random.random() while z &gt; 0: z = z - (((lamb ** goals) * math.exp(-1 * lamb)) / math.factorial(goals)) goals += 1 return goals - 1 def generate_random_score(home, away): delta_skill = (home.skill - away.skill) / 12 return generate_random_goals(delta_skill, H_PARAMETER), generate_random_goals(delta_skill, A_PARAMETER) def simulate_league(group): for home_team in group: print("=" * 50) print(home_team.name.upper() + "'S HOME GAMES: ") print("=" * 50) for away_team in group: if home_team == away_team: pass if home_team != away_team: home_score, away_score = generate_random_score(home_team, away_team) print(home_team.name, home_score, ":", away_score, away_team.name) home_team.gf += home_score away_team.gf += away_score home_team.ga += away_score away_team.ga += home_score home_team.mp += 1 away_team.mp += 1 if home_score == away_score: home_team.draws += 1 away_team.draws += 1 home_team.points += 1 away_team.points += 1 if home_score &gt; away_score: home_team.wins += 1 away_team.losses += 1 home_team.points += 3 if away_score &gt; home_score: away_team.wins += 1 home_team.losses += 1 away_team.points += 3 def simulate_knockout(knockout_match_teams): for home_team in knockout_match_teams: print("=" * 50) print(home_team.name.upper() + "'S HOME GAME: ") print("=" * 50) for away_team in knockout_match_teams: if home_team == away_team: pass if home_team != away_team: home_score, away_score = generate_random_score(home_team, away_team) print(home_team.name, home_score, ":", away_score, away_team.name) home_team.kog += home_score away_team.kog += away_score away_team.koag += away_score def simulate_quarters(quarter_finals_teams): for home_team in quarter_finals_teams: print("=" * 50) print(home_team.name.upper() + "'S HOME GAME: ") print("=" * 50) for away_team in quarter_finals_teams: if home_team == away_team: pass if home_team != away_team: home_score, away_score = generate_random_score(home_team, away_team) print(home_team.name, home_score, ":", away_score, away_team.name) home_team.qfg += home_score away_team.qfg += away_score away_team.qfag += away_score def simulate_semis(semi_finals_teams): for home_team in semi_finals_teams: print("=" * 50) print(home_team.name.upper() + "'S HOME GAME: ") print("=" * 50) for away_team in semi_finals_teams: if home_team == away_team: pass if home_team != away_team: home_score, away_score = generate_random_score(home_team, away_team) print(home_team.name, home_score, ":", away_score, away_team.name) home_team.sfg += home_score away_team.sfg += away_score away_team.sfag += away_score def simulate_final(team_1, team_2): home_score, away_score = generate_random_score(team_1, team_2) print(team_1.name, home_score, ":", away_score, team_2.name) team_1.fg += home_score team_2.fg += away_score if team_1.fg == team_2.fg: penalty_shootout(team_1, team_2) if team_1.fg &gt; team_2.fg: print("=" * 50) print(team_1.name, "have won the UEFA Champions League") if team_2.fg &gt; team_1.fg: print("=" * 50) print(team_2.name, "have won the UEFA Champions League") def penalty_shootout(team_1, team_2): print("The game has ended with the scores level!\n") print("This means the game has gone to a penalty shootout!\n") input("Press enter to start the penalty shootout.\n") team_1.penalty += random.randint(1,1000) team_2.penalty += random.randint(1,1000) if team_1.penalty &gt; team_2.penalty: print(team_1.name, "have won the penalty shootout\n") print(team_1.name, "are the winners of the UEFA Champions League.") if team_1.penalty &lt; team_2.penalty: print(team_2.name, "have won the penalty shootout\n") print(team_2.name, "are the winners of the UEFA Champions League.") if team_1.penalty == team_2.penalty: team_1_decider = random.randint(1,1000) team_2_decider = random.randint(1,1000) if team_1_decider &gt; team_2_decider: print(team_1.name, "have won the penalty shootout\n") print(team_1.name, "are the winners of the UEFA Champions League.") if team_2_decider &gt; team_1_decider: print(team_1.name, "have won the penalty shootout\n") print(team_1.name, "are the winners of the UEFA Champions League.") if __name__ == "__main__": print("UEFA Champions League Simulator") print("Are you ready to play your very own UEFA Champions League?") input("Press the enter key to begin. \n") all_teams = [ Team("Chelsea", "Premier League", 87), Team("Liverpool", "Premier League", 91), Team("Manchester City", "Premier League", 106), Team("Barcelona", "La Liga", 138), Team("Bayern Munich", "Bundesliga", 128), Team("Juventus", "Serie A", 124), Team("PSG", "Ligue 1", 103), Team("Zenit", "Russian Premier League", 72), Team("Tottenham Hotspur", "Premier League", 78), Team("Real Madrid", "La Liga", 146), Team("Atletico Madrid", "La Liga", 127), Team("Valencia", "La Liga", 37), Team("Borussia Dortmund", "Bundesliga", 85), Team("Bayer Leverkusen", "Bundesliga", 61), Team("RB Leipzig", "Bundesliga", 22), Team("Napoli", "Serie A", 80.1), Team("Inter Milan", "Serie A", 31.1), Team("Atalanta", "Serie A", 14.945), Team("Olimpique Lyon", "Ligue 1", 61.5), Team("LOSC Lille", "Ligue 1", 11.699), Team("Locomotiv Moskva", "Russian Premier League", 28.5), Team("Shakhtar Donetsk", "Ukrainian Premier League", 80), Team("FC Red Bull Salzburg", "Austrian Bundesliga", 54.51), Team("Benfica", "Primeira Liga", 68), Team("K.R.C. Genk", "Belgian First Division", 25), Team("Galatasaray", "Super Lig", 22.5), Team("Ajax", "Eredivisie", 70.5), Team("Celtic", "Scottish Premiership", 31), Team("Porto", "Primeira Liga", 93), Team("Dynamo Kyiv", "Ukrainian Premier League", 65), Team("PAOK", "Super League Greece", 23.5), Team("Basel", "Swiss Super League", 54.5) ] skill_sorted_teams = sorted(all_teams, key=lambda t: t.skill, reverse=True) for team in all_teams[:8]: pot_1.append(team) for team in pot_1: allocated_teams.append(team) for team in skill_sorted_teams: if len(pot_2) &lt; 8 and team not in pot_1: pot_2.append(team) allocated_teams.append(team) for team in skill_sorted_teams: if len(pot_3) &lt; 8 and team not in allocated_teams: pot_3.append(team) allocated_teams.append(team) for team in skill_sorted_teams: if len(pot_4) &lt; 8 and team not in allocated_teams: pot_4.append(team) allocated_teams.append(team) print("First, pots will be arranged to complete the draw.") input("Press the enter key to see the pots.\n") print("\n") print("Pot 1:") print("=" * 40) for team in pot_1: print(team.name, "|", team.league, "|", team.skill) print("=" * 40) print("\n") print("Pot 2:") print("=" * 40) for team in pot_2: print(team.name, "|", team.league, "|", team.skill) print("=" * 40) print("\n") print("Pot 3:") print("=" * 40) for team in pot_3: print(team.name, "|", team.league, "|", team.skill) print("=" * 40) print("\n") print("Pot 4:") print("=" * 40) for team in pot_4: print(team.name, "|", team.league, "|", team.skill) print("=" * 40) print("\n") group_selection(group_a) group_selection(group_b) group_selection(group_c) group_selection(group_d) group_selection(group_e) group_selection(group_f) group_selection(group_g) group_selection(group_h) print("It's time to do the group stage draw.") input("Press the enter key to see the groups. \n") print("=" * 20) print("Group A:") print("=" * 20) for team in group_a: print(team.name) print("\n") print("=" * 20) print("Group B:") print("=" * 20) for team in group_b: print(team.name) print("\n") print("=" * 20) print("Group C:") print("=" * 20) for team in group_c: print(team.name) print("\n") print("=" * 20) print("Group D:") print("=" * 20) for team in group_d: print(team.name) print("\n") print("=" * 20) print("Group E:") print("=" * 20) for team in group_e: print(team.name) print("\n") print("=" * 20) print("Group F:") print("=" * 20) for team in group_f: print(team.name) print("\n") print("=" * 20) print("Group G:") print("=" * 20) for team in group_g: print(team.name) print("\n") print("=" * 20) print("Group H:") print("=" * 20) for team in group_h: print(team.name) print("=" * 20) print("\n") print("Now it's time to play the group stage matches.") input("Press the enter key to see the results.\n") for group in groups: simulate_league(group) print("\n") input("Press the enter key to see the standings.\n") sorted_group_a = sorted(group_a, key=lambda t: t.points, reverse=True) sorted_group_b = sorted(group_b, key=lambda t: t.points, reverse=True) sorted_group_c = sorted(group_c, key=lambda t: t.points, reverse=True) sorted_group_d = sorted(group_d, key=lambda t: t.points, reverse=True) sorted_group_e = sorted(group_e, key=lambda t: t.points, reverse=True) sorted_group_f = sorted(group_f, key=lambda t: t.points, reverse=True) sorted_group_g = sorted(group_g, key=lambda t: t.points, reverse=True) sorted_group_h = sorted(group_h, key=lambda t: t.points, reverse=True) sorted_groups = [sorted_group_a, sorted_group_b, sorted_group_c, sorted_group_d, sorted_group_e, sorted_group_f, sorted_group_g, sorted_group_h] for group in sorted_groups: print( "| {:&lt;20} | {:^4} | {:^3} | {:^3} | {:^3} | {:^4} | {:^4} | {:^6} |".format("CLUB", "MP", "W", "D", "L", "GF", "GA", "PTS")) for team in group: print("| {:&lt;20} | {:^4} | {:^3} | {:^3} | {:^3} | {:^4} | {:^4} | {:^6} |".format(team.name, team.mp, team.wins, team.draws, team.losses, team.gf, team.ga, team.points)) print("\n") input("Press the enter key to see which teams have made it through to the knockout stages of the competition.\n") for group in sorted_groups: qualified_for_knockouts.append(group[0]) qualified_for_knockouts.append(group[1]) for team in qualified_for_knockouts: print(team.name) print("\n") input("Press the enter key to see the results of the round of 16.\n") for match in match_teams: selection_1 = random.choice(qualified_for_knockouts) match.append(selection_1) qualified_for_knockouts.remove(selection_1) selection_2 = random.choice(qualified_for_knockouts) match.append(selection_2) qualified_for_knockouts.remove(selection_2) for matches in match_teams: simulate_knockout(matches) print("\n") for match in match_teams: if match[0].kog &gt; match[1].kog: qualified_quarter_finals.append(match[0]) elif match[0].kog &lt; match[1].kog: qualified_quarter_finals.append(match[1]) elif match[0].kog == match[1].kog: if match[0].koag &gt; match[1].koag: qualified_quarter_finals.append(match[0]) elif match[0].koag &lt; match[1].koag: qualified_quarter_finals.append(match[1]) else: winner = random.randint(0,1) qualified_quarter_finals.append(match[winner]) input("Press the enter key to see which teams have made it through to the quarter finals of the competition.\n") for team in qualified_quarter_finals: print(team.name) print("\n") for quarter_final in quarter_finals: selection_1 = random.choice(qualified_quarter_finals) quarter_final.append(selection_1) qualified_quarter_finals.remove(selection_1) selection_2 = random.choice(qualified_quarter_finals) quarter_final.append(selection_2) qualified_quarter_finals.remove(selection_2) input("Press the enter key to see the results of the quarter finals.\n") for quarter_final in quarter_finals: simulate_quarters(quarter_final) print("\n") for match in quarter_finals: if match[0].qfg &gt; match[1].qfg: qualified_semi_finals.append(match[0]) elif match[0].qfg &lt; match[1].qfg: qualified_semi_finals.append(match[1]) elif match[0].qfg == match[1].qfg: if match[0].qfag &gt; match[1].qfag: qualified_semi_finals.append(match[0]) elif match[0].qfag &lt; match[1].qfag: qualified_semi_finals.append(match[1]) else: winner = random.randint(0,1) qualified_semi_finals.append(match[winner]) input("Press the enter key to see which teams have made it through to the semi finals of the competition.\n") for team in qualified_semi_finals: print(team.name) print("\n") for semi_final in semi_finals: selection_1 = random.choice(qualified_semi_finals) semi_final.append(selection_1) qualified_semi_finals.remove(selection_1) selection_2 = random.choice(qualified_semi_finals) semi_final.append(selection_2) qualified_semi_finals.remove(selection_2) input("Press the enter key to see the results of the quarter finals.\n") for semi_final in semi_finals: simulate_semis(semi_final) print("\n") for match in semi_finals: if match[0].sfg &gt; match[1].sfg: qualified_final.append(match[0]) elif match[0].sfg &lt; match[1].sfg: qualified_final.append(match[1]) elif match[0].sfg == match[1].sfg: if match[0].sfag &gt; match[1].sfag: qualified_final.append(match[0]) elif match[0].sfag &lt; match[1].sfag: qualified_final.append(match[1]) else: winner = random.randint(0,1) qualified_final.append(match[winner]) input("Press the enter key to see which teams have made it through to the final of the competition.\n") for team in qualified_final: print(team.name) print("\n") print("Presenting the final of the UEFA Champions League.\n") print("="*50) print(qualified_final[0].name, "VS", qualified_final[1].name) print("="*50) print("\n") input("Press the enter key to see which team has won the Champions League.\n") simulate_final(qualified_final[0], qualified_final[1]) <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Don't shorten variable names. It's really annoying having to scroll back to the top of the page and read a comment to know what 'kog' or kohg' stands for. The interpreter doesn't care how long variable names are, but humans do.</p>\n\n<p>Use meaningful names. What the heck is <code>H_PARAMATER</code> and <code>A_PARAMATER</code>? \nMost of the time 1 letter variable names are also meaningless, such as <code>z</code>.</p>\n\n<p>Arrays are very useful. No need to have <code>group_a - group_h</code> or <code>pot_1 - pot_4</code> (whatever the heck <code>pot</code> means. This will be a maintenance nightmare.</p>\n\n<p>Your indentation is off in a couple places, such as here:</p>\n\n<pre><code>for group in sorted_groups:\n print(\n \"| {:&lt;20} | {:^4} | {:^3} | {:^3} | {:^3} | {:^4} | {:^4} | {:^6} |\".format(\"CLUB\", \"MP\", \"W\", \"D\",\n \"L\", \"GF\",\n \"GA\", \"PTS\"))\n for team in group:\n print(\"| {:&lt;20} | {:^4} | {:^3} | {:^3} | {:^3} | {:^4} | {:^4} | {:^6} |\".\n</code></pre>\n\n<p>Use method names that make sense. <code>penalty_shootout</code> isn't really a method name. All your methods also seem to be doing many things, I suggest creating more methods, each only doing 1 thing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T12:51:27.513", "Id": "226418", "ParentId": "226411", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T10:03:34.037", "Id": "226411", "Score": "-1", "Tags": [ "python", "python-3.x", "simulation" ], "Title": "Champions League Simulation" }
226411
<p>I have a code that calls many times a function returning a list of the dates between two dates formatted as </p> <blockquote> <p>('0001-01-01 00:01:00'),('0001-01-02 00:01:00'), ...</p> </blockquote> <p>The current solution is:</p> <pre><code>import numpy as np import time from datetime import datetime beg = datetime.strptime('01 01 0001', '%d %M %Y') #datetime end = datetime.strptime('01 01 2001', '%d %M %Y') def get_days(date1, date2): day_diff = (date1 - date2).days + 1 days = [str(start_date + dt.timedelta(d)) for d in range(day_diff)] dates = "('" + "'),('".join(days) + "')" return dates </code></pre> <p>Is there a faster way to achieve this?</p> <pre><code> #timing t0 = time.time() dates_list = get_days(beg, end) #feed datetime t1 = time.time() total_create = t1-t0 print("list comprehension: ", total_create,'s') </code></pre>
[]
[ { "body": "<p>With the list comprehension you are filling a whole list with your values, and then you are sending that list to <code>join</code>.</p>\n\n<p>Instead of a generating a list and then sending it, you can send a <strong>generator</strong> instead: similar to the list comprehension, but generates the values <em>on-demand</em>. With your old approach, if you had 10000 dates you would have them all at a list; with a generator it generates one at a time, so at least you will be consuming less memory.</p>\n\n<p>With a generator, you would directly do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>dates = \"('\" + \"'),('\".join(str(start_date + dt.timedelta(d)) for d in range(day_diff)) + \"')\"\n</code></pre>\n\n<p>On a side note, the parameter names <code>date1, date2</code> are not very explicit; it should be clear from the names which is the start and which is the end date. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T12:56:04.773", "Id": "226419", "ParentId": "226417", "Score": "3" } } ]
{ "AcceptedAnswerId": "226419", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T12:31:50.210", "Id": "226417", "Score": "3", "Tags": [ "python", "datetime", "formatting", "interval" ], "Title": "List of dates with special formatting" }
226417
<p>The question is:</p> <blockquote> <p>Write a program that prompts the user to input ten values between 80 and 85 and stores them in an array. Your program must be able to count the frequency of each value appears in the array.</p> </blockquote> <p>Is there any more efficient ways to present the count for frequency number between 80 to 85? Below is the sample code which had been done in the simplest ways to count the frequency for each number.</p> <p>The part which needs more efficient ways to present:</p> <pre class="lang-cpp prettyprint-override"><code> for(int i = 0; i &lt; inputSize; i++) { if(inputValue[i] == 80) { tempCount80++; } else if(inputValue[i] == 81) { tempCount81++; } else if(inputValue[i] == 82) { tempCount82++; } else if(inputValue[i] == 83) { tempCount83++; } else if(inputValue[i] == 84) { tempCount84++; } else if(inputValue[i] == 85) { tempCount85++; } else { cout &lt;&lt; "Error Accurs." &lt;&lt; endl; } } cout &lt;&lt; 80 &lt;&lt; " " &lt;&lt; tempCount80 &lt;&lt; endl; cout &lt;&lt; 81 &lt;&lt; " " &lt;&lt; tempCount81 &lt;&lt; endl; cout &lt;&lt; 82 &lt;&lt; " " &lt;&lt; tempCount82 &lt;&lt; endl; cout &lt;&lt; 83 &lt;&lt; " " &lt;&lt; tempCount83 &lt;&lt; endl; cout &lt;&lt; 84 &lt;&lt; " " &lt;&lt; tempCount84 &lt;&lt; endl; cout &lt;&lt; 85 &lt;&lt; " " &lt;&lt; tempCount85 &lt;&lt; endl; </code></pre> <p>The original code is: -</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; using namespace std; int main() { const int inputSize = 10; int inputValue[inputSize]; int tempCount80 = 0; int tempCount81 = 0; int tempCount82 = 0; int tempCount83 = 0; int tempCount84 = 0; int tempCount85 = 0; for(int i = 0; i &lt; inputSize; i++) { int tempValue = 0; cout &lt;&lt; "Please enter a number between 80 and 85: "; cin &gt;&gt; tempValue; if(tempValue &gt; 79 &amp;&amp; tempValue &lt; 86) { inputValue[i] = tempValue; } else { cout &lt;&lt; "The number must be between 80 and 85" &lt;&lt; endl; do { i--; break; } while(i &gt; 0); } } for(int i = 0; i &lt; inputSize; i++) { if(inputValue[i] == 80) { tempCount80++; } else if(inputValue[i] == 81) { tempCount81++; } else if(inputValue[i] == 82) { tempCount82++; } else if(inputValue[i] == 83) { tempCount83++; } else if(inputValue[i] == 84) { tempCount84++; } else if(inputValue[i] == 85) { tempCount85++; } else { cout &lt;&lt; "Error Accurs." &lt;&lt; endl; } } cout &lt;&lt; 80 &lt;&lt; " " &lt;&lt; tempCount80 &lt;&lt; endl; cout &lt;&lt; 81 &lt;&lt; " " &lt;&lt; tempCount81 &lt;&lt; endl; cout &lt;&lt; 82 &lt;&lt; " " &lt;&lt; tempCount82 &lt;&lt; endl; cout &lt;&lt; 83 &lt;&lt; " " &lt;&lt; tempCount83 &lt;&lt; endl; cout &lt;&lt; 84 &lt;&lt; " " &lt;&lt; tempCount84 &lt;&lt; endl; cout &lt;&lt; 85 &lt;&lt; " " &lt;&lt; tempCount85 &lt;&lt; endl; return 0; } </code></pre> <p>The output is as expected, but need to find more efficient ways to solve the question.</p>
[]
[ { "body": "<p><strong>Answer to the Performance Issue</strong><br>\nAnytime there are a list of variables named NAMEi where i is an integer, there is a strong chance that a container such as std::array or std::vector should be used. Sometimes using a table rather than multiple <code>if</code> statements can improve performance.</p>\n\n<p>Indexing into an array will prevent the repetitive code that is currently in the solution:</p>\n\n<pre><code>#include &lt;array&gt;\n\nint main()\n{\nconst int inputSize = 10;\nconst int frequencyCount = 6;\nstd::array&lt;int, inputSize&gt; inputValues;\nstd::array&lt;int, frequencyCount&gt; freqs;\n\n ...\n}\n</code></pre>\n\n<p>The array <code>freqs</code> will contain the frequency of the occurrence, there are a couple of ways to index into the array <code>freqs</code>. One would be to subtract 80 from the input value.</p>\n\n<p>This will reduce the multiple <code>if</code> statements into a simple increment of an item in an array. It will also reduce the amount of code necessary to print the frequencies.</p>\n\n<p>When performance is an issue, prefer \"\\n\" over <code>std::endl</code>. The use of <code>std::endl</code> flushes the output which may mean there is a system call for each use. A system call can add a great deal of time.</p>\n\n<p>Remove the <code>do/while</code> loop in the error checking.</p>\n\n<p><strong>Use the Container Classes Provided by C++</strong><br>\nThe code currently appears to be C rather than C++. It is using the old style C arrays, C++ supplies an <code>array</code> container class as part of the standard library. Using the <a href=\"http://www.cplusplus.com/reference/array/array/\" rel=\"noreferrer\">array</a> container class would allow you to use iterators instead of indexes, at least for printing. Here is a second <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"noreferrer\">reference</a>.</p>\n\n<p><strong>Avoid Using Namespace STD</strong><br>\nIf you are coding professionally you probably should get out of the habit of using the \"using namespace std;\" statement. The code will more clearly define where cout and other functions are coming from (std::cin, std::cout). 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 function cout you may override within your own classes. 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\n<p><strong>DRY Code</strong><br>\nThere is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code mutiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n\n<p><strong>Complexity</strong><br>\nThe function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n\n<p>There is also a programming principle called the Single Responsibility Principe that applies here. <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">The Single Responsibility Principle states</a>:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>There are at least 3 possible functions in <code>main()</code>.<br>\n - Get the user input<br>\n - Get process the frequencies<br>\n - Print the frequencies </p>\n\n<p><strong>Magic Numbers</strong><br>\nThere are Magic Numbers in the <code>main()</code> function (79 and 86), it might be better to create symbolic constants for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintainence easier.</p>\n\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T16:05:33.740", "Id": "226435", "ParentId": "226420", "Score": "15" } }, { "body": "<p><code>using namespace std;</code> <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">is a bad habit you should avoid</a>.</p>\n\n<hr>\n\n<p><strong>Input Handling:</strong></p>\n\n<pre><code>for(int i = 0; i &lt; inputSize; i++) {\n int tempValue = 0;\n cout &lt;&lt; \"Please enter a number between 80 and 85: \";\n cin &gt;&gt; tempValue;\n\n if(tempValue &gt; 79 &amp;&amp; tempValue &lt; 86) {\n inputValue[i] = tempValue;\n } else {\n cout &lt;&lt; \"The number must be between 80 and 85\" &lt;&lt; endl;\n do {\n i--;\n break;\n } while(i &gt; 0);\n }\n}\n</code></pre>\n\n<p>Although we want exactly <code>inputSize</code> inputs, we may have to request the input multiple times from the user. Doing this by decrementing <code>i</code> like that is quite inventive, but it's probably neater to use another loop to repeat the input request until we get a valid input:</p>\n\n<pre><code>for (int i = 0; i != inputSize; ++i) {\n\n int number = 0;\n\n while (true) {\n\n std::cout &lt;&lt; \"Please enter a number between 80 and 85: \";\n number = 0;\n std::cin &gt;&gt; number;\n\n if (number &gt;= 80 &amp;&amp; number &lt;= 85) {\n break;\n }\n else {\n std::cout &lt;&lt; \"The number must be between 80 and 85.\\n\";\n }\n }\n\n inputValue[i] = number;\n}\n</code></pre>\n\n<p>The inner loop could then be moved to a separate function, so the outer loop would simply look like:</p>\n\n<pre><code>for (int i = 0; i != inputSize; ++i) {\n inputValue[i] = getInput();\n}\n</code></pre>\n\n<p>Note that we should add error handling code to ensure that the user input is valid (e.g. what if the user enters \"abc\", or a number too large to fit in an <code>int</code>?). This is quite awkward in C++, but ends up looking something like this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;limits&gt;\n\nint getInput() {\n\n while (true) {\n\n std::cout &lt;&lt; \"Please enter a number between 80 and 85: \";\n\n int number = 0;\n std::cin &gt;&gt; number;\n\n std::cout &lt;&lt; \"\\n\";\n\n if (std::cin.eof()) {\n std::cout &lt;&lt; \"Unexpected end of file.\\n\";\n std::cin.clear();\n continue;\n }\n\n if (std::cin.bad() || std::cin.fail()) {\n std::cout &lt;&lt; \"Invalid input (error reading number).\\n\";\n std::cin.clear();\n std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\\n');\n continue;\n }\n\n if (number &lt; 80 || number &gt; 85) {\n std::cout &lt;&lt; \"Invalid input (number out of range).\\n\";\n continue;\n }\n\n return number;\n }\n\n // unreachable\n return 0;\n}\n\nint main() {\n\n int number = getInput();\n\n std::cout &lt;&lt; number &lt;&lt; std::endl;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Frequency count:</strong></p>\n\n<p>Rather than individual variables, we can use another array here. This removes a lot of the repetition. Something like:</p>\n\n<pre><code>const int freqSize = 6;\nint frequencies[freqSize] = { 0, 0, 0, 0, 0, 0 };\n\nfor (int i = 0; i != inputSize; ++i) {\n int binIndex = inputValue[i] - 80;\n\n assert(binIndex &gt;= 0 &amp;&amp; binIndex &lt; freqSize); // need #include &lt;cassert&gt;\n frequencies[binIndex] += 1;\n}\n\nfor (int i = 0; i != freqSize; ++i)\n std::cout &lt;&lt; (i + 80) &lt;&lt; \" \" &lt;&lt; frequencies[i] &lt;&lt; \"\\n\";\n</code></pre>\n\n<p>We should probably define our min (80) and max (85) values as constant variables somewhere, instead of using \"magic numbers\".</p>\n\n<hr>\n\n<p>Note that in \"real\" C++ code, we would probably use a data structure such as <code>std::map&lt;int, int&gt;</code> to store the count of each input value, and avoid using C-style arrays completely.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T19:15:50.527", "Id": "226451", "ParentId": "226420", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T13:04:22.237", "Id": "226420", "Score": "7", "Tags": [ "c++", "array", "homework" ], "Title": "Count the frequency of items in an array" }
226420
<p>I'm new in oop programming pattern. I created this simple User Class and i'm wondering if it : </p> <ul> <li>Is following oop rules and logic ?</li> <li>Is maintaibable ?</li> <li>Is can be tested without any problems ?</li> <li>Can be expanded to a large user class (permissions,etc) ?</li> <li>Is secure ?</li> </ul> <p>this is my class</p> <pre><code>&lt;?php class User { private $data; private $errors; public CONST FIELD_OPTION = [ 'user_login' =&gt; [ 'callback' =&gt; 'is_user_login_exists', 'error_message' =&gt; 'is already exists', 'response' =&gt; true ], 'user_email' =&gt; [ 'callback' =&gt; 'is_email_exists', 'error_message' =&gt; 'Email is already exists', 'response' =&gt; true ], 'user_pwd' =&gt; [ 'callback' =&gt; 'is_password_valid', 'error_message' =&gt; 'Password is not valid', 'response' =&gt; false ] ]; function __construct( array $data = [] ) { $this-&gt;dataParser( $data ); } /** * */ public function get( array $filters = [] ) { $db = db(); $query = $db-&gt;dsql()-&gt;table('users'); if(!empty($filters) &amp;&amp; is_array($filters)) { foreach($filters as $key) { try { $value = $this-&gt;getData($key, true); $query-&gt;where($key, $value); } catch(Exception $e) { $this-&gt;errors['data'][$key] = $e-&gt;getMessage(); } } } return $query-&gt;get(); } /** * Create new user */ public function create() { $db = db(); $data = [ 'user_pwd' =&gt; $this-&gt;getData('user_pwd'), 'user_login' =&gt; $this-&gt;getData('user_login'), 'user_email' =&gt; $this-&gt;getData('user_email'), 'user_name' =&gt; $this-&gt;getData('user_name') ]; $query = $db-&gt;dsql()-&gt;table('users')-&gt;set($data); $insert = $query-&gt;insert(); return $insert; } /** * Verifying all fields * * @param mixed(bool on failire|null on success) $fields */ public function vertify_fields( $requireds ) { if(is_string($requireds)) { $requireds = [$requireds]; } if(!is_array($requireds)) { return false; } $fields = self::FIELD_OPTION; foreach( $requireds as $field_name ) { $field = $fields[$field_name]; $value = $this-&gt;getData($field_name); if( empty($value) ) { $this-&gt;errors['fields'][$field_name] = 'This field is required'; continue; } if($field['response'] === call_user_func_array($field['callback'],[$value])) { $this-&gt;errors['fields'][$field_name] = $field['error_message']; } } } public function identify() { /** * We identify user by : * @string $user_login * @string $user_pwd */ $user_login = $this-&gt;getData('user_login'); $user_pwd = $this-&gt;getData('user_pwd'); $db = db(); $query = $db-&gt;dsql()-&gt;table('users')-&gt;where('user_login', $user_login)-&gt;limit(1); $user = $query-&gt;getRow(); if(!$user) { return false; } $user_pwd_hash = $user['user_pwd']; return password_verify($user_pwd, $user_pwd_hash); } /** * Return mixed(null|array) */ public function get_errors() { return $this-&gt;errors; } /** * check if @prop $errors is null or not */ public function have_errors() : bool { return ($this-&gt;errors === null) ? false : true; } /** * * @param mixed $key * @return string */ private function getData( $key, bool $force = false ) { $value = $this-&gt;data-&gt;$key ?? null; if( $force &amp;&amp; is_null($value) ) { throw new Exception($key . ' is missing'); } return $value; } private function dataParser( array $data ) : void { $this-&gt;data = (object) $data; } } </code></pre> <p>this is a example demonstrate how I'm using this class to create new users</p> <pre><code>function create_user_ajax() { $response = ['status' =&gt; 'error']; $User = new User($_POST); $User-&gt;vertify_fields(['user_email', 'user_login', 'user_pwd']); if($User-&gt;have_errors()) { $response['errors'] = $User-&gt;get_errors(); }else{ $User-&gt;create(); $response['status'] = 'success'; } echo json_encode($response); } </code></pre> <p>I appreciate any suggestion, improvement. thank you in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T21:55:50.840", "Id": "440092", "Score": "0", "body": "Your title seems to describe the concerns you have instead of what the script does. Please edit. Does `vertify_fields()` make the data non-horizontal?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T22:00:48.700", "Id": "440095", "Score": "0", "body": "@mickmackusa I'm not sure about what do you mean by non-horizontal" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T22:01:49.650", "Id": "440096", "Score": "0", "body": "...you have a typo in your method name, it should be _verify_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T22:04:48.980", "Id": "440098", "Score": "0", "body": "Yes it's verify if email exists, password valide,..." } ]
[ { "body": "<p>I can understand why no one has yet answered your question. The basic problem is that your User Class is not really an User Class. All it does is process user input, and that's not something an User Class should do. An User Class should deal with an user, nothing else. Things like:</p>\n\n<ul>\n<li>Changing user name and/or password.</li>\n<li>Verifying passwords.</li>\n<li>Keep information about an user.</li>\n<li>Keeping user information in the database up to date.</li>\n<li>permissions.</li>\n</ul>\n\n<p>Basically anything that has to do with the user <strong><em>once the user is known</em></strong>. The basic structure of an user class therefore should be:</p>\n\n<pre><code>class User {\n\n public function __construct($userId) {\n }\n\n}\n</code></pre>\n\n<p>Your code seems to be dealing with a login form. Your class therefore should be called something like: <code>LoginFormInput</code>. A good login <em>can result</em> in an User Class, but the processing of user input should not be done in the User Class itself. </p>\n\n<p>A good guide into designing a class, like this, is the <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">Model–view–controller (MVC) pattern</a>. It clearly separates input, internal logic, and output. </p>\n\n<p>Talking about user input processing. This should be done with care. How you deal with user input largely determines how secure your code is. Dumping all of <code>$_POST</code> directly into a class can be safe, if that class was intentionally designed to deal with it, but in most cases you want to filter user input at the top of a PHP script. In your case you could do something like:</p>\n\n<pre><code>&lt;?php\n\n$input[\"login\"] = filter_input(INPUT_POST, \"user_login\", FILTER_SANITIZE_STRING);\n$input[\"password\"] = filter_input(INPUT_POST, \"user_pwd\", FILTER_UNSAFE_RAW);\n$input[\"email\"] = filter_input(INPUT_POST, \"user_email\", FILTER_SANITIZE_EMAIL);\n$input[\"name\"] = filter_input(INPUT_POST, \"user_name\", FILTER_SANITIZE_STRING);\n</code></pre>\n\n<p>Only four inputs are now accepted, nothing else, and most of them are sanitized before they go into <code>$input</code>. Notice that I intentionally did not filter the password. This way any user password is possible. This filtering therefore doesn't make the content of <code>$input</code> safe, it is still user input and should be treated with care.</p>\n\n<p>I normally process each form in its own PHP script, specifically written for that form. The code above would be the start, and most of your User Class would form the rest of the code. The end result could be a valid <code>$userId</code> which can be stored in the session, and can be used to create an User object.</p>\n\n<p>One other thing in your code, that goes against everything I have learned, is the use of <code>call_user_func_array()</code> in <code>verify_fields()</code>. Just don't do that. It is bad for a lot of reasons, like maintainability and testability, but mostly because it is simply difficult to understand what it exactly does.</p>\n\n<p>Your error processing is also unclear. You use both exceptions and error responses. It is one or the other, not both.</p>\n\n<p>Also pay attention to the names you choose. I've already discussed the class name, but there's more. The obvious typo in <code>vertify_fields()</code>, a <code>dataParser()</code> method that doesn't do any parsing, and I still wonder what the differences between the <code>get()</code> and <code>getData()</code> methods are. I can't tell from the name.</p>\n\n<p>A class should be used to encapsulate the inner workings of whatever the class is dealing with. It should abstract away from the details and give you a clean interface. Your class doesn't do this. </p>\n\n<p>In the end I have to conclude that your class is probably syntactically correct, but that's about it. It seems like you haven't fully understood the reasons why we use OOP. </p>\n\n<p>There are lot's of tutorials on the internet. Some of them only explain the syntax, others explain how objects relate to each other, but there are very few that correctly explain how to use them effectively. I can't find one I really like. However, if you take them all together you will get the idea:</p>\n\n<p><a href=\"https://www.guru99.com/object-oriented-programming.html\" rel=\"nofollow noreferrer\">https://www.guru99.com/object-oriented-programming.html</a></p>\n\n<p><a href=\"https://code-boxx.com/simple-php-mvc-example\" rel=\"nofollow noreferrer\">https://code-boxx.com/simple-php-mvc-example</a></p>\n\n<p><a href=\"https://www.valuebound.com/resources/blog/object-oriented-programming-concepts-php-part-1\" rel=\"nofollow noreferrer\">https://www.valuebound.com/resources/blog/object-oriented-programming-concepts-php-part-1</a></p>\n\n<p><a href=\"https://www.studytonight.com/php/php-object-oriented-programming\" rel=\"nofollow noreferrer\">https://www.studytonight.com/php/php-object-oriented-programming</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T12:25:53.950", "Id": "440490", "Score": "0", "body": "thank you for your time and clarification. I really appreciate that.\n\nI'm using `call_user_func_array` to call a function !\nthe logic I use is that I loop through an array and every input have a function that check it validity. like user_email have function `is_email_exists`.\nin my opinion that calling fields one by one will make the code larger . On the contrary using this way we can store inputs configurations in separated array. and that make code more cleaner !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T13:48:03.397", "Id": "440500", "Score": "0", "body": "@MouradKaroudi I understand your reason for using `call_user_func_array()` but you asked whether your class is maintainable, testable, and follows common sense rules. This clearly doesn't. That's all that I'm saying." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T15:54:37.913", "Id": "440529", "Score": "0", "body": "Notice that `filter_input(INPUT_POST, \"user_email\", FILTER_SANITIZE_EMAIL);` will fail for emails like `a.valid.email@gmail.com`, which has dots on the *local-part*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T18:15:36.260", "Id": "440542", "Score": "0", "body": "@IsmaelMiguel You're talking about `FILTER_VALIDATE_EMAIL`, whereas I used `FILTER_SANITIZE_EMAIL`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T10:26:42.760", "Id": "226618", "ParentId": "226422", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T13:26:12.560", "Id": "226422", "Score": "2", "Tags": [ "beginner", "php", "object-oriented" ], "Title": "PHP User class usability,maintainability,secure" }
226422
<p>There is a <a href="https://codereview.stackexchange.com/questions/226774/bank-atm-mockup-app?noredirect=1#comment440984_226774">follow-up on this question</a>.</p> <p>I have created this bank ATM app mockup which I believe implement some Domain-Design Design layered architecture, repository pattern and uow pattern, if not fully. This app have 3 basic functions:</p> <ul> <li>Check balance</li> <li>Deposit</li> <li>Withdraw</li> </ul> <p>In my solution, I have these projects (layer):</p> <ul> <li>ATM.Model (Domain model entity layer)</li> <li>ATM.Persistence (Persistence Layer)</li> <li>ATM.ApplicationService (Application layer)</li> <li>ATM.ConsoleUICore (UI layer)</li> </ul> <p><strong>ATM.Model (Domain model entity layer)</strong></p> <pre><code>namespace ATM.Model { public class BankAccount { public int Id { get; set; } public string AccountName { get; set; } public decimal Balance { get; set; } public decimal CheckBalance() { return Balance; } public void Deposit(int amount) { // Domain logic Balance += amount; } public void Withdraw(int amount) { // Domain logic //if(amount &gt; Balance) //{ // throw new Exception("Withdraw amount exceed account balance."); //} Balance -= amount; } } } namespace ATM.Model { public class Transaction { public int Id { get; set; } public int BankAccountId { get; set; } public DateTime TransactionDateTime { get; set; } public TransactionType TransactionType { get; set; } public decimal Amount { get; set; } } public enum TransactionType { Deposit, Withdraw } } </code></pre> <p><strong>ATM.Persistence (Persistence Layer)</strong></p> <pre><code>namespace ATM.Persistence.Context { public class AppDbContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"[connstring]"); } public DbSet&lt;BankAccount&gt; BankAccounts { get; set; } public DbSet&lt;Transaction&gt; Transactions { get; set; } } } namespace ATM.Persistence.Repository { public class RepositoryBankAccount { public AppDbContext context { get; } public RepositoryBankAccount() { context = new AppDbContext(); } public BankAccount FindById(int bankAccountId) { return context.BankAccounts.Find(bankAccountId); } public void AddBankAccount(BankAccount account) { context.BankAccounts.Add(account); } public void UpdateBankAccount(BankAccount account) { context.Entry(account).State = EntityState.Modified; } } } namespace ATM.Persistence.Repository { public class RepositoryTransaction { private readonly AppDbContext context; public RepositoryTransaction() { context = new AppDbContext(); } public void AddTransaction(Transaction transaction) { context.Transactions.Add(transaction); } } } </code></pre> <p><strong>ATM.ApplicationService (Application layer)</strong></p> <pre><code>namespace ATM.ApplicationService { public class AccountService { private readonly UnitOfWork uow; public AccountService() { uow = new UnitOfWork(); } public void DepositAmount(BankAccount bankAccount, int amount) { bankAccount.Deposit(amount); uow.BankAccounts.UpdateBankAccount(bankAccount); var transaction = new Transaction() { BankAccountId = bankAccount.Id, Amount = amount, TransactionDateTime = DateTime.Now, TransactionType = TransactionType.Deposit }; uow.Transactions.AddTransaction(transaction); try { uow.Commit(); } catch { uow.Rollback(); } finally { uow.Dispose(); } } public void WithdrawAmount(BankAccount bankAccount, int amount) { bankAccount.Withdraw(amount); uow.BankAccounts.UpdateBankAccount(bankAccount); //repoBankAccount.UpdateBankAccount(bankAccount); var transaction = new Transaction() { BankAccountId = bankAccount.Id, Amount = amount, TransactionDateTime = DateTime.Now, TransactionType = TransactionType.Withdraw }; uow.Transactions.AddTransaction(transaction); try { uow.Commit(); } catch { uow.Rollback(); } finally { uow.Dispose(); } } public decimal CheckBalanceAmount(int bankAccountId) { BankAccount bankAccount = uow.BankAccounts.FindById(bankAccountId); return bankAccount.CheckBalance(); } } } </code></pre> <p><strong>ATM.ConsoleUICore (UI layer)</strong></p> <pre><code>namespace ATM.ConsoleUICore { class Program { static void Main() { AccountService accountService = new AccountService(); RepositoryBankAccount repoBankAccount = new RepositoryBankAccount(); var bankAccount = repoBankAccount.FindById(2); Console.WriteLine("1. Check balance"); Console.WriteLine("2. Deposit"); Console.WriteLine("3. Withdraw"); Console.WriteLine("Enter option: "); string opt = Console.ReadLine(); switch (opt) { case "1": Console.WriteLine($"Your balance is ${bankAccount.CheckBalance()}"); break; case "2": // User to input amount. // Data validation to make sure amount is greater than zero. // Pass the input amount to Application layer. accountService.DepositAmount(bankAccount, 50); // After getting the operation status from Application service layer. // Print operation status here: Either success or fail Console.WriteLine("Deposit successfully"); break; case "3": break; default: break; } } } } </code></pre> <p>What do you think of this mock-up in regards to Domain-Driven Design or layered architecture design and repository pattern and uow pattern point of view? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T14:29:39.667", "Id": "440028", "Score": "4", "body": "You haven't told us anything about your application. What features does it have? How do they work? Why have you separated it in these particular layers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T14:37:19.563", "Id": "440029", "Score": "0", "body": "It has few features like check balance, deposit and withdraw function. Just to see if I implement DDD, repository and uow pattern correctly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T16:13:31.553", "Id": "440049", "Score": "3", "body": "Rather than listing these functions in a response could you please add them to the top of the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T11:17:54.163", "Id": "440338", "Score": "0", "body": "Same [comment](https://stackoverflow.com/questions/57555384/database-data-is-not-updated-but-object-did-and-without-error#comment101612825_57555384) applies as that to your Stack Overflow question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T12:37:50.220", "Id": "440345", "Score": "0", "body": "What if one transaction fail and the other successful? That's why I use uow" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T14:46:36.730", "Id": "440371", "Score": "0", "body": "I did some read up. If I use another uow and repository layer, my orm is not tightly coupled. But doing so losses some ef feature." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T11:15:28.450", "Id": "440652", "Score": "1", "body": "Just wanted to point out DbContext is essentially a UOW class. From a DDD perspective shouldn't your `Deposit` and `Withdraw` methods new up a `Transaction`? Shouldn't all of the logic for what happens when a deposit/withdrawal is made be inside of the `BankAccount`? Another developer could come along call one of those methods and the `BankAccount` without creating a new `Transaction` and assume everything is correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T11:16:44.303", "Id": "440653", "Score": "1", "body": "You may want to also look at clean / hexagonal architecture instead of N-Tier and layering in the way you build things. Layering like this is a pretty much outdated way of development." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T13:42:28.453", "Id": "226423", "Score": "0", "Tags": [ "c#", "ddd", "entity-framework-core" ], "Title": "Bank ATM App Mockup - Implementing Domain-Driven Design (DDD)" }
226423
<p>So I've just written a framework that is supposed to make it easier to create a network-based application (client-server) using the native java.net package. I was wondering if the structure of my code is well understandable and if there are ways to improve my code (in both, readability and performance). I provided a UML-diagram to make it easier to gain a fast overview of the code I wrote:</p> <p><a href="https://i.stack.imgur.com/FTfMF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FTfMF.jpg" alt="enter image description here"></a></p> <p>And here is the source of the classes:</p> <p><strong>AbstractClient.java</strong></p> <pre><code>package com.joshuafeld.net; import java.io.IOException; import java.net.Socket; /** * A client can connect to a running server using native Java sockets. It can perform requests * and perform actions based on potential requests it can get from the server. */ public abstract class AbstractClient extends AbstractSocketWrapper { /** * Creates a new client with a socket that is connected to the specified port number on the * named host. * * &lt;p&gt;If the specified host is {@code null} it is the equivalent of specifying the address as * {@link java.net.InetAddress#getByName(String) InetAddress.getByName}{@code (null)}. In * other words, it is equivalent to specifying an address of the loopback interface. * * @param address The host name, or {@code null} for the loopback address. * @param port The port number. * * @throws IOException If an I/O error occurs when creating the underlying socket. */ public AbstractClient(final String address, final int port) throws IOException { super(new Socket(address, port)); new Thread(this).start(); } /** * This is just used to guarantee consistency in the client-server system. It calls the * method {@link #handleMessage(String) handleMessage} which then can be extended by a subclass. * This is created in the hope of making the system more understandable for a new user. * * @param message The message to handle. */ @Override /* default */ void handle(final String message) { handleMessage(message); } /** * Handles an incoming message from the server. * * @param message The incoming message. */ public abstract void handleMessage(String message); } </code></pre> <p><strong>AbstractServer.java</strong></p> <pre><code>package com.joshuafeld.net; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.LinkedList; import java.util.List; /** * A server that is based on the native Java sever socket implementation. A server waits for * requests to come in over the network. It performs some operation based on that request, and then * possibly returns a result to the requester. */ public abstract class AbstractServer { /** * Logs messages to the console. */ private static final Logger logger = LoggerFactory.getLogger(AbstractServer.class); /** * Waits for requests to come in over the network. */ private ServerSocket serverSocket; /** * The currently open socket connections. */ private final List&lt;ConnectionSocket&gt; sockets; /** * Creates a server with a server socket, bound to the specified port. A port number of * {@code 0} means that the port number is automatically allocated, typically from an ephemeral * port range. This port number can then be retrieved by calling {@link #getPort() getPort}. * * @param port The port number, or {@code 0} to use a port number that is * automatically allocated. * * @throws IllegalArgumentException If the port parameter is outside the specified range of * valid port values which is between 0 and 65535, inclusive. */ public AbstractServer(final int port) { if (port &lt; 0 || port &gt; 0xFFFF) { throw new IllegalArgumentException("Port value out of range: " + port); } sockets = new LinkedList&lt;&gt;(); try { serverSocket = new ServerSocket(port); } catch (final IOException exception) { logger.error("An I/O error occurred while opening the server socket", exception); } new Thread(new ConnectionAcceptor()).start(); } /** * Closes the server socket as well as all connected sockets. */ public void close() { try { serverSocket.close(); } catch (final IOException exception) { logger.error("An I/O error occurred while closing the server socket", exception); } sockets.forEach(this::close); } /** * Closes the specified socket and removes it from the list of currently connected sockets. * * @param socket The socket to close. */ public void close(final ConnectionSocket socket) { handleDisconnect(socket); sockets.remove(socket); socket.close(); } /** * Broadcasts a message to all connected sockets/clients. * * @param message The message to broadcast. */ public void broadcast(final String message) { sockets.forEach(socket -&gt; socket.send(message)); } /** * Handles an incoming message from the specified socket. * * @param socket The socket at which the message arrived. * @param message The message. */ public abstract void handleMessage(ConnectionSocket socket, String message); /** * Handles a newly connected socket. * * @param socket The newly connected socket. */ public abstract void handleConnect(ConnectionSocket socket); /** * Handles a disconnected/closed socket. * * @param socket The closed socket. */ public abstract void handleDisconnect(ConnectionSocket socket); /** * Returns the IP address to which the server socket is bound. * * &lt;p&gt;If the server socket was bound prior to being {@link #close() closed}, then this method * will continue to return the IP address after the server socket is closed. * * @return The IP address to which the server socket is bound. */ public String getAddress() { return serverSocket.getInetAddress().getHostAddress(); } /** * Returns the port number on which the server socket is listening. * * &lt;p&gt;If the server socket was bound prior to being {@link #close() closed}, then this method * will continue to return the port number after the server socket is closed. * * @return The port number on which the server socket is listening or -1 if the socket is not * bound yet. */ public int getPort() { return serverSocket.getLocalPort(); } /** * Listens for a connection to be made to the server socket and accepts it. */ private class ConnectionAcceptor implements Runnable { /** * Creates a new connection acceptor. */ private ConnectionAcceptor() { // empty on purpose } /** * Listens for a connection to be made to the server socket and accepts it. The method * blocks until a connection is made or the server is {@link #close() closed}. */ @Override public void run() { while (!serverSocket.isClosed()) { try { final ConnectionSocket socket = new ConnectionSocket(serverSocket.accept()); handleConnect(socket); new Thread(socket).start(); sockets.add(socket); } catch (final IOException exception) { logger.error("An I/O error occurred while waiting for a connection", exception); } } } } /** * The socket that represents the connection to a specific client. */ public class ConnectionSocket extends AbstractSocketWrapper { /** * Creates a new wrapped socket. The socket has to be connected already. * * @param socket The socket to wrap. */ public ConnectionSocket(final Socket socket) { super(socket); } /** * Passes the handling of the message on to the method * {@link #handleMessage(ConnectionSocket, String) handleMessage}. * * @param message The message to handle. */ @Override void handle(final String message) { handleMessage(this, message); } } } </code></pre> <p><strong>AbstractSocketWrapper.java</strong></p> <pre><code>package com.joshuafeld.net; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UncheckedIOException; import java.net.Socket; /** * A simple wrapper for the native Java {@link Socket Socket} that automatically handles messages * as soon as they are received by the underlying socket. */ public abstract class AbstractSocketWrapper implements Runnable { /** * Logs messages to the console. */ private static final Logger logger = LoggerFactory.getLogger(AbstractSocketWrapper.class); /** * The underlying socket/communication endpoint. */ private final Socket socket; /** * Reads incoming messages from the input stream. */ private BufferedReader input; /** * Writes messages to the output stream. */ private PrintWriter output; /** * Creates a new wrapped socket. The socket has to be connected already. * * @param socket The socket to wrap. */ public AbstractSocketWrapper(final Socket socket) { this.socket = socket; try { input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new PrintWriter(socket.getOutputStream(), true); } catch (final IOException exception) { logger.error("An I/O error occurred while creating the input/output stream or the " + "socket is not connected", exception); } } /** * Listens for new messages on the input stream and passes them on to the * {@link #handle(String) handle} method for further handling. */ @Override public void run() { while (!socket.isClosed()) { try { input.lines().forEach(this::handle); } catch (final UncheckedIOException exception) { // This will happen if the input stream is closed. Because this is natural behavior // and not really an error, we will just ignore this and not log it into the // console. break; } } } /** * Sends a message to the connected socket. The message is terminated by a newline. * * @param message The message to send. */ public void send(final String message) { if (!socket.isClosed()) { output.println(message); } } /** * Closes the socket as well as the input reader and output writer. * * &lt;p&gt;Once a socket has been closed, it is not available for further networking use (i.e. can't * be reconnected or rebound). A new socket needs to be created. */ public void close() { try { socket.close(); input.close(); } catch (final IOException exception) { logger.error("An I/O error occurred while closing the socket/input", exception); } output.close(); } /** * Handles a received message. * * @param message The message to handle. */ /* default */ abstract void handle(final String message); } </code></pre> <hr> <p>Example of a simple daytime server/client using this code:</p> <p><strong>DaytimeServer.java</strong></p> <pre><code>package com.joshuafeld.net.daytime; import com.joshuafeld.net.AbstractServer; import java.text.SimpleDateFormat; import java.util.Date; public class DaytimeServer extends AbstractServer { private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss"); public DaytimeServer() { super(13); } @Override public void handleConnect(final ConnectionSocket socket) { socket.send(DATE_FORMAT.format(new Date())); socket.close(); } @Override public void handleMessage(final ConnectionSocket socket, final String message) { // nothing to do here } @Override public void handleDisconnect(final ConnectionSocket socket) { // nothing to do here } public static void main(String[] args) { new DaytimeServer(); } } </code></pre> <p><strong>DaytimeClient.java</strong></p> <pre><code>package com.joshuafeld.net.daytime; import com.joshuafeld.net.AbstractClient; import java.io.IOException; public class DaytimeClient extends AbstractClient { public DaytimeClient(String address) throws IOException { super(address, 13); } @Override public void handleMessage(final String message) { System.out.println(message); close(); } public static void main(String[] args) throws IOException { new DaytimeClient("localhost"); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T14:09:08.293", "Id": "440025", "Score": "0", "body": "Do you happen to have a working client/server example of this abstract API?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T14:14:49.697", "Id": "440026", "Score": "1", "body": "@dfhwze Yes I have added it to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T17:16:45.060", "Id": "440054", "Score": "0", "body": "Accepting the first answer you get shortly after you get it tends to discourage further answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T01:19:00.980", "Id": "440112", "Score": "0", "body": "Thanks for the heads-up, I'm new to this site so I wasn't quite sure what to do." } ]
[ { "body": "<p><em>I read through your profile and saw you are a 17 year old developer hobbiest. I didn't know what OO was at that age. Well done. I made this review under the impression you were a somewhat experienced professional.</em></p>\n\n<h3>AbstractSocketWrapper</h3>\n\n<ul>\n<li>The constructor silently catches <code>IOException</code>. This leaves the socket in a corrupted state. Throw any exception up the stack to let higher level classes decide how to handle the corrupted socket connection.</li>\n<li>method <code>run</code> could abort at any time when the the socket gets closed gracefully <code>!socket.isClosed()</code> or otherwise: <code>UncheckedIOException</code>. But the container class does not get notified about this. Perhaps you should raise an event. If not, container classes should periodically check for lingering socket connections and close them.</li>\n<li>method <code>send</code> prints a friendly message (with a new line). This suggests to me the API can only be used for human readable messages, which limits its usability. The guard in this method is also not that useful. A disconnected socket should get disposed correctly, and the guard does not guarantee that the call will succeed.</li>\n<li>method <code>close</code> seems robust, however when <code>socket.close();</code> fails, <code>input.close();</code> does not get called, possibly leading to unwanted behavior (memory leak?).</li>\n</ul>\n\n<h3>ConnectionAcceptor</h3>\n\n<ul>\n<li>method <code>run</code> is ill-implemented. You perform <code>handleConnect(socket);</code> before <code>sockets.add(socket);</code>. And as you can see in your example server, a server can close the socket in <code>handleConnect</code>. This would mean a socket gets added even though it's already been closed.</li>\n</ul>\n\n<h3>AbstractServer</h3>\n\n<ul>\n<li>method <code>close</code> is not robust. If any socket fails to close <code>sockets.forEach(this::close);</code> others will not get closed, causing lingering socket connections.</li>\n<li>method <code>broadcast</code> has the same issue that failure in unicasting to a single client prevents other clients from being sent to.</li>\n</ul>\n\n<h3>General</h3>\n\n<ul>\n<li>Your API is not threadsafe. Consider using a locking mechanism when manipulating the list of connections in the server, and also when taking a snapshot of connections to send to.</li>\n<li>Your API should be made more robust against exceptions, and should check for lingering connections.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:20:31.763", "Id": "440035", "Score": "0", "body": "First of all, thank you very much for the detailed review. There is one thing I don't really understand: Why is it that if _\"any socket fails to close sockets.forEach(this::close); others will not get closed, causing lingering socket connections\"_? Shouldn't the for-each loop just continue and close the next one since no exception is thrown if closing a socket fails?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:32:11.577", "Id": "440038", "Score": "0", "body": "_output.close()_ might still throw an exception. And I suggested in my review that _close_ on _AbstractSocketWrapper_ should throw exceptions, so the server can handle them appropriately. It's my opinion that container classes should handle exceptions of classes they use (in most cases)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:40:56.943", "Id": "440040", "Score": "1", "body": "Ah alright I understand, thanks again!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T14:39:47.753", "Id": "226429", "ParentId": "226425", "Score": "2" } } ]
{ "AcceptedAnswerId": "226429", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T14:01:24.360", "Id": "226425", "Score": "3", "Tags": [ "java", "object-oriented", "socket", "server", "client" ], "Title": "Java Networking Framework" }
226425
<p>Let's assume that you need to filter customers based on 3 criteria:</p> <ul> <li>name</li> <li>tags assigned to customer</li> <li>customer's location</li> </ul> <p>For some reasons you have to do it directly in your program code, without database queries or PL/SQL for that matter.<br><br> Which of these two solutions do you find better in any terms? (e.g code readability, performance, cleanliness)</p> <p><strong>First example</strong></p> <pre><code>public List&lt;Customer&gt; filterStepbyStep(List&lt;Customer&gt; customers, String searchString, List&lt;Tag&gt; selectedTags, List&lt;LocationId&gt; selectedLocations) { List&lt;Customer&gt; filteredCustomers = new ArrayList&lt;Customer&gt;(customers); boolean searchStringNotEmpty = searchString != null &amp;&amp; !searchString.trim().isEmpty(); boolean locationsNotEmpty = selectedLocations != null &amp;&amp; selectedLocations.size() &gt; 0; boolean selectedTagsNotEmpty = selectedTags != null &amp;&amp; selectedTags.size() &gt; 0; filteredCustomers.removeIf(customer -&gt; { boolean valid = true; //searchString if (valid &amp;&amp; searchStringNotEmpty) { valid = customer.name.contains(searchString); } //locations if (valid &amp;&amp; locationsNotEmpty) { valid = selectedLocations.stream().anyMatch(locationId -&gt; locationId.equals(customer.locationId)); } //tags if (valid &amp;&amp; selectedTagsNotEmpty) { boolean tagValid = false; for (Tag selectedTag : selectedTags) { for (Tag customerTag : customer.getTags()) { if (selectedTag == customerTag) { tagValid = true; break; } } if (tagValid) { break; } } valid = tagValid; } return !valid; }); return filteredCustomers; } </code></pre> <p><strong>Second example</strong></p> <pre><code>public List&lt;Customer&gt; filterWithLambda(List&lt;Customer&gt; customers, String searchString, List&lt;Tag&gt; selectedTags, List&lt;LocationId&gt; selectedLocations) { List&lt;Customer&gt; filteredCustomers = new ArrayList&lt;Customer&gt;(customers); boolean searchStringNotEmpty = searchString != null &amp;&amp; !searchString.trim().isEmpty(); boolean locationsNotEmpty = selectedLocations != null &amp;&amp; selectedLocations.size() &gt; 0; boolean selectedTagsNotEmpty = selectedTags != null &amp;&amp; selectedTags.size() &gt; 0; filteredCustomers.removeIf(customer -&gt; { return (searchStringNotEmpty &amp;&amp; !customer.name.contains(searchString)) || (locationsNotEmpty &amp;&amp; !selectedLocations.stream().anyMatch(locationId -&gt; locationId.equals(customer.locationId))) || (selectedTagsNotEmpty &amp;&amp; !selectedTags.stream().anyMatch(selectedTag -&gt; customer.getTags().stream().anyMatch(customerTag -&gt; selectedTag == customerTag))); }); return filteredCustomers; } </code></pre> <p><br/> For me second example is more readable, I can immediately see that customer gets filtered out (removed) if any of 3 operands of OR operator is true.<br/> On the other hand repeating if(valid) for each property in first example does not seem too clean to me. I also find it tiresome and tedious to follow valid variable. Having this kind of state with valid variable is IMO error-prone. <br/> The only reason I can see, that one would prefer first example is not being familiar with lambda expressions.</p> <p>I've created small <a href="https://repl.it/@matvs/Filtering" rel="noreferrer">repl.it</a> to try these approaches out.</p> <p><em>If you can think of better way of doing this, than two above examples, then please feel free to post it here.</em></p>
[]
[ { "body": "<p>As far as which is easier to read, there isn't a clearly correct answer. The second is more shorter, but more cramped. I personally prefer code with a little more whitespace, such as the first example. Others prefer code that's more succinct. Which is more readable is probably a question to ask your coworkers.</p>\n\n<p>Marking variables as <code>final</code> will clue the reader in that they don't change once assigned.</p>\n\n<p>In camelCase, the method name should be <code>filterStepByStep</code>.</p>\n\n<p>Both methods use lambdas, so the name <code>filterWithLambda</code> is misleading.</p>\n\n<p>In recent versions of Java, you don't need to specify the type on the right hand side of a generic assignment. You can just use <code>&lt;&gt;</code>.</p>\n\n<p>You can get rid of 'valid' by returning <code>false</code> early.</p>\n\n<p>The equals check for locations can be cleaned up using <code>customer.locationId::equals</code>, or, better, by just using <code>contains</code>.</p>\n\n<p>The check on tags can be cleaned up using <code>Set</code> operations.</p>\n\n<p>I would consider renaming the variables to <code>matchCustomerName</code>, <code>matchLocation</code>, and <code>matchTags</code> to make the checks read more cleanly.</p>\n\n<p>If you were to make all these changes, your code might look more like:</p>\n\n<pre><code>public static List&lt;Customer&gt; filterStepByStep(\n final List&lt;Customer&gt; customers,\n final String searchString,\n final List&lt;Tag&gt; selectedTags,\n final List&lt;LocationId&gt; selectedLocations) {\n\n final List&lt;Customer&gt; filteredCustomers = new ArrayList&lt;&gt;(customers);\n final boolean matchCustomerName = searchString != null &amp;&amp; !searchString.trim().isEmpty();\n final boolean matchLocation = selectedLocations != null &amp;&amp; selectedLocations.size() &gt; 0;\n final boolean matchTags = selectedTags != null &amp;&amp; selectedTags.size() &gt; 0;\n\n\n filteredCustomers.removeIf(customer -&gt; {\n if (matchCustomerName &amp;&amp; !customer.name.contains(searchString)) {\n return true;\n }\n\n if (matchLocation &amp;&amp; !selectedLocations.contains(customer.locationId)) {\n return true;\n }\n\n if (matchTags) {\n final Set&lt;Tag&gt; matchedTags = new HashSet&lt;&gt;(selectedTags);\n matchedTags.retainAll(customer.getTags());\n return matchedTags.isEmpty();\n }\n\n return false;\n });\n\n return filteredCustomers;\n}\n\npublic List&lt;Customer&gt; filterWithLambda(\n final List&lt;Customer&gt; customers,\n final String searchString,\n final List&lt;Tag&gt; selectedTags,\n final List&lt;LocationId&gt; selectedLocations) {\n\n final List&lt;Customer&gt; filteredCustomers = new ArrayList&lt;&gt;(customers);\n final boolean matchCustomerName = searchString != null &amp;&amp; !searchString.trim().isEmpty();\n final boolean matchLocations = selectedLocations != null &amp;&amp; selectedLocations.size() &gt; 0;\n final boolean matchTags = selectedTags != null &amp;&amp; selectedTags.size() &gt; 0;\n\n filteredCustomers.removeIf(customer -&gt; {\n return (matchCustomerName &amp;&amp; !customer.name.contains(searchString))\n || (matchLocations &amp;&amp; !selectedLocations.contains(customer.locationId))\n || (matchTags &amp;&amp; !selectedTags.stream().anyMatch(customer.getTags()::contains));\n });\n\n return filteredCustomers;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T04:54:25.563", "Id": "440122", "Score": "0", "body": "+1 for using `Set<Tag>` to speed up `.contains`, but minus \\$O(N)\\$ for re-creating the set for each and every customer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T12:17:38.717", "Id": "440165", "Score": "0", "body": "@AjNeufeld retainAll is a destructive operation. It's easier to read, and there's no mention of this being a bottleneck, or of performance being relevant at all. I prefer to optimize for readability until there's a known bottleneck causing a problem. If that were the case, I agree your answer would run faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T13:22:22.260", "Id": "440176", "Score": "0", "body": "Oh, I understood what you were doing, and the need to use `.retainAll()` to do it. I’m more lamenting the JDK has `Set.containsAll()` but no `Set.containsAny()` which would turn your clean-but-destructive approach into just a clean approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T13:31:49.963", "Id": "440177", "Score": "0", "body": "@AJNeufeld Yeah, I don't usually miss that one, but on the rare occasion when I do, I *really* miss it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T19:35:10.250", "Id": "440255", "Score": "1", "body": "Eureka! You can miss `Set.containsAny()` no more! `!Collections.disjoint(c1, c2)` does the trick. If the collections contain any common items, they are not disjoint. The implementation contains a check to see if either `c1` or `c2` is a `Set`, and optimizes performance accordingly." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:43:32.373", "Id": "226433", "ParentId": "226426", "Score": "3" } }, { "body": "<p>Of #1 and #2, I prefer #2. But I actually dislike them both.</p>\n\n<p>For every customer, you are not only testing for the desired criteria, you are also testing the <code>searchStringNotEmpty</code>, <code>locationsNotEmpty</code> and <code>selectedTagsNotEmpty</code> flags. If you have 1,000,000 customers, that may be up to 3,000,000 tests of unchanging boolean variables.</p>\n\n<p>What you want is more like:</p>\n\n<pre><code>List&lt;Customer&gt; filteredCustomers = new ArrayList&lt;Customer&gt;(customers);\n\nif (searchStringNotEmpty)\n filterCustomers.retainIf(c -&gt; c.name.contains(searchString));\n\nif (locationsNotEmpty)\n filterCustomers.retainIf(c -&gt; locations.contains(c.locationId));\n\nif (selectedTagsNotEmpty)\n filterCustomers.retainIf(c -&gt; /* c contains any of the selectedTags */);\n</code></pre>\n\n<p>Instead of <code>searchStringNotEmpty</code> being tested once for each customer, it is tested once, and only if true is the filtering performed for the search string.</p>\n\n<p>Except ... if you have 1,000,000 customers, you may only want to pass through the list once, (to avoid cache thrashing) and the above will pass through the list up to 3 times. So let's fix that so we pass through the list once.</p>\n\n<h2>Dynamic Programming</h2>\n\n<p>What we want to do is write a program to <em>write a program</em> to filter the customers.</p>\n\n<p>Technically, we'll just be writing a program to assemble a program to filter the customers. Enter stream programming.</p>\n\n<pre><code>Stream&lt;Customer&gt; stream = customers.stream();\n\nif (searchStringNotEmpty)\n stream = stream.filter(c -&gt; c.name.contains(searchString));\n\nif (locationsNotEmpty)\n stream = stream.filter(c -&gt; locations.contains(c.locationId));\n\nif (selectedTagsNotEmpty)\n stream = stream.filter(c -&gt; /* c contains any of the selectedTags */);\n\nList&lt;Customer&gt; filteredCustomers = stream.collect(Collectors.toList());\n</code></pre>\n\n<p>We start with the stream of customers. If a search string is present, we add the appropriate filter to the stream, and store the resulting stream back in our <code>stream</code> variable. In the same way, we can add the other two filters. Once the stream pipeline has been configured, we perform the <code>collect()</code> terminal operation, which actually begins the stream processing, collecting all <code>Customer</code> objects which pass through the filters (if any) into a list.</p>\n\n<p><strong>Note</strong>: Perhaps you just want to return the resulting <code>stream</code> to the caller, instead of a <code>filteredCustomers</code> list, to allow the caller to do additional stream processing on the result. For instance, the caller might want to take the results and partition them into a map based on location, in which case first collecting the customers into a list is unnecessary step.</p>\n\n<h2>Predicates</h2>\n\n<p>As an alternative to building up a stream pipeline, with filters, you could build a complex <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/function/Predicate.html\" rel=\"nofollow noreferrer\"><code>Predicate</code></a> from individual predicates for the 3 filter conditions. The predicates would simply combine with <code>.and()</code> to form a larger predicate.</p>\n\n<pre><code>Predicate&lt;Customer&gt; filter = c -&gt; true;\n\nif (searchStringNotEmpty)\n filter = filter.and(c -&gt; c.name.contains(searchString));\n\nif (locationsNotEmpty)\n filter = filter.and(c -&gt; locations.contains(c.locationId));\n\nif (selectedTagsNotEmpty)\n filter = filter.and(c -&gt; /* c contains any of the selectedTags */);\n\nList&lt;Customer&gt; filteredCustomers = new ArrayList&lt;Customer&gt;(customers);\nfilteredCustomers.retainIf(filter);\n</code></pre>\n\n<p>You could avoid the extra <code>c -&gt; true</code> filter stage, by initializing <code>filter</code> to <code>null</code>, and then either assign to <code>filter</code>, or execute <code>filter = filter.and(...)</code> depending on whether <code>filter</code> is <code>null</code> or not at each step. At the end, simply don't call <code>.retainIf(filter)</code> if <code>filter</code> is still <code>null</code> at the end. That would be more efficient, but the above is easier to understand.</p>\n\n<h2>Optimizations</h2>\n\n<p>Both <code>selectedLocations</code> and <code>selectedTags</code> are lists. We can improve things by turning these each into a <code>Set</code> for faster <code>.contains()</code> testing.</p>\n\n<p>(Of course, this requires both <code>LocationId</code> and <code>Tag</code> to properly implement <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/Object.html#hashCode()\" rel=\"nofollow noreferrer\"><code>Object.hashCode()</code></a> in order to function properly.)</p>\n\n<p>(Unlike @EricStein's answer, these sets would be constructed once, not once per customer.)</p>\n\n<p>We can even do some other optimizations based on the sizes of these lists. A list of 1 can be handled much simpler, with <code>equals()</code> in the location case and a simple <code>.contains()</code> for the tag case.</p>\n\n<p>In the multiple tags case, <a href=\"https://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#disjoint%28java.util.Collection,%20java.util.Collection%29\" rel=\"nofollow noreferrer\"><code>Collections.disjoint()</code></a> can be used to to test for common tags.</p>\n\n<pre><code>Stream&lt;Customer&gt; stream = customers.stream();\n\nif (searchString != null &amp;&amp; !searchString.trim().isEmpty())\n stream = stream.filter(c -&gt; c.name.contains(searchString));\n\nif (selectedLocations != null &amp;&amp; selectedLocations.size() &gt; 0) {\n if (selectedLocations.size() == 1) {\n var location = locations.get(0);\n stream = stream.filter(c -&gt; location.equals(c.locationId));\n } else {\n var location_set = new HashSet&lt;&gt;(locations);\n stream = stream.filter(c -&gt; location_set.contains(c.locationId));\n }\n}\n\nif (selectedTags != null &amp;&amp; selectedTags.size() &gt; 0) {\n if (selectedTags.size() == 1) {\n var tag = selectedTags.get(0);\n stream = stream.filter(c -&gt; c.getTags().contains(tag));\n } else {\n var tag_set = new HashSet&lt;&gt;(selectedTags);\n stream = stream.filter(c -&gt; !Collections.disjoint(tag_set, c.getTags()));\n }\n}\n\nList&lt;Customer&gt; filteredCustomers = stream.collect(Collectors.toList());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T05:24:23.270", "Id": "440125", "Score": "0", "body": "Is there a performance difference between using _stream.filter_ more than once vs building a single _predicate_ with multiple _and_ concatenations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T13:09:02.117", "Id": "440174", "Score": "1", "body": "@dfhwze I’m sure there is a measurable difference, but I’m not sure which way the scale would fall. That would be an interesting comparative-review question." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T04:52:36.170", "Id": "226471", "ParentId": "226426", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T14:01:49.117", "Id": "226426", "Score": "6", "Tags": [ "java", "object-oriented", "comparative-review", "lambda" ], "Title": "Filtering a list of customers in Java based on three criteria" }
226426
<p>I have this function that takes a string which represents a html-color and returns the OLE value for it. If the string is null or empty or it can't be parsed, it uses a default value.<br> However I have to write that one line containing the default value twice and I don't see how I could remove this redundancy in the best possible way. </p> <p>I know this isn't a big deal but I am curious to see what you guys might suggest for this :)<br> What do you think is the best possible way to remove this redundancy?</p> <pre><code>private int GetOleFromHTML(string stringRep) { Color c; if (string.IsNullOrWhiteSpace(stringRep)) { c = Color.FromArgb(224, 224, 224); } else { try { c = ColorTranslator.FromHtml(stringRep); } catch { c = Color.FromArgb(224, 224, 224); } } return ColorTranslator.ToOle(c); } </code></pre>
[]
[ { "body": "<p>Since a method has to be executed to get this color, you cannot declare the color as constant. A <code>static readonly</code> field is what comes closest to a <code>const</code>.</p>\n\n<pre><code>private static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);\n\nprivate int GetOleFromHTML(string stringRep)\n{\n Color c;\n if (string.IsNullOrWhiteSpace(stringRep))\n {\n c = DefaultColor\n }\n else\n {\n try\n {\n c = ColorTranslator.FromHtml(stringRep);\n }\n catch\n {\n c = DefaultColor\n }\n }\n\n return ColorTranslator.ToOle(c);\n}\n</code></pre>\n\n<p>Another approach would be to directly store the OLE color as <code>int</code>.</p>\n\n<pre><code>const int DefaultOleColor = 14737632; // R=224, G=224, B=224\n\nprivate int GetOleFromHTML(string stringRep)\n{\n if (string.IsNullOrWhiteSpace(stringRep))\n {\n return DefaultOleColor;\n }\n try\n {\n return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));\n }\n catch\n {\n return DefaultOleColor;\n }\n}\n</code></pre>\n\n<p>Or calculated explicitly:</p>\n\n<pre><code>const int DefaultOleColor = 256 * (256 * 224 + 224) + 224;\n</code></pre>\n\n<p>Or with bit shift operations</p>\n\n<pre><code>const int DefaultOleColor = 224 &lt;&lt; 16 | 224 &lt;&lt; 8 | 224; // My preferred variant.\n</code></pre>\n\n<p>These expressions can be used to initialize the constant as they can be fully evaluated at compile time.</p>\n\n<p>You can test these variants easily in the Immediate Window of Visual Studio. You must qualify the names with the namespaces for the first variant (<code>System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(224, 224, 224))</code>). </p>\n\n<hr>\n\n<p>Avoiding repetition is not the only reason for having constants. Constant declarations give a name to otherwise \"magic\" values. See <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic number (programming)</a> (Wikipedia).</p>\n\n<p>This variant avoids the repetition by restructuring the code, but still uses a constant.</p>\n\n<pre><code>const int DefaultOleColor = 224 &lt;&lt; 16 | 224 &lt;&lt; 8 | 224;\n\nprivate int GetOleFromHTML(string stringRep)\n{\n if (!String.IsNullOrWhiteSpace(stringRep))\n {\n try\n {\n return ColorTranslator.ToOle(ColorTranslator.FromHtml(stringRep));\n }\n catch\n {\n }\n }\n return DefaultOleColor;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T14:57:50.103", "Id": "440031", "Score": "0", "body": "This answer keeps getting better with every edit :) You already have my vote. One question though: do you think the _catch_ could somehow be prevented?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:11:06.937", "Id": "440033", "Score": "1", "body": "Here you can see the Reference Source of the [ColorTranslator.FromHtml(String) Method](https://referencesource.microsoft.com/#System.Drawing/commonui/System/Drawing/Advanced/ColorTranslator.cs,228). It is quite complex as it accounts for different formats of HTML color. An attempt to avoid these exceptions would be at least as complex. Assuming the exceptions occur rarely, it is not worth the candle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:12:24.780", "Id": "440034", "Score": "0", "body": "Ah I was afraid it would be too complex. Thanks for this feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T16:42:39.557", "Id": "440225", "Score": "0", "body": "I really like the const-int solution. Since this is only used internally at a single point in a small program, I think I will go with this but I also have to give credit to [techbots answer](https://codereview.stackexchange.com/a/226437/203991) because I think if this method were in a library or in a bigger project where it is also used more, their approach seems more clean. Btw nice references and explanations." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T14:31:58.157", "Id": "226428", "ParentId": "226427", "Score": "5" } }, { "body": "<p>Another option, though not without caveats, is to reverse the logic. Something like this should work:</p>\n\n<pre><code>private int GetOleFromHTML(string stringRep)\n{\n Color c = Color.FromArgb(224, 224, 224);\n if (!string.IsNullOrWhiteSpace(stringRep))\n {\n try\n {\n c = ColorTranslator.FromHtml(stringRep);\n }\n catch\n {\n //Use default color value if the string is invalid.\n }\n }\n\n return ColorTranslator.ToOle(c);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T16:46:18.170", "Id": "440226", "Score": "0", "body": "Good idea. I also thought about this later on but didn't persue the idea because I thought maybe I'd be able to remove the redundancy without creating the default color before I even know if I have to use it or not. The const solution seems to be the middle-ground in this case." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T14:58:14.013", "Id": "226430", "ParentId": "226427", "Score": "5" } }, { "body": "<p>You have difficulties getting rid of the repeated code because you're trying to force two different operations into one:</p>\n\n<ul>\n<li>parsing html</li>\n<li>converting the result into <code>OLE</code> color</li>\n</ul>\n\n<p>Start with extracting the default value and make it a field:</p>\n\n<pre><code>static readonly Color DefaultColor = Color.FromArgb(224, 224, 224);\n</code></pre>\n\n<p>Then create the main API and give it a name that clearly communicates that it does. Now that the parsing has been extrated, you can as simple ternary operators here:</p>\n\n<pre><code>public Color ParseHtmlColorOrDefault(string value, Color defaultColor)\n{ \n return \n !string.IsNullOrWhiteSpace(value) &amp;&amp; TryParseHtmlColor(value, out var color)\n ? color\n : defaultColor;\n}\n</code></pre>\n\n<p>The parsing with its <code>try/catch</code> as the <code>TrySomething</code> pattern:</p>\n\n<pre><code>private static bool TryParseHtmlColor(string value, out Color color)\n{\n try\n { \n color = ColorTranslator.FromHtml(value);\n return true;\n }\n catch\n {\n color = Color.Empty;\n return false;\n }\n}\n</code></pre>\n\n<p>Finally, create an extension for the final step of converting <code>Color</code> to <code>OLE</code> color:</p>\n\n<pre><code>public static int ToOle(this Color color) =&gt; ColorTranslator.ToOle(color);\n</code></pre>\n\n<p>Use it like that:</p>\n\n<pre><code>var oleColor = ParseHtmlColorOrDefault(\"#FFAABB\", DefaultColor).ToOle();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T16:36:41.340", "Id": "440223", "Score": "1", "body": "Great points, thank you. Btw I don't really think you should have added the beginner tag to my question because I like to think that I know C# and I'm not _new_ to the language. I know that there are several ways this redudancy could be remove but I wanted to put this here so I could learn more about what more experienced people than me would consider as the _best_ solution for this (I'm by no means an expert). Also regarding your solution, since in my program this code is only used in one place and not publicly exposed, would you say it's okay to just use the const-int solution of Olivier?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T17:35:02.243", "Id": "440232", "Score": "0", "body": "@Joelius it was just my gut feeling, this time it was wrong ;-] I removed it... you could have to, it's ok to edit the tags. Sure, you can combine _the powers_ of all answers and build what works best for you. I just didn't want to repeat the other answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T17:46:24.523", "Id": "440237", "Score": "1", "body": "Alright, I'll accept [Oliviers answer](https://codereview.stackexchange.com/a/226428/203991) because I'm going to use something along the lines of his const-int solution. However, I have to give credit to all three answers, all very insightful, non repetitive and well written, thank you all :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T16:37:28.113", "Id": "226437", "ParentId": "226427", "Score": "5" } } ]
{ "AcceptedAnswerId": "226428", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T14:19:52.437", "Id": "226427", "Score": "7", "Tags": [ "c#", "converting" ], "Title": "Convert HTML color to OLE" }
226427
<p>I would like to make this code more efficient, I have isolated the problem as being these two for loops:</p> <pre><code> for i, device in enumerate(list_devices): for data_type_attr_name in data_types: result_list_element = { "device_reference": device.name, "device_name": "REF - " + device.name, "data_type": data_type_attr_name, "type": next( (data_type["type"] for data_type in DATA_TYPES if data_type["name"] == data_type_attr_name) ), "data_points": getattr(device, data_type_attr_name)( is_last_value=is_last_value, from_timestamp=from_timestamp, to_timestamp=to_timestamp, aggregate_period_name=aggregate_period_name, aggregate_operation_name=aggregate_operation_name, decimal_places=decimal_places, ), } if not isinstance(result_list_element["data_points"], list): raise TypeError("`data_points` must be returned as a list, even if it contains only one element.") result_list.append(result_list_element) return result_list </code></pre> <p><code>list_devices</code> is a list of Django model objects, <code>data_types</code> is a list of strings, each one representing a data type.</p> <p>Is there any way of losing one of the for loops while maintaining the same output?</p> <p>Thanks</p>
[]
[ { "body": "<p>Use <a href=\"https://docs.python.org/3.7/library/itertools.html#itertools.product\" rel=\"nofollow noreferrer\">itertools.product</a></p>\n\n<pre><code>import itertools\n\nfor device, data_type_attr_name in itertools.product(list_devices, data_types):\n result_list_element = {\n \"device_reference\": device.name,\n \"device_name\": \"REF - \" + device.name,\n \"data_type\": data_type_attr_name,\n \"type\": next((data_type[\"type\"] for data_type in DATA_TYPES if data_type[\"name\"] == data_type_attr_name)),\n \"data_points\": getattr(device, data_type_attr_name)(\n is_last_value=is_last_value,\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n aggregate_period_name=aggregate_period_name,\n aggregate_operation_name=aggregate_operation_name,\n decimal_places=decimal_places,\n ),\n }\n if not isinstance(result_list_element[\"data_points\"], list):\n raise TypeError(\"`data_points` must be returned as a list, even if it contains only one element.\")\n result_list.append(result_list_element)\nreturn result_list\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:37:53.380", "Id": "226432", "ParentId": "226431", "Score": "2" } }, { "body": "<p>Assume you are referring to speed, not conciseness when asking about efficiency. In which case reducing the amount of loops will not necessarily improve performance.</p>\n\n<pre><code>\"type\": next((data_type[\"type\"] for data_type in DATA_TYPES if data_type[\"name\"] == data_type_attr_name))\n</code></pre>\n\n<p>This can be improved so that you are not needing to go over <code>DATA_TYPES</code> looking for a matching name to <code>data_type_attr_name</code> every iteration. Instead you can make a reverse lookup dictionary once before the loop where <code>data_type[\"name\"]</code> is the key. </p>\n\n<p>Whenever you are searching through a list often, it can be very beneficial to create a dictionary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T22:28:46.597", "Id": "226464", "ParentId": "226431", "Score": "3" } } ]
{ "AcceptedAnswerId": "226432", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:26:14.100", "Id": "226431", "Score": "2", "Tags": [ "python", "performance", "django" ], "Title": "Optimising two for loops in Python" }
226431
<p>I recently solved the Knight Dialer problem but I'm not quite sure if I got the time complexity right; hence I'm requesting the following:</p> <p>1) Time and space complexity review and explanation on why so.</p> <p>The question says:</p> <blockquote> <p><em>Imagine you place a knight chess piece on a phone dial pad. This chess piece moves in an uppercase “L” shape: two steps horizontally followed by one vertically, or one step horizontally then two vertically: Pay no attention to the poorly-redacted star and pound keys Suppose you dial keys on the keypad using only hops a knight can make. Every time the knight lands on a key, we dial that key and make another hop. The starting position counts as being dialed. <strong>How many distinct numbers can you dial in N hops from a particular starting position?</em></strong></p> </blockquote> <p>Knight dialer: (movs map has all the possible movements for every number)</p> <pre><code>private static int knightDialer(int start, int nth, Map&lt;Integer, Integer[]&gt; movs, Set&lt;Integer&gt; res) { if (nth == 0) { return 0; } Integer[] validMoves = movs.get(start); for (Integer mov : validMoves) { if (!res.contains(mov)) { res.add(mov); knightDialer(mov, nth - 1, movs, res); } } return res.size(); } </code></pre> <p>If I'm missing something important for the review, please let me know.</p> <p>Thanks.</p> <hr> <p>Test Case:</p> <pre><code>public static void main(String[] args) { int start = 0; int nth = 3; System.out.println(knightDialer(start, nth)); System.out.println(); } private static int knightDialer(int start, int nth) { Map&lt;Integer, Integer[]&gt; movs = getAllMoves(); Set&lt;Integer&gt; res = new HashSet&lt;&gt;(); res.add(start); return knightDialer(start, nth, movs, res); } private static Map&lt;Integer, Integer[]&gt; getAllMoves() { Map&lt;Integer, Integer[]&gt; movs = new HashMap&lt;&gt;(); movs.put(1, new Integer[]{ 6, 8 }); movs.put(2, new Integer[]{ 7, 9 }); movs.put(3, new Integer[]{ 4, 8 }); movs.put(4, new Integer[]{ 3, 9, 0 }); movs.put(6, new Integer[]{ 1, 7, 0 }); movs.put(7, new Integer[]{ 2, 6 }); movs.put(8, new Integer[]{ 1, 3 }); movs.put(9, new Integer[]{ 2, 4 }); movs.put(0, new Integer[]{ 4, 6 }); return movs; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T16:07:10.653", "Id": "440047", "Score": "1", "body": "What are the two tasks, and do they have anything to do with each other? If not, please post them as two separate questions. Also add the [tag:java] language tag." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T16:13:03.477", "Id": "440048", "Score": "1", "body": "Will do. Then I'm going to ask another question for the ugly numbers and leave this solely for the knight dialer algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T21:52:50.030", "Id": "440091", "Score": "1", "body": "My reading of the problem statement would be to find out how many _sequences_ of digits of length `n` can be produced starting from any particular position. Can you clarify the intention of the code and explain how you've solved the problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T22:15:59.720", "Id": "440099", "Score": "0", "body": "The intention of the code is to count all possible moves (keys dialed) for n hops. If you start at 1, then you can hop to either 6 or 8, so we can count those hops (by adding them into the set) and decrement the value of n prior calling the recursive method. This would repeat until n == 0.\nThe general idea is to count how many keys can be dialed in n hops (start point being counted too). The loop is there because if you can make 2 different hops, that means 2 method calls, so the loop is going through the Integer[] and picking the values individually." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T09:56:52.457", "Id": "440145", "Score": "0", "body": "The \"test case\" doesn't actually seem to do any tests, except to verify that no exceptions are thrown. Did the source of the question include any test cases (input and expected output)? Like VisualMelon, I would expect that `161616` would be a valid 6-digit number. I would also interpret the question as asking how many (N+1)-digit numbers can be dialled, not how many numbers *up to* N+1 digits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T10:40:40.277", "Id": "440151", "Score": "0", "body": "The test case should execute the recursive method which solves the knight dialer problem. If you execute that main method, it should print an integer. The current specified case is 2 moves starting at zero. To test it, I just counted manually and then used the program to check if the output I got manually was right. The article is this: https://hackernoon.com/google-interview-questions-deconstructed-the-knights-dialer-f780d516f029. \nAs for my understanding since 161616 are not distinct numbers, from that sequence I'd just take 16 and ignore the rest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T10:51:50.173", "Id": "440152", "Score": "0", "body": "I might got the problem wrong and what I understood of \"distinct numbers\" is not what the problem meant, but still it's doing what I understand was needed, so it solves a problem. If that was the case, is that a problem to know what this snippet's time complexity is?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T13:50:15.733", "Id": "440180", "Score": "0", "body": "The article lists `6–1–6`, `6–7–6`, and `6–0–6` as valid three-digit sequences. (It also makes me worry about the ignorance of Google interviewers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:12:53.407", "Id": "440191", "Score": "0", "body": "I actually have both solutions: this one and one that counts unique sequences. The algorithm is pretty much the same. Still unsure on its times complexities though." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T15:47:09.527", "Id": "226434", "Score": "1", "Tags": [ "java", "algorithm", "programming-challenge" ], "Title": "Custom Knight dialer solution's time and space complexity" }
226434
<p>I'm using the matomo reports api to pull out some data in js. For some charts, I'm in the need to sort the array data based on inner property value ("val"), further to get only the 3 highest (Hong Kooong, Munich, Tokyo). Finally, this data should be used for the creation of a new key/val object (newObj).</p> <p>This is what my code looks like what does what it should. I would be interested if it can be optimized using es6 syntax.</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> let data = { 0 : {"label":"New York", "val": 20}, 1 : {"label":"Rio", "val": 10}, 3 : {"label":"Tokyo", "val": 50}, 4 : {"label":"Santiago", "val": 20}, 5 : {"label":"Hong Kooong", "val": 100}, 6 : {"label":"Munich", "val": 90}, } let compare = (a, b) =&gt; { let valA = a.val; let valB = b.val; let c = 0; if (valA &gt; valB) { c = 1; } else if (valA &lt; valB) { c = -1; } return c * -1; } let dataArray = Object.values(data).sort(compare) dataArray = dataArray.slice(0, 3) let newLabel = [] let newValue = [] Object.keys(dataArray).map(function(key, index) { newLabel.push(dataArray[index]['label']) newValue.push(dataArray[index]['val']) }); let newObj = {} newObj.data = {} newObj.data.labels = newLabel newObj.data.values = newValue console.log(newObj)</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Let's start with how I would have done 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>const data = {\n 0 : {\"label\":\"New York\", \"val\": 20},\n 1 : {\"label\":\"Rio\", \"val\": 10},\n 3 : {\"label\":\"Tokyo\", \"val\": 50},\n 4 : {\"label\":\"Santiago\", \"val\": 20},\n 5 : {\"label\":\"Hong Kooong\", \"val\": 100},\n 6 : {\"label\":\"Munich\", \"val\": 90},\n}\n\nconst result = Object.values(data)\n .sort((a, b) =&gt; b.val - a.val)\n .slice(0, 3)\n .reduce((c, v) =&gt; {\n c.data.labels.push(v.label)\n c.data.values.push(v.val)\n return c\n }, { data: { labels: [], values: []}})\n \nconsole.log(result)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Now onto your code:</p>\n\n<pre><code>let dataArray = Object.values(data).sort(compare)\ndataArray = dataArray.slice(0, 3)\n</code></pre>\n\n<p>You were off to a good start here. One minor nitpick is to just chain the operations since you're just reassigning <code>dataArray</code> with sort's results.</p>\n\n<pre><code>let newLabel = []\nlet newValue = []\nObject.keys(dataArray).map(function(key, index) {\n newLabel.push(dataArray[index]['label'])\n newValue.push(dataArray[index]['val'])\n});\n\nlet newObj = {}\nnewObj.data = {}\nnewObj.data.labels = newLabel\nnewObj.data.values = newValue\n</code></pre>\n\n<p>This is where it went crazy.</p>\n\n<p>Firstly, you used <code>Object.keys()</code> on <code>dataArray</code> (an array), which is not needed. If you need the array item index, all of the array methods provide the item index as second argument of the callback.</p>\n\n<p>Also, this is a bad use of <code>array.map()</code>. <code>array.map()</code> is used to transform values in one array to another array of values, i.e. a 1:1 transform operation. In this case, you're merely using it for looping, something better suited for <code>array.forEach()</code>.</p>\n\n<p>Since you're \"reducing\"/\"aggregating\" an array of values into one value (turning an array of values into an object), <code>array.reduce()</code> is the better option.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T06:48:57.277", "Id": "440128", "Score": "0", "body": "great answer. learned a lot, thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T16:42:43.243", "Id": "226439", "ParentId": "226436", "Score": "5" } }, { "body": "<p>Your <code>compare</code> function can be simplified a bit using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign\" rel=\"nofollow noreferrer\"><code>Math.sign</code></a>:</p>\n\n<pre><code>let compare = (a, b) =&gt; {\n return -Math.sign(a.val - b.val);\n}\n</code></pre>\n\n<p><code>sign</code> will return one of -1, 0, or 1, which correspond to the sign of the number passed to it. This is basically what you were doing manually. Most languages have a <code>sign</code> (or <code>signum</code>) function for cases like this.</p>\n\n<p>I also used a unary prefix <code>-</code> to negate instead of using <code>* -1</code>. As an alternative, you could change it to just:</p>\n\n<pre><code>let compare = (a, b) =&gt; {\n return Math.sign(b.val - a.val); // a and b were swapped\n}\n</code></pre>\n\n<p>Which will have the same effect. It depends on what looks more readable to you.</p>\n\n<hr>\n\n<p>I'll leave it off there as someone else went in depth.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T16:44:11.367", "Id": "226440", "ParentId": "226436", "Score": "4" } } ]
{ "AcceptedAnswerId": "226439", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T16:11:31.057", "Id": "226436", "Score": "3", "Tags": [ "javascript", "ecmascript-6" ], "Title": "Sort, slice and rebuild new object with array data" }
226436
<p>Building upon a recent question I answered here</p> <h3><a href="https://codereview.stackexchange.com/questions/225978/simple-middleware-pipeline-builder-similar-to-asp-net-core">Simple middleware pipeline builder (similar to asp.net-core)</a></h3> <p>I came across a cross site question</p> <h3>Stackoverflow: <a href="https://stackoverflow.com/questions/57558181/adding-middleware-in-carter-framework-makes-some-url-to-not-trigger">Adding middleware in Carter framework makes some URL to not trigger</a></h3> <p>which looked like it could benefit from what I had learned from the previous question.</p> <p>It is related to a GitHub library called <a href="https://github.com/CarterCommunity/Carter" rel="nofollow noreferrer">Carter</a></p> <blockquote> <p>Carter is a library that allows Nancy-esque routing for use with ASP.Net Core.</p> </blockquote> <p>The OP was hoping to be able to add tasks to the expected delegate for the middleware's <a href="https://github.com/CarterCommunity/Carter/blob/master/src/CarterOptions.cs" rel="nofollow noreferrer">CarterOptions</a> class.</p> <pre><code>/// &lt;summary&gt; /// Initializes &lt;see cref=&quot;CarterOptions&quot;/&gt; /// &lt;/summary&gt; /// &lt;param name=&quot;before&quot;&gt;A global before handler which is invoked before all routes&lt;/param&gt; /// &lt;param name=&quot;after&quot;&gt;A global after handler which is invoked after all routes&lt;/param&gt; /// &lt;param name=&quot;openApiOptions&quot;&gt;A &lt;see cref=&quot;OpenApiOptions&quot;/&gt; instance to configure OpenApi&lt;/param&gt; public CarterOptions(Func&lt;HttpContext, Task&lt;bool&gt;&gt; before = null, Func&lt;HttpContext, Task&gt; after = null, OpenApiOptions openApiOptions = null) { //... } </code></pre> <p>This is the before code where the options is created directly.</p> <pre><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env) { var options = new CarterOptions( before: ctx =&gt; { ctx.Request.Header[&quot;x-request-id&quot;] = Guid.NewGuid().ToString(); return this.BeforeLog(ctx); }, after: ctx =&gt; AfterLog(ctx) ); app.UseCarter(options); //... } </code></pre> <p>I came up with the following builder for the middleware's options class</p> <pre><code>sealed class CarterOptionsBuilder { delegate Task&lt;bool&gt; BeforeDelegate(HttpContext context); delegate Task AfterDelegate(HttpContext context); private readonly Stack&lt;Func&lt;BeforeDelegate, BeforeDelegate&gt;&gt; befores = new Stack&lt;Func&lt;BeforeDelegate, BeforeDelegate&gt;&gt;(); private readonly Stack&lt;Func&lt;AfterDelegate, AfterDelegate&gt;&gt; afters = new Stack&lt;Func&lt;AfterDelegate, AfterDelegate&gt;&gt;(); public CarterOptionsBuilder AddBeforeHook(Func&lt;HttpContext, Task&lt;bool&gt;&gt; handler) { befores.Push(next =&gt; async context =&gt; { return await handler(context) &amp;&amp; await next(context); }); return this; } public CarterOptionsBuilder AddAfterHook(Func&lt;HttpContext, Task&gt; handler) { afters.Push(next =&gt; context =&gt; { handler(context); return next(context); }); return this; } public CarterOptions Build(OpenApiOptions openApiOptions = null) { var before = new BeforeDelegate(c =&gt; Task.FromResult(true)); while (befores.Any()) { var current = befores.Pop(); before = current(before); } var after = new AfterDelegate(c =&gt; Task.CompletedTask); while (afters.Any()) { var current = afters.Pop(); after = current(after); } return new CarterOptions(before.Invoke, after.Invoke, openApiOptions); } } </code></pre> <p>Which allowed for functionality like</p> <pre><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env) { CarterOptions options = new CarterOptionsBuilder() .AddBeforeHook(this.AddRequestId) .AddBeforeHook(this.BeforeLog) .AddAfterHook(this.AfterLog) .Build(); app.UseCarter(options); } private Task AfterLog(HttpContext arg) { //... return Task.CompletedTask; } private Task&lt;bool&gt; BeforeLog(HttpContext arg) { //... return Task.FromResult(true); } private Task&lt;bool&gt; AddRequestId(HttpContext ctx) { ctx.Request.Header[&quot;x-request-id&quot;] = Guid.NewGuid().ToString(); return Task.FromResult(true); } </code></pre> <p>This does open extensibility for more customization like</p> <pre><code>public static CarterOptionsBuilder AddLog(this CarterOptionsBuilder builder) { return builder .AddBeforeHook(this.BeforeLog) .AddAfterHook(this.AfterLog); } private static Task AfterLog(HttpContext arg) { //... return Task.CompletedTask; } private static Task&lt;bool&gt; BeforeLog(HttpContext arg) { //... return Task.FromResult(true); } </code></pre> <p>Might consider contributing it as a pull-request to the repository.</p> <p>Is it even worth the trouble?</p> <p>Thoughts and opinions on the design, given the original feature request.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T18:00:38.787", "Id": "440060", "Score": "1", "body": "Cool, inspired by my question ;-) I think `HandleAfter` is incorrect. `after(context);` should be placed below `return next(context);`... if this means _after-a-request_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T18:02:25.333", "Id": "440062", "Score": "0", "body": "@t3chb0t in this case the delegate(s) is not after a request per say, but a desired action/task that is to be perform after a request." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T18:04:49.670", "Id": "440063", "Score": "0", "body": "ok, I guess then I need to take a look at that framework first as these concepts are new to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T18:05:13.397", "Id": "440064", "Score": "0", "body": "@t3chb0t it is technically two pipelines. one is invoked before request, the other after. But each pipeline acts like a normal pipeline." } ]
[ { "body": "<p>I still don't undestand that framework but there are few minor things that I think could be improved anyway:</p>\n\n<ul>\n<li><code>AddBeforeHook</code> &amp; <code>AddAfterHook</code> could actually use the <code>BeforeDelegate</code> &amp; <code>AfterDelegate</code> respectively instead of <code>Func</code>s.</li>\n<li>I would rename <code>handler</code> to <code>before</code> &amp; <code>after</code> since the third one is already called <code>next</code>. I find this way it would be clearer what they handle.</li>\n<li><p>I think you should be able to rewrite the <code>while</code>s in the <code>Build</code> method with an <code>Aggregate</code> like:</p>\n\n<pre><code>before = befores.Aggregate(before, (current, next) =&gt; next(current));\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>var before = befores.Aggregate(new BeforeDelegate(c =&gt; Task.FromResult(true)), (current, next) =&gt; next(current));\n</code></pre>\n\n<p>Elements are enumerated in the <code>Pop</code> order.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T18:36:43.113", "Id": "440544", "Score": "0", "body": "Like the aggregates idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T18:38:09.200", "Id": "440545", "Score": "0", "body": "Had them named previously before and after, but thought they caused confusion which to me was evident in your comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T18:46:24.460", "Id": "440546", "Score": "0", "body": "@Nkosi my comment was a sign of a lack of knowledge about how this framework works. I think to someone who knows the ins and outs of it, make `before` and `after` probably more sense than just `handler`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T18:19:44.440", "Id": "226644", "ParentId": "226443", "Score": "2" } } ]
{ "AcceptedAnswerId": "226644", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T17:49:40.427", "Id": "226443", "Score": "3", "Tags": [ "c#", "asp.net-core" ], "Title": "Sub-Middleware like options builder for an Asp.Net Core Middleware" }
226443
<p>I've decided to rebuild the code with advices from previous topic <a href="https://codereview.stackexchange.com/questions/226315/c-least-cost-swapping-2">C++ Least cost swapping 2</a> I've also decided to change input from passing the file name to passing the content of a file, so i am wondering if the input checking is still correct as in previous version. Please review my code.</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;cstdlib&gt; uint32_t constexpr MaxWeight = 6500; uint32_t constexpr MinVertexes = 2; uint32_t constexpr MaxVertexes = 1000000; struct ObjectCollection { size_t count = 0; std::vector&lt;uint32_t&gt; weights; std::vector&lt;size_t&gt; startingOrder; std::vector&lt;size_t&gt; endingOrder; uint32_t minWeight = MaxWeight; }; std::size_t readValue(std::istringstream&amp; iss) { std::size_t value; iss &gt;&gt; value; if (!iss) throw std::runtime_error("Invalid input."); return value; } std::istringstream readLine(std::istream&amp; stream) { std::string line; std::getline(stream , line); if (line.empty()) throw std::runtime_error("Invalid input"); return std::istringstream(line); } std::vector&lt;size_t&gt; readOrder(std::istringstream iss, size_t const objectCount) { std::vector&lt;size_t&gt; v; v.reserve(objectCount); int i = 1; while (!iss.eof() &amp;&amp; i &lt;= objectCount) { size_t orderNumber = readValue(iss); if (orderNumber - 1 &gt; objectCount) { throw std::runtime_error("Too high index in order"); } v.push_back(orderNumber - 1); ++i; } if (v.size() != objectCount) throw std::runtime_error("Too few values in line"); return v; } void readWeightsAndSetMinWeight(std::istringstream iss, ObjectCollection&amp; objects) { objects.weights.reserve(objects.count); int i = 1; while (!iss.eof() &amp;&amp; i &lt;= objects.count) { uint32_t weight = static_cast&lt;uint32_t&gt;(readValue(iss)); if (weight &gt; MaxWeight) { throw std::runtime_error("Too high weight"); } objects.weights.push_back(weight); objects.minWeight = std::min(objects.minWeight, weight); ++i; } if (objects.weights.size() != objects.count) throw std::runtime_error("Too few values in line"); } ObjectCollection readFromFile(std::istream&amp; stream) { ObjectCollection objects; if (!std::cin.good()) throw std::exception("Unable to read values"); readLine(stream) &gt;&gt; objects.count; if (objects.count&lt;MinVertexes || objects.count&gt;MaxVertexes) { throw std::exception("Invalid amount of vertexes"); } readWeightsAndSetMinWeight(readLine(stream), objects); objects.startingOrder = readOrder(readLine(stream), objects.count); objects.endingOrder = readOrder(readLine(stream), objects.count); return objects; } uint64_t calculateLowestCostOfWork(ObjectCollection const&amp; objects) { size_t n = objects.count; std::vector&lt;size_t&gt; permutation(n); //constructing permutation for (size_t i = 0; i &lt; n; ++i) { permutation[objects.endingOrder[i]] = objects.startingOrder[i]; } long long result = 0; std::vector&lt;bool&gt; visitedVertexes(n); for (int i = 0; i &lt; n; ++i) { if (visitedVertexes[i]) continue; size_t cycleSize = 0; uint32_t cycleMinWeight = MaxWeight; long long cycleSumOfWeights = 0; size_t vertexToVisit = i; //decomposition for simple cycles and calculating parameters for each cycle while (!visitedVertexes[vertexToVisit]) { visitedVertexes[vertexToVisit] = true; cycleSize++; vertexToVisit = permutation[vertexToVisit]; cycleSumOfWeights += objects.weights[vertexToVisit]; cycleMinWeight = std::min(cycleMinWeight, objects.weights[vertexToVisit]); } //calculating lowest cost for each cycle uint64_t swappingWithMinWeightInCycle = cycleSumOfWeights + (static_cast&lt;uint64_t&gt;(cycleSize) - 2) * static_cast&lt;uint64_t&gt;(cycleMinWeight); uint64_t swappingWithMinWeight = cycleSumOfWeights + cycleMinWeight + (static_cast&lt;uint64_t&gt;(cycleSize) + 1) * static_cast&lt;uint64_t&gt;(objects.minWeight); result += std::min(swappingWithMinWeightInCycle, swappingWithMinWeight); } return result; } int main() { ObjectCollection elephants; try { elephants = readFromFile(std::cin); std::cout &lt;&lt; calculateLowestCostOfWork(elephants); } catch (std::exception const&amp; ex) { std::cerr &lt;&lt; "Error: " &lt;&lt; ex.what() &lt;&lt; "\n"; return EXIT_FAILURE; } catch (...) { std::cerr &lt;&lt; "Error unknown \n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } </code></pre>
[]
[ { "body": "<p>Let's go through the code and see what can be improved.</p>\n<hr />\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;sstream&gt;\n#include &lt;stdexcept&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;cstdlib&gt;\n</code></pre>\n<p>The header names should sorted in alphabetical order.</p>\n<hr />\n<pre><code>uint32_t constexpr MaxWeight = 6500;\nuint32_t constexpr MinVertexes = 2;\nuint32_t constexpr MaxVertexes = 1000000;\n</code></pre>\n<p><code>constexpr</code> is usually put in the beginning because the benefits of east <code>const</code> don't really apply to <code>constexpr</code> — <code>constexpr</code> applies to the entire declaration, just like <code>static</code> or <code>inline</code> does. You can't declare a &quot;pointer to <code>constexpr</code>&quot; or &quot;reference to <code>constexpr</code>&quot; (the pointer / reference itself will be <code>constexpr</code> instead).</p>\n<p>Add <code>#include &lt;cstdint&gt;</code>, and use <code>std::uint32_t</code> instead of <code>uint32_t</code>. Also, since you manage to get rid of magic numbers, why not eliminate magic types as well? Something like</p>\n<pre><code>using Weight_t = std::uint32_t;\n</code></pre>\n<hr />\n<pre><code>struct ObjectCollection\n{\n size_t count = 0;\n std::vector&lt;uint32_t&gt; weights;\n std::vector&lt;size_t&gt; startingOrder;\n std::vector&lt;size_t&gt; endingOrder;\n uint32_t minWeight = MaxWeight;\n};\n</code></pre>\n<p>Again, <code>std::size_t</code> and <code>std::uint32_t</code>. Also, it seems that there is a class invariant that the three vectors are all of size <code>count</code>. You may want to ensure this.</p>\n<hr />\n<pre><code>std::size_t readValue(std::istringstream&amp; iss)\n{\n std::size_t value;\n iss &gt;&gt; value;\n if (!iss)\n throw std::runtime_error(&quot;Invalid input.&quot;);\n\n return value;\n}\n</code></pre>\n<p>This is overly restrictive, both in <code>std::size_t</code> and <code>std::istringstream</code>. Make it a template:</p>\n<pre><code>template &lt;typename T, typename Istream&gt;\nT read_value(Istream&amp;&amp; is)\n{\n T value;\n if (!(is &gt;&gt; value))\n throw std::runtime_error{&quot;invalid input&quot;};\n return value;\n}\n</code></pre>\n<hr />\n<pre><code>std::istringstream readLine(std::istream&amp; stream)\n{\n std::string line;\n std::getline(stream\n , line);\n if (line.empty()) throw std::runtime_error(&quot;Invalid input&quot;);\n return std::istringstream(line);\n}\n</code></pre>\n<p>This function should return a string, not a string stream, in my opinion. Also, why the line break in the <code>getline</code>?</p>\n<hr />\n<pre><code>std::vector&lt;size_t&gt; readOrder(std::istringstream iss, size_t const objectCount)\n{\n std::vector&lt;size_t&gt; v;\n v.reserve(objectCount);\n\n int i = 1;\n while (!iss.eof() &amp;&amp; i &lt;= objectCount)\n {\n size_t orderNumber = readValue(iss);\n if (orderNumber - 1 &gt; objectCount)\n {\n throw std::runtime_error(&quot;Too high index in order&quot;);\n }\n v.push_back(orderNumber - 1);\n ++i;\n }\n if (v.size() != objectCount) throw std::runtime_error(&quot;Too few values in line&quot;);\n return v;\n}\n</code></pre>\n<p>Don't take streams by value. Take by reference instead. And it doesn't make very much sense to declare a parameter as top-level <code>const</code>.</p>\n<p>The while loop should really be a for loop. Loop counters should start from 0 and use <code>&lt;</code> instead of starting from 1 and using <code>&lt;=</code>. Like this:</p>\n<pre><code>for (std::size_t i = 0; i &lt; objectCount; ++i) {\n // ...\n}\n</code></pre>\n<hr />\n<p>The <code>readWeightsAndSetMinWeight</code> function is similar. Casting the result of <code>readValue</code> to <code>uint32_t</code> doesn't feel right; with the template above, this problem is solved.</p>\n<hr />\n<p>It seems that you check the input status every time you read something, and throw an exception on failure. You can automate this by using <code>istream::exceptions</code>:</p>\n<pre><code>std::cin.exceptions(std::ios_base::failbit);\n</code></pre>\n<p><code>std::cin</code> will automatically throw exceptions of type <code>std::ios_base::failure</code> when <code>failbit</code> is on.</p>\n<hr />\n<p>This should be enough to get you started.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T22:40:09.307", "Id": "226465", "ParentId": "226444", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T18:01:24.847", "Id": "226444", "Score": "4", "Tags": [ "c++" ], "Title": "Least cost swapping 3" }
226444
<p>I have implemented <code>Token</code> and <code>FieldToken</code> classes as part of my <a href="https://github.com/m-peko/booleval" rel="nofollow noreferrer">project</a> and would like to hear some suggestions for improvement.</p> <p>First, <code>Token</code> class represents logical operators, relational operators, parentheses, etc. It does not hold a value, only type of the token (e.g. <code>AND</code>, <code>OR</code>, etc.). Here is its implementation:</p> <h1>Token.h</h1> <pre><code>class Token { public: enum class Type : uint8_t { UNKNOWN = 0, FIELD = 1, // Logical operators AND = 2, OR = 3, // Relational operators NEQ = 4, GT = 5, LT = 6, // Parentheses LP = 7, RP = 8 }; public: Token() noexcept; Token(Token&amp;&amp; other) = default; Token(Token const&amp; other) = default; Token(Type const type) noexcept; Token&amp; operator=(Token&amp;&amp; other) = default; Token&amp; operator=(Token const&amp; other) = default; bool operator==(Token const&amp; other) const noexcept; virtual ~Token() = default; virtual void type(Type const type) noexcept; Type type() const noexcept; bool is(Type const type) const noexcept; bool is_not(Type const type) const noexcept; bool is_one_of(Type const type1, Type const type2) const noexcept; template &lt;typename... Types&gt; bool is_one_of(Type const type1, Type const type2, Types const ... types) const noexcept; static std::unordered_map&lt;std::string, Type&gt; type_expressions() noexcept; private: Type type_; }; template &lt;typename... Types&gt; bool Token::is_one_of(Type const type1, Type const type2, Types const ... types) const noexcept { return is(type1) || is_one_of(type2, types...); } </code></pre> <h1>Token.cpp</h1> <pre><code>Token::Token() noexcept : type_(Type::UNKNOWN) {} Token::Token(Type const type) noexcept : type_(type) {} bool Token::operator==(Token const&amp; other) const noexcept { return type_ == other.type_; } void Token::type(Type const type) noexcept { type_ = type; } Token::Type Token::type() const noexcept { return type_; } bool Token::is(Type const type) const noexcept { return type_ == type; } bool Token::is_not(Type const type) const noexcept { return type_ != type; } bool Token::is_one_of(Type const type1, Type const type2) const noexcept { return is(type1) || is(type2); } std::unordered_map&lt;std::string, Token::Type&gt; Token::type_expressions() noexcept { static std::unordered_map&lt;std::string, Type&gt; type_expressions = { { "and", Type::AND }, { "&amp;&amp;" , Type::AND }, { "or" , Type::OR }, { "||" , Type::OR }, { "neq", Type::NEQ }, { "!=" , Type::NEQ }, { "greater", Type::GT }, { "&gt;", Type::GT }, { "less", Type::LT }, { "&lt;", Type::LT }, { "(", Type::LP }, { ")", Type::RP } }; return type_expressions; } </code></pre> <p>Now, <code>FieldToken</code> class represents all other tokens, usually strings whose value I need to know. Therefore, I derived <code>Token</code> class to preserve all the functionality and added field value as a new data member.</p> <h1>FieldToken.h</h1> <pre><code>template &lt;typename FieldType = std::string&gt; class FieldToken : public Token { public: FieldToken() noexcept; FieldToken(FieldToken&amp;&amp; other) = default; FieldToken(FieldToken const&amp; other) = default; FieldToken(FieldType const&amp; field) noexcept; FieldToken&amp; operator=(FieldToken&amp;&amp; other) = default; FieldToken&amp; operator=(FieldToken const&amp; other) = default; bool operator==(FieldToken const&amp; other) const noexcept; virtual ~FieldToken() = default; void type(Type const type) noexcept override; void field(FieldType const&amp; field) noexcept; FieldType const&amp; field() const noexcept; private: template &lt;typename T&gt; void ignore(T&amp;&amp;); private: FieldType field_; }; template &lt;typename FieldType&gt; FieldToken&lt;FieldType&gt;::FieldToken() noexcept : Token(Token::Type::FIELD), field_{} {} template &lt;typename FieldType&gt; FieldToken&lt;FieldType&gt;::FieldToken(FieldType const&amp; field) noexcept : Token(Token::Type::FIELD), field_(field) {} template &lt;typename FieldType&gt; void FieldToken&lt;FieldType&gt;::type(Type const type) noexcept { ignore(type); Token::type(Token::Type::FIELD); } template &lt;typename FieldType&gt; void FieldToken&lt;FieldType&gt;::field(FieldType const&amp; field) noexcept { field_ = field; } template &lt;typename FieldType&gt; FieldType const&amp; FieldToken&lt;FieldType&gt;::field() const noexcept { return field_; } template &lt;typename FieldType&gt; template &lt;typename T&gt; void FieldToken&lt;FieldType&gt;::ignore(T&amp;&amp;) {} </code></pre> <p>What do you think? Any implementation or logical suggestions are welcomed...</p>
[]
[ { "body": "<h1>Make <code>type_expressions</code> a const member variable</h1>\n\n<p>Why have a function returning a <code>std::unordered_map&lt;&gt;</code> with constant data, if you can just as well declare this map directly as a member variable? Declare this in the header file:</p>\n\n<pre><code>class Token {\n ...\npublic:\n static const std::unordered_map&lt;std::string, Type&gt; type_expressions;\n ...\n};\n</code></pre>\n\n<p>And the following in the implementation file:</p>\n\n<pre><code>const std::unordered_map&lt;std::string, Type&gt; Token::type_expressions = {\n {\"and\", Type::AND},\n ...\n};\n</code></pre>\n\n<h1>Consider having <code>Token</code> just be a <code>class enum</code></h1>\n\n<p>Your class <code>Token</code> is not very generic. It works like an <code>enum</code>, with just two differences: it has a <code>is_one_of()</code> convenience function, and there's a map from strings to <code>Type</code>. But it has a hardcoded set of <code>Types</code>. I recommend just doing:</p>\n\n<pre><code>enum class Token: uint8_t {\n UNKNOWN,\n FIELD,\n ...\n};\n</code></pre>\n\n<p>Have the map from strings to types just be a non-class variable, and defining <code>is_one_of()</code> as a generic function that can compare any set of things:</p>\n\n<pre><code>template&lt;typename T, typename... Ts&gt;\nbool is_one_of(T const value, T const value1, Ts const ... values) {\n return value == value1 || is_one_of(value, values...);\n}\n\ntemplate&lt;typename T&gt;\nbool is_one_of(T const value, T const value1) {\n return value == value1;\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T16:45:58.027", "Id": "440734", "Score": "0", "body": "Is your is_one_of template right? https://ideone.com/PZ5kT1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T17:42:04.487", "Id": "440743", "Score": "0", "body": "@nomanpouigt No it's not, I always forget you can't have a variable number of arguments with the same type this way." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T19:47:18.243", "Id": "226519", "ParentId": "226445", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T18:13:13.827", "Id": "226445", "Score": "2", "Tags": [ "c++", "c++11" ], "Title": "Token class implementation" }
226445
<p>I have rewritten my python code in cython in order to speed up it quite a bit. However after checking the code in jupyter it seems that part of it is still compiled as python code, therefore its not being sped up enough.</p> <p>My function is pretty basic, it gets start date, end date and creates array of additional dates based on that and some other conditions.</p> <p>The thing is I’m a bit clueless how could I change the highlighted yellow part of code of the <code>date_range_np</code> function as seen on the attached imaged. Because I’m already using numpy arrays so I thought it would be compiled as cython code. There is also one loop that I think is slowing down the function but so far I wasn’t able to come up with any replacement that sginificatly sped up the function. Actually speed is very important as those functions are executed thousands of times. Any ideas how could I refactor it to speed it up?</p> <p>Here is my code:</p> <pre><code>%%cython -a import numpy as np cimport numpy as np from datetime import datetime cpdef np.int64_t get_days(np.int64_t year, np.int64_t month): cdef np.ndarray months=np.array([31,28,31,30,31,30,31,31,30,31,30,31]) if month==2: if (year%4==0 and year%100!=0) or (year%400==0): return 29 return months[month-1] cpdef np.ndarray[np.int64_t] date_range_np(np.int64_t start, np.int64_t end, char* freq): cdef np.ndarray res cdef np.int64_t m_start cdef np.int64_t m_end if freq.decode("utf-8")[len(freq)-1] == "M": m_start = np.int64(start).astype('M8[D]').astype('M8[M]').view("int64") m_end = np.int64(end).astype('M8[D]').astype('M8[M]').view("int64") res = np.arange(m_start, m_end-2, np.int64(freq[:(len(freq)-1)])).view("M8[M]").astype("M8[D]").view("int64") return np.array([np.min([x+datetime.fromtimestamp(start*24*60*60).day-1, x+get_days(datetime.fromtimestamp(start*24*60*60).year,datetime.fromtimestamp(start*24*60*60).month)]) for x in res]) elif freq.decode("utf-8")[len(freq)-1] == "D": return np.arange(start, end-2, np.int64(freq[:(len(freq)-1)])) cpdef np.ndarray[np.int64_t] loanDates(np.int64_t startDate,np.int64_t endDate,np.int64_t freq): # if frequency indicates repayment every n months if int(12 / freq) == 12 / freq: # Generate date range and add offset depending on starting day #print(date_range_np(start=startDate, end=endDate, freq=(str(-int(12 / freq)) + "M").encode("utf8"))) ts = date_range_np(start=startDate, end=endDate, freq=(str(-int(12 / freq)) + "M").encode("utf8")) else: ts = date_range_np(start=startDate, end=endDate, freq=(str(-int(365 / freq)) + "D").enocode("utf8")) #print(ts) if ts.shape[0] == 0: return np.array([]) elif ts.shape[0] &gt;= 1 and ts[0] &gt; startDate: ts = np.delete(arr=ts, obj=0) if ts[ts.shape[0]-1] &lt; endDate: ts = np.delete(arr=ts, obj=-1) if ts[0] != startDate: ts = np.insert(ts,0,startDate) # If no dates generated (start date&gt;end date) ts = ts # If last date generated is not end date add it return ts.astype('int64') </code></pre> <p>And the function highlighted:</p> <p><a href="https://i.stack.imgur.com/kK69j.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kK69j.jpg" alt="bottleneck function"></a></p> <p>If you want to test the functions you can try:</p> <pre><code>%timeit date_range_np(20809,17986, b"-1M") </code></pre> <p>I get about 1ms for that function.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T18:55:57.013", "Id": "440068", "Score": "1", "body": "How does your function compare to [`pandas.date_range`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.date_range.html)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T05:26:27.820", "Id": "440126", "Score": "1", "body": "I used it before and it was slower" } ]
[ { "body": "<p>I'm sorry, but this code is <em>really</em> hard to read. I must admit I don't know Cython too well, so I won't be able to comment too much on that part. But anyways, here are a few comments, in random order.</p>\n\n<ul>\n<li><p>While <a href=\"https://cython.readthedocs.io/en/latest/src/userguide/special_methods.html#docstrings\" rel=\"nofollow noreferrer\">Cython does not fully support docstrings</a> (they do not show up in the interactive <code>help</code>), this should not prevent you from adding some to explain what the different functions do and what arguments they take.</p></li>\n<li><p>You seem to be doing <code>np.int64(start).astype('M8[D]').astype('M8[M]').view(\"int64\")</code> quite a lot. As far as I can tell, this extracts the month from a date, which was given as an integer(?). There is quite possibly a better way to do that (using the functions in <code>datetime</code>), but they might be slower. Nevertheless, you should put this into its own function.</p></li>\n<li><p>You do <code>freq.decode(\"utf-8\")[len(freq)-1]</code> twice. Do it once and save it to a variable. Also, <code>freq[len(freq)-1]</code> should be the same as <code>freq[-1]</code> and <code>freq[:len(freq)-1]</code> the same as <code>freq[:-1]</code>. This is especially costly <a href=\"https://cython.readthedocs.io/en/latest/src/tutorial/strings.html#general-notes-about-c-strings\" rel=\"nofollow noreferrer\">as <code>len(freq)</code> is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> for <code>char *, in Cython</code></a>.</p></li>\n<li><p>You create <code>datetime.fromtimestamp(start*24*60*60)</code> three times, once each to get the day, month and year. Save it to a variable and reuse it.</p></li>\n<li><p>The last two comments in <code>loanDates</code> seem not to be true anymore:</p>\n\n<pre><code># If no dates generated (start date&gt;end date)\nts = ts\n\n# If last date generated is not end date add it\nreturn ts.astype('int64')\n</code></pre></li>\n<li><a href=\"https://cython.readthedocs.io/en/latest/src/tutorial/strings.html#general-notes-about-c-strings\" rel=\"nofollow noreferrer\">The documentation seems to recommend against using C strings</a>, unless you really need them. If I read the documentation correctly you could just make the type of <code>freq</code> <code>str</code> and get rid of all your <code>encode(\"utf-8\")</code> and <code>decode(\"utf-8\")</code> code.</li>\n<li><p>The definition of the <code>months</code> array is done every time the function <code>get_days</code> is called. In normal Python I would recommend making it a global constant, here you would have to try and see if it makes the runtime worse.</p></li>\n<li><p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. Since Cython is only an extension, it presumably also applies here. It recommends surrounding operators with whitespace (<code>freq[len(freq) - 1]</code>), using <code>lower_case</code> for all function and variable names and limiting your linelength (to 80 characters by default, but 120 is also an acceptable choice).</p></li>\n</ul>\n\n<p>In the end, taking 1ms to create a date range is already quite fast. As you said this is already faster than <code>pandas.daterange</code> (which does a lot of parsing of the input first, which you avoid by passing in numbers directly). You might be able to push it down to microseconds, but you should ask yourself if and why you need this many dateranges per second.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T17:35:04.547", "Id": "440233", "Score": "1", "body": "Thanks for the reply. Are the points 2 and 4 suggested to save time or more to make the code more readable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T17:42:27.383", "Id": "440235", "Score": "0", "body": "@AlexT Both! Although there is a small function overhead, it will probably be less than doing the computation twice (especially since it involves multiple attribute lookups). But when in doubt, measure it!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T09:20:37.777", "Id": "226480", "ParentId": "226447", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T18:24:18.450", "Id": "226447", "Score": "4", "Tags": [ "python", "performance", "datetime", "numpy", "cython" ], "Title": "Cython functions for generating NumPy date ranges" }
226447
<p>I recently reviewed a question here on Code Review. The problem statement is</p> <blockquote> <p>Write a program that prompts the user to input ten values between 80 and 85 and stores them in an array. Your program must be able to count the frequency of each value appears in the array.</p> </blockquote> <p>I coded my own solution for the problem statement. My questions are<br> - Can this be optimized more?<br> - Did I miss anything in C++14 or C++17 that might improve the code?<br> - Is the code readable?<br> - Are the variable and function names good or can they be improved?</p> <p>My goals were to write the best C++ I could, remove any magic numbers and allow the solution to scale for different sets of numbers.</p> <pre><code>#include "pch.h" #include &lt;iostream&gt; #include &lt;array&gt; const size_t INPUTSIZE = 10; const size_t FREQUENCYSIZE = 6; const int MINLEGALVALUE = 80; const int MAXLEGALVALUE = 85; std::array&lt;int, INPUTSIZE&gt; getUserInput() { std::array&lt;int, INPUTSIZE&gt; inputValues; size_t i = 0; do { int inputValue = 0; std::cout &lt;&lt; "Please enter a number between " &lt;&lt; MINLEGALVALUE &lt;&lt; " and " &lt;&lt; MAXLEGALVALUE &lt;&lt; ":" ; std::cin &gt;&gt; inputValue; if (inputValue &gt;= MINLEGALVALUE &amp;&amp; inputValue &lt;= MAXLEGALVALUE) { inputValues[i] = inputValue; i++; } else { std::cout &lt;&lt; "The number must be between" &lt;&lt; MINLEGALVALUE &lt;&lt; " and " &lt;&lt; MAXLEGALVALUE &lt;&lt; "\n"; } } while (i &lt; INPUTSIZE); return inputValues; } std::array&lt;unsigned, FREQUENCYSIZE&gt; getFrequencyCounts(std::array&lt;int, INPUTSIZE&gt; inputValues) { std::array&lt;unsigned, FREQUENCYSIZE&gt; freqs = { 0 }; for (auto inputs : inputValues) { freqs[inputs - MINLEGALVALUE]++; } return freqs; } void printFrequencies(std::array&lt;unsigned, FREQUENCYSIZE&gt; freqs) { unsigned rowLabel = MINLEGALVALUE; for (auto frequency : freqs) { std::cout &lt;&lt; rowLabel &lt;&lt; " " &lt;&lt; frequency &lt;&lt; "\n"; rowLabel++; } } int main() { std::array&lt;int, INPUTSIZE&gt; inputValues = getUserInput(); std::array&lt;unsigned, FREQUENCYSIZE&gt; freqs = getFrequencyCounts(inputValues); std::cout &lt;&lt; "\n"; printFrequencies(freqs); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T19:56:42.420", "Id": "440081", "Score": "2", "body": "You've asked for optimizations, but the input size is too small for the usual [histogramming optimizations](http://fastcompression.blogspot.com/2014/09/counting-bytes-fast-little-trick-from.html) to matter, and anyway the program spends all of its time doing IO. Do you want to know about them anyway?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T11:13:10.997", "Id": "440155", "Score": "1", "body": "*Can this be optimized more?* The answer is basically always \"yes\". :P The real questions are \"how\", \"how much\", and go on from there into what speed vs. machine-code size footprint tradeoff you want to hit, and details about which inputs to optimize for (worst case vs. best case vs. average). (And of course for which ISA). Also optimizing for latency vs. throughput on an out-of-order execution CPU if the problem is small enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T11:19:17.487", "Id": "440156", "Score": "0", "body": "@PeterCordes You're right, I should have specified speed vs. size. I generally look for speed optimizations and accept the memory size trade off." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:22:31.940", "Id": "440195", "Score": "0", "body": "Sometimes you can shrink code-size without hurting speed. And for performance as a small part of a large program, smaller L1i cache footprint is an advantage. So sometimes the best thing for overall speed is to put some effort into code-size. (Often not, though, if there's anything you can usefully do with SIMD. But for histograms there isn't much until AVX512 scatter/gather + conflict-detection on x86, and even then it's not always worth it, and certainly not for a small problem size like 10 elements, not even one full vector of 32-bit counters.)" } ]
[ { "body": "<p>If you go for modern C++ the static variables should be marked as <code>constexpr</code> instead of plain old <code>const</code>.</p>\n\n<p>As was said in the other question, it should be beneficial to create an array of length <code>MAXLEGALVALUE - MINLEGALVALUE</code> and directly index into that array. That way there is probably less memory consumed and we count automatically. </p>\n\n<p>Personally I would use <code>std::size_t</code> or a well specified integer type like <code>std::uint32_t</code> rather than <code>unsigned</code>, which depends on the implementation.</p>\n\n<p>In range based for loops where the type is unambiguous I am not really a fan of auto. </p>\n\n<pre><code>for (auto inputs : inputValues)\n</code></pre>\n\n<p>How do you know that copying it is cheap here? You have to check the type of the container. Also you should consider const correctness so rather use <code>const int</code> or <code>const auto</code> if you prefere that.</p>\n\n<pre><code>for (const int inputs : inputValues)\n</code></pre>\n\n<p>Note that you have a truncation warning here as MINLEGALVALUE is of type <code>int</code>:</p>\n\n<pre><code>unsigned rowLabel = MINLEGALVALUE;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T11:22:54.717", "Id": "440157", "Score": "0", "body": "`unsigned` is actually a reasonable choice: the max count you might need to hold depends on how big your input array is. `int` / `unsigned int` are normally one of the fastest integer types that the machine can handle efficiently, unless it's an 8-bit implementation where `unsigned char` would be even faster. Obviously with a huge array of the same value repeated, with more than `UINT_MAX` entries, you could wrap around, but the OP is aiming for portable performance. Apparently even if that means a tradeoff in wrapping around in weird edge-case inputs (huge and unevenly distributed)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T19:49:05.863", "Id": "226453", "ParentId": "226448", "Score": "5" } }, { "body": "<p>One idea for simplification is to count frequencies directly instead of putting all the values in an array that you only use for counting frequencies. You can then remove the <code>getFrequencyCounts</code> function and the whole thing gets a little more efficient. This works well when you have a set of values in a dense range like [80,85]. If you have a lot of values far between eachother, using a <code>set</code> or <code>unordered_set</code> is probably a better choice. I found the code easy enough to read. Here are some ideas with comments in the code:</p>\n\n<pre><code>#include &lt;array&gt;\n#include &lt;iostream&gt;\n\nconstexpr size_t INPUTSIZE = 10;\nconstexpr int MINLEGALVALUE = 80;\nconstexpr int MAXLEGALVALUE = 85;\nconstexpr size_t FREQUENCYSIZE = MAXLEGALVALUE - MINLEGALVALUE + 1;\n\nstd::array&lt;unsigned, FREQUENCYSIZE&gt; getUserInputFreq() {\n std::array&lt;unsigned, FREQUENCYSIZE&gt; inputValues{0}; // initialize with 0\n\n size_t i = 0;\n do {\n int inputValue = 0;\n std::cout &lt;&lt; \"Please enter a number between \" &lt;&lt; MINLEGALVALUE &lt;&lt; \" and \"\n &lt;&lt; MAXLEGALVALUE &lt;&lt; \":\";\n\n // make sure the istream you read from succeeded in extracting\n if(std::cin &gt;&gt; inputValue) {\n if(inputValue &gt;= MINLEGALVALUE &amp;&amp; inputValue &lt;= MAXLEGALVALUE) {\n // count frequencies directly if you don't actually need the\n // input values\n ++inputValues[static_cast&lt;size_t&gt;(inputValue - MINLEGALVALUE)];\n ++i; // prefer prefix operator++\n } else {\n std::cout &lt;&lt; \"The number must be between\" &lt;&lt; MINLEGALVALUE &lt;&lt; \" and \"\n &lt;&lt; MAXLEGALVALUE &lt;&lt; \"\\n\";\n }\n } else \n break; // erroneous input or EOF\n\n } while(i &lt; INPUTSIZE);\n\n return inputValues;\n}\n\nvoid printFrequencies(std::array&lt;unsigned, FREQUENCYSIZE&gt; freqs) {\n int rowLabel = MINLEGALVALUE;\n for(auto frequency : freqs) {\n std::cout &lt;&lt; rowLabel &lt;&lt; \" \" &lt;&lt; frequency &lt;&lt; \"\\n\";\n ++rowLabel; // prefer prefix operator++\n }\n}\n\nint main() {\n std::array&lt;unsigned, FREQUENCYSIZE&gt; freqs = getUserInputFreq();\n\n std::cout &lt;&lt; \"\\n\";\n\n printFrequencies(freqs);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T11:29:59.093", "Id": "440158", "Score": "0", "body": "Yes counting on the fly as you read data can be good (hiding store-forwarding latency for a run of the same number), but now you're hard-coding reading it from `std::cin`. That's even less generic. Plus, I think the OP was just using GetInput as part of the caller for the histogram function to make a complete example. Anyway, you could **take an [`InputIterator`](https://en.cppreference.com/w/cpp/iterator) as a function arg** or something like that to let the caller specify where the input comes from." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T12:06:45.440", "Id": "440164", "Score": "0", "body": "@PeterCordes \"_now you're hard-coding reading it from `std::cin`_\" - That part was actually not changed from OP's implementation. I only changed the function name from `getUserInput` to `getUserInputFreq` and continued to use `std::cin` since the whole thing looked pretty focused on user interaction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T13:05:48.497", "Id": "440173", "Score": "0", "body": "The original had one function that reads input, and a *separate* function that histogrammed a container (with an unfortunate hard-coding of the type). You're making it worse, not better, for separability / reusability. After inlining + optimization of an iterator, you can still have basically the same machine code you could get from your function, but with clean source." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T13:52:03.273", "Id": "440181", "Score": "0", "body": "@PeterCordes \"_The original had one function that reads input_\" - yes, from `std::cin`, with a prompt-like text. What I did was to reduce the number of steps and also to add status checking where appropriate. The only thing not saved is the order in which the numbers were entered. The original post didn't show any demand for it. if I were to make a generic input function, I'd make it read from a `std::istream&` but that didn't seem worth the effort since the whole `getUserInput` function has focus on input from a user." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T19:50:38.790", "Id": "226454", "ParentId": "226448", "Score": "2" } }, { "body": "<h3>Names</h3>\n\n<p>All-caps names are typically reserved for macros. They don't seem to me to make much sense for <code>const</code> variables. In fact, they only make minimal sense for object-like macros--they were originally used for function-like macros as kind of a warning that you should be cautious about passing an argument with side-effects, because they might happen more than once.</p>\n\n<h3>Minimize Magic</h3>\n\n<p>I'd typically try to keep the magic numbers to a minimum. For example, instead of defining <code>FREQUENCYSIZE</code> by itself, I'd probably do something like this:</p>\n\n<pre><code>const int lower_bound = 80;\ncount int upper_bound = 85;\nconst int frequency_size = upper_bound - lower_bound + 1;\n</code></pre>\n\n<h3>Separation of Concerns</h3>\n\n<p>I'd at least consider separating validating data from reading the data. I'd prefer to have a function on the general order of:</p>\n\n<pre><code>bool valid(int val) { \n return val &gt;= lower_bound &amp;&amp; val &lt; upper_bound;\n}\n</code></pre>\n\n<h3>Class Usage</h3>\n\n<p>We have a number of different things related to reading and working with numbers in a specified range. It might be worth considering wrapping those bits and pieces into a coherent class for dealing with a value in a range, and let the outside world create and use objects of that class.</p>\n\n<pre><code>template &lt;class T, T lower_bound, T upper_bound&gt;\nclass bounded {\npublic:\n static bool valid(T val) { return val &gt;= lower_bound &amp;&amp; val &lt; upper_bound; }\n\n friend std::istream &amp;operator&gt;&gt;(std::istream &amp;is, bounded &amp;b) { \n T val;\n is &gt;&gt; val;\n if (valid(val)) \n b.val = val;\n else\n is.setstate(std::ios_base::failbit);\n return is;\n }\n\n friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, bounded const &amp;b) {\n return os &lt;&lt; b.val;\n }\n\n size_t index() { return size_t(val - lower_bound); }\n\n static constexpr size_t range() { return upper_bound - lower_bound + 1; }\n\nprivate:\n T val;\n};\n</code></pre>\n\n<p>That let's us simplify the rest of the code a bit, something on this general order:</p>\n\n<pre><code>int main() {\n using integer = bounded&lt;int, 80, 85&gt;;\n\n std::array&lt;integer, 10&gt; inputs;\n std::array&lt;size_t, integer::range()&gt; freqs {};\n\n for (integer &amp;i : inputs) {\n std::cin &gt;&gt; i;\n ++freqs[i.index()];\n }\n\n for (auto freq : freqs)\n std::cout &lt;&lt; freq &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>Technically, this doesn't meet the requirements as-is (e.g., it doesn't print out a prompt to tell the user to enter data), but I think it gives at least some idea of a direction things could go.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T20:13:57.583", "Id": "226456", "ParentId": "226448", "Score": "10" } } ]
{ "AcceptedAnswerId": "226456", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T18:37:27.507", "Id": "226448", "Score": "9", "Tags": [ "c++", "performance", "c++14", "c++17" ], "Title": "Count the frequency of integers in an array" }
226448
<p>I wrote a queue class in C++ using arrays of fixed width. Could anyone review my code ? I would appreciate any comment and recommendations. It works like a circular queue, so I handled back and front pointers in that manner.</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;iostream&gt; template &lt;class T&gt; class Queue { public: Queue(void); Queue(Queue&lt;T&gt;&amp; copyQueue); bool empty(void) const; std::size_t size(void) const; void clear(void); T front(void) const; void pop(void); void push(T&amp; item); void print(std::ostream&amp; os); private: static const std::size_t MAX_SIZE = 50; T list[MAX_SIZE]; T* frontPtr; T* backPtr; std::size_t sizeQ; }; template &lt;class T&gt; Queue&lt;T&gt;::Queue(void) { frontPtr = nullptr; backPtr = nullptr; sizeQ = 0; } template &lt;class T&gt; Queue&lt;T&gt;::Queue(Queue&lt;T&gt;&amp; copyQueue) { frontPtr = nullptr; backPtr = nullptr; sizeQ = 0; if(copyQueue.backPtr &gt;= copyQueue.frontPtr){ for(T* i = copyQueue.frontPtr; i &lt;= copyQueue.backPtr; i++){ push(*i); } } else { for(T* i = copyQueue.frontPtr; i &lt;= (copyQueue.list + MAX_SIZE -1); i++){ push(*i); } for(T* i = copyQueue.list; i &lt;= copyQueue.backPtr; i++) { push(*i); } } } template &lt;class T&gt; bool Queue&lt;T&gt;::empty(void) const { return (sizeQ == 0); } template &lt;class T&gt; std::size_t Queue&lt;T&gt;::size(void) const { return sizeQ; } template &lt;class T&gt; void Queue&lt;T&gt;::clear(void) { frontPtr = nullptr; backPtr = nullptr; sizeQ = 0; } template &lt;class T&gt; T Queue&lt;T&gt;::front(void) const { if(frontPtr == nullptr) { std::cerr &lt;&lt; "Queue is empty. No front value" &lt;&lt; '\n'; } else { return *frontPtr; } } template &lt;class T&gt; void Queue&lt;T&gt;::pop(void) { if(sizeQ == 0) { std::cerr &lt;&lt; "Queue is empty. Can't pop." &lt;&lt; '\n'; } else{ frontPtr = list + ((frontPtr - list + 1) % MAX_SIZE); sizeQ -= 1; } } template &lt;class T&gt; void Queue&lt;T&gt;::push(T&amp; item) { if(sizeQ == MAX_SIZE) { std::cerr &lt;&lt; "Queue is full. Can't push" &lt;&lt; '\n'; } else{ if(sizeQ == 0) { frontPtr = backPtr = list; } else { backPtr = list + ((backPtr - list + 1) % MAX_SIZE); } *backPtr = item; sizeQ += 1; } } template &lt;class T&gt; void Queue&lt;T&gt;::print(std::ostream&amp; os) { if(backPtr &gt;=frontPtr){ for(T* i = frontPtr; i &lt;= backPtr; i++){ os &lt;&lt; *i &lt;&lt; '\n'; } } else { for(T* i = frontPtr; i &lt;= (list + MAX_SIZE -1); i++){ os &lt;&lt; *i &lt;&lt; '\n'; } for(T* i = list; i &lt;= backPtr; i++) { os &lt;&lt; *i &lt;&lt; '\n'; } } } </code></pre> <p><strong>Edit:</strong> Not using <code>googletest</code>, but a simple main function to test the <code>Queue.h</code> can be found below:</p> <pre><code>#include "Queue.h" int main() { Queue&lt;int&gt; newQueue; for(int i=1; i&lt;110; i = i+2) newQueue.push(i); newQueue.pop(); newQueue.pop(); newQueue.pop(); newQueue.pop(); int i = 999; newQueue.push(++i); newQueue.push(++i); newQueue.push(++i); newQueue.push(++i); newQueue.print(std::cout); Queue&lt;int&gt; copiedQueue(newQueue); std::cout &lt;&lt; copiedQueue.size() &lt;&lt; '\n'; copiedQueue.print(std::cout); for(int i=1; i&lt;11; i = i+2) copiedQueue.pop(); newQueue.print(std::cout); std::cout &lt;&lt; copiedQueue.empty(); std::cout &lt;&lt; newQueue.empty(); copiedQueue.print(std::cout); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T22:02:53.273", "Id": "440097", "Score": "0", "body": "You've obviously put a lot of time into this, could you please add some code that uses this class or tests it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T07:09:28.637", "Id": "440130", "Score": "0", "body": "@pacmaninbw , I added a main function to test the code." } ]
[ { "body": "<p>Some general improvements:</p>\n\n<ol>\n<li>Use <code>&lt;cstdlib&gt;</code>, not <code>&lt;stdlib.h&gt;</code>. The latter is a deprecated header that is kept for C compatibility. It should not be used in new C++ code. </li>\n<li>Do not use <code>void</code> in an empty parameter list. It is counterintuitive and is not necessary in C++ at all. It is only used in C prototypes.</li>\n<li>The copy constructor should take by const reference because it does not modify the argument. Same for <code>push</code>. </li>\n<li>You are using assignment in constructors when you ought to use member initializer clauses. This is bad practice. </li>\n<li><code>front</code> should return by const reference, not by value. Returning by value makes an unnecessary copy. </li>\n<li><code>MAX_SIZE</code> is not a macro and should not be in ALL_CAPS. And it should be <code>constexpr</code>. Or better, a template parameter. </li>\n<li>It is advised in C++ to use <code>std::array</code> instead of raw arrays. </li>\n</ol>\n\n<p>There are still many things to improve, but this should be enough to get you started. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T20:55:01.227", "Id": "440556", "Score": "0", "body": "thank you for having time to analyze and elaborate the class. Regarding your `8`th suggestion, shall I remove the `sizeQ`variable? Then, I should track the fullness of the queue by `backPtr - frontPtr`? This would create problem as it is a circular queue. Could you please inform me a bit more on this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T20:58:59.583", "Id": "440557", "Score": "1", "body": "@ErdemTuna Oops, I didn't realize that this is a circular queue. Sorry for that. Still, the `sizeQ` variable contains more information than it should and you have to keep it synchronized. You may replace it with a `bool` variable indicating whether the queue is empty, I guess. I'll delete that bullet." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T17:06:09.623", "Id": "226578", "ParentId": "226452", "Score": "3" } }, { "body": "<p>1) swap from using an array to either vector or std::array, N> elems;\n current when using std::array the types that you may hold in you queue are limited to default constructable</p>\n\n<p>2) copy constructor should be passed by const ref</p>\n\n<p>3) Perhapse think about moving the max size parameter as a template perameter template class Queue</p>\n\n<p>4) I noticed there is not a assignment operator is this on purpose? </p>\n\n<p>5) correct me if I am wrong but when implementing a circular queue and a push runs out of space shouldn't you pop from the front and push to back</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-31T18:13:39.997", "Id": "442146", "Score": "0", "body": "Thank you for the evaluation. Regarding `3`, why and how should `MAX_SIZE` be a template class? Regarding `4`, I just didn't implement it, I should write that part. Regarding `5`, I wasn't aware of that fact, but I guess you are right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-01T22:31:22.180", "Id": "442300", "Score": "1", "body": "@ErdemTuna \n\n3 - why? Because it would allow for a more flexible use case of the class now the max size can still be determined at compile time but different instances can have different max sizes if you wish. How? ```c++ template <class T, std::size_t MAX_SIZE = 50> \nclass Queue { ```" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-30T16:08:07.557", "Id": "227185", "ParentId": "226452", "Score": "1" } } ]
{ "AcceptedAnswerId": "226578", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T19:38:26.760", "Id": "226452", "Score": "4", "Tags": [ "c++", "queue" ], "Title": "Basic Queue in C++ Using Array" }
226452
<p>I wrote a backtracking Sudoku solving algorithm in Python. It solves a 2D array like this (zero means "empty field"):</p> <pre><code>[ [7, 0, 0, 0, 0, 9, 0, 0, 3], [0, 9, 0, 1, 0, 0, 8, 0, 0], [0, 1, 0, 0, 0, 7, 0, 0, 0], [0, 3, 0, 4, 0, 0, 0, 8, 0], [6, 0, 0, 0, 8, 0, 0, 0, 1], [0, 7, 0, 0, 0, 2, 0, 3, 0], [0, 0, 0, 5, 0, 0, 0, 1, 0], [0, 0, 4, 0, 0, 3, 0, 9, 0], [5, 0, 0, 7, 0, 0, 0, 0, 2], ] </code></pre> <p>like this:</p> <pre><code>[ [7, 5, 8, 2, 4, 9, 1, 6, 3], [4, 9, 3, 1, 5, 6, 8, 2, 7], [2, 1, 6, 8, 3, 7, 4, 5, 9], [9, 3, 5, 4, 7, 1, 2, 8, 6], [6, 4, 2, 3, 8, 5, 9, 7, 1], [8, 7, 1, 9, 6, 2, 5, 3, 4], [3, 2, 7, 5, 9, 4, 6, 1, 8], [1, 8, 4, 6, 2, 3, 7, 9, 5], [5, 6, 9, 7, 1, 8, 3, 4, 2] ] </code></pre> <p>But for "hard" Sudokus (where there are a lot of zeros at the beginning), it's quite slow. It takes the algorithm around 9 seconds to solve the Sudoku above. That's a lot better then what I startet with (90 seconds), but still slow.</p> <p>I think that the "deepcopy" can somehow be improved/replaced (because it is executed 103.073 times in the example below), but my basic approaches were slower..</p> <p>I heard of 0.01 second C/C++ solutions but I'm not sure if those are backtracking algorithms of some kind of mathematical solution...</p> <p>This is my whole algorithm with 2 example Sudokus:</p> <pre><code>from copy import deepcopy def is_sol_row(mat,row,val): m = len(mat) for i in range(m): if mat[row][i] == val: return False return True def is_sol_col(mat,col,val): m = len(mat) for i in range(m): if mat[i][col] == val: return False return True def is_sol_block(mat,row,col,val): rainbow = [0,0,0,3,3,3,6,6,6] i = rainbow[row] j = rainbow[col] elements = { mat[i + 0][j + 0], mat[i + 1][j + 0], mat[i + 2][j + 0], mat[i + 0][j + 1], mat[i + 1][j + 1], mat[i + 2][j + 1], mat[i + 0][j + 2], mat[i + 1][j + 2], mat[i + 2][j + 2], } if val in elements: return False return True def is_sol(mat,row,col,val): return is_sol_row(mat,row,val) and is_sol_col(mat,col,val) and is_sol_block(mat,row,col,val) def findAllZeroIndizes(mat): m = len(mat) indizes = [] for i in range(m): for j in range(m): if mat[i][j] == 0: indizes.append((i,j)) return indizes def sudoku(mat): q = [(mat,0)] zeroIndizes = findAllZeroIndizes(mat) while q: t,numSolvedIndizes = q.pop() if numSolvedIndizes == len(zeroIndizes): return t else: i,j = zeroIndizes[numSolvedIndizes] for k in range(1,10): if is_sol(t,i,j,k): newt = deepcopy(t) newt[i][j] = k q.append((newt,numSolvedIndizes+1)) return False mat = [ [7, 0, 0, 0, 0, 9, 0, 0, 3], [0, 9, 0, 1, 0, 0, 8, 0, 0], [0, 1, 0, 0, 0, 7, 0, 0, 0], [0, 3, 0, 4, 0, 0, 0, 8, 0], [6, 0, 0, 0, 8, 0, 0, 0, 1], [0, 7, 0, 0, 0, 2, 0, 3, 0], [0, 0, 0, 5, 0, 0, 0, 1, 0], [0, 0, 4, 0, 0, 3, 0, 9, 0], [5, 0, 0, 7, 0, 0, 0, 0, 2], ] # mat = [ # [3, 0, 6, 5, 0, 8, 4, 0, 0], # [5, 2, 0, 0, 0, 0, 0, 0, 0], # [0, 8, 7, 0, 0, 0, 0, 3, 1], # [0, 0, 3, 0, 1, 0, 0, 8, 0], # [9, 0, 0, 8, 6, 3, 0, 0, 5], # [0, 5, 0, 0, 9, 0, 6, 0, 0], # [1, 3, 0, 0, 0, 0, 2, 5, 0], # [0, 0, 0, 0, 0, 0, 0, 7, 4], # [0, 0, 5, 2, 0, 6, 3, 0, 0] # ] print(sudoku(mat)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T02:39:59.657", "Id": "440120", "Score": "0", "body": "see also: [speed up backtracking sudoku solver](https://stackoverflow.com/q/57562309/3789665)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T11:36:53.843", "Id": "440159", "Score": "0", "body": "You can use a backtracking algorithm that is considerably faster than brute force: Knuth's Algorithm X. I wrote one in another language just the other week: https://codereview.stackexchange.com/questions/226317/leetcode-37-sudoku-as-exact-cover-problem-solved-using-dancing-links." } ]
[ { "body": "<p>Your sudoku solver is missing a crucial part: the one that fills all obvious cells without backtracking.</p>\n\n<p>In your example sudoku, in row 1 column 7 there must be a 1 because that's the only place in row 1 where a 1 is possible. That's because the blocks to the left already contain a 1, and columns 8 and 9 also contain a 1 further down.</p>\n\n<p>With that improvement, the algorithm should get quite fast. That's probably how every other sudoku solver attacks the complexity, therefore you should have a look at the answers of related code reviews.</p>\n\n<p>In 2006 <a href=\"http://roland-illig.de/tmp/sudoku-1.0.tar.gz\" rel=\"nofollow noreferrer\">I wrote a sudoku solver in C</a> using exactly this improvement. You may have a look at it, it should be pretty fast, even when you translate it back to Python.</p>\n\n<p>Since sudokus are popular, several people have already <a href=\"https://warwick.ac.uk/fac/sci/moac/people/students/peter_cock/python/sudoku\" rel=\"nofollow noreferrer\">documented</a> how they wrote a sudoku solver. I found this one via <a href=\"https://rosettacode.org/wiki/Sudoku\" rel=\"nofollow noreferrer\">Rosetta Code</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T20:16:01.773", "Id": "226457", "ParentId": "226455", "Score": "2" } }, { "body": "<h1>Style</h1>\n\n<p>Your code mostly follows <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> but is a bit more terse. Mostly:</p>\n\n<ul>\n<li>Using 4 spaces for indentation;</li>\n<li>Putting a space after every coma;</li>\n<li>Using two blank lines to separate top-level functions;</li>\n</ul>\n\n<p>should ease reading your code.</p>\n\n<p>You also use camelCaseVariableNames from time to time, instead of snake_case.</p>\n\n<p>Lastly, using an <a href=\"https://stackoverflow.com/q/419163/5069029\"><code>if __name__ == '__main__'</code></a> would allow you to more easily test or reuse your module.</p>\n\n<h1>Naming</h1>\n\n<p>I find <code>is_sol</code> and derived functions kind of misleading as it does not test if it found a solution (as the name would suggest) but if a number could fit at a given position in the grid. Changing names to use wording such as test, check… and/or fits, find… could improve understanding at a glance.</p>\n\n<h1>Looping</h1>\n\n<p>Many times you iterate over indices to retrieve a value in a list. I suggest you have a look at Ned Batchelder's talk <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">loop like a native</a> and try to iterate over the elements directly instead.</p>\n\n<p>You also often use plain-Python <code>for</code> loops where list-comprehensions or generator expresions would faster: <a href=\"https://docs.python.org/3/library/functions.html#any\" rel=\"nofollow noreferrer\"><code>any</code></a> and <a href=\"https://docs.python.org/3/library/functions.html#all\" rel=\"nofollow noreferrer\"><code>all</code></a> are your friends here.</p>\n\n<h1>Copying</h1>\n\n<p>Instead of using the slow <code>deepcopy</code> you could leverage the fact that you know your data structure. You use a list of lists, so <code>copy</code> your inner lists into a new outer list. Timings on my machine indicates this is 40x faster:</p>\n\n<pre><code>&gt;&gt;&gt; import timeit\n&gt;&gt;&gt; timeit.timeit('deepcopy(mat)', 'from __main__ import mat; from copy import deepcopy')\n48.071381973999905\n&gt;&gt;&gt; timeit.timeit('[row.copy() for row in mat]', 'from __main__ import mat')\n1.1098871960002725\n</code></pre>\n\n<h1>Proposed improvements</h1>\n\n<pre><code>VALID_NUMBERS = range(1, 10)\n\n\ndef fits_in_row(value, grid, row):\n return all(element != value for element in grid[row])\n\n\ndef fits_in_column(value, grid, column):\n return all(row[column] != value for row in grid)\n\n\ndef fits_in_block(value, grid, row, column):\n block_row = (row // 3) * 3\n block_column = (column // 3) * 3\n return all(\n grid[block_row + i][block_column + j] != value\n for i in range(3) for j in range(3)\n )\n\n\ndef fits_in_cell(value, grid, row, column):\n return (\n fits_in_row(value, grid, row)\n and fits_in_column(value, grid, column)\n and fits_in_block(value, grid, row, column)\n )\n\n\ndef empty_cells_indices(grid):\n return [\n (i, j)\n for i, row in enumerate(grid)\n for j, element in enumerate(row)\n if element not in VALID_NUMBERS\n ]\n\n\ndef sudoku(grid):\n to_solve = [(grid, 0)]\n empty_cells = empty_cells_indices(grid)\n\n while to_solve:\n grid, guessed_cells = to_solve.pop()\n if guessed_cells == len(empty_cells):\n return grid\n\n row, column = empty_cells[guessed_cells]\n for value in VALID_NUMBERS:\n if fits_in_cell(value, grid, row, column):\n new = [row.copy() for row in grid]\n new[row][column] = value\n to_solve.append((new, guessed_cells + 1))\n\n\nif __name__ == '__main__':\n mat = [\n [7, 0, 0, 0, 0, 9, 0, 0, 3],\n [0, 9, 0, 1, 0, 0, 8, 0, 0],\n [0, 1, 0, 0, 0, 7, 0, 0, 0],\n\n [0, 3, 0, 4, 0, 0, 0, 8, 0],\n [6, 0, 0, 0, 8, 0, 0, 0, 1],\n [0, 7, 0, 0, 0, 2, 0, 3, 0],\n\n [0, 0, 0, 5, 0, 0, 0, 1, 0],\n [0, 0, 4, 0, 0, 3, 0, 9, 0],\n [5, 0, 0, 7, 0, 0, 0, 0, 2],\n ]\n\n # mat = [\n # [3, 0, 6, 5, 0, 8, 4, 0, 0],\n # [5, 2, 0, 0, 0, 0, 0, 0, 0],\n # [0, 8, 7, 0, 0, 0, 0, 3, 1],\n # [0, 0, 3, 0, 1, 0, 0, 8, 0],\n # [9, 0, 0, 8, 6, 3, 0, 0, 5],\n # [0, 5, 0, 0, 9, 0, 6, 0, 0],\n # [1, 3, 0, 0, 0, 0, 2, 5, 0],\n # [0, 0, 0, 0, 0, 0, 0, 7, 4],\n # [0, 0, 5, 2, 0, 6, 3, 0, 0]\n # ]\n\n import pprint\n pprint.pprint(sudoku(mat))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T11:07:21.287", "Id": "440153", "Score": "0", "body": "Using copy instead of deepcopy is indeed a lot faster. Thanks you so much for the tipps. When I replace the deepcopy with copy in my initial solution, it takes me ~ 1.8s, but using things like \"all, any...\" seem to make it slower than that. (2.4s). Using only one line ```return all(element != value for element in grid[row])``` looks nice but it seems that something takes longer.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T11:11:21.580", "Id": "440154", "Score": "1", "body": "@ndsvw The code I proposed run in 1.6s on my machine. I will test removing all `all`s in a bit to check but this seems odd that it runs slower." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T08:51:30.080", "Id": "226478", "ParentId": "226455", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T20:09:33.243", "Id": "226455", "Score": "2", "Tags": [ "python", "algorithm", "sudoku", "backtracking" ], "Title": "How to make my backtraching sudoku solving algorithm in Python faster?" }
226455
<p>This code adds the following functionality to the basic <code>tkinter.Tk()</code> class...</p> <ul> <li><p>settings-file interaction for persistent application settings</p></li> <li><p>fullscreen functionality using F11, can remember last configuration or be defaulted</p></li> <li><p>removes the need for multiple <code>root.configure()</code> statements</p></li> <li><p>removes the need for <code>root.title()</code> and <code>root.row/columnconfigure()</code></p></li> </ul> <p>You adjust the default window by calling it using the Window() class, and then you can use two functions to adjust the settings file (which will be named <code>settings.ini</code> by default).</p> <ul> <li><code>root.set()</code> configures all of the software options found in settings.ini in realtime.</li> <li><code>root.get()</code> returns a dictionary with the settings you want to reference from <code>settings.ini</code></li> <li>you can supply multiple arguments to both of these functions</li> </ul> <p>One thing that always bugged me about tkinter was the need for multiple <code>root.configure()</code> statements, so I wrote a function called <code>root.config()</code> that loops through all the keyword arguments you supply and runs the appropriate configuration for them.</p> <ul> <li>this function also handles the <code>title()</code> and <code>row/columnconfigure()</code> functions in this format:</li> </ul> <pre class="lang-py prettyprint-override"><code>root = Window() root.config(bg='black', title='My Window', row=(0, 1), col=(0, 1)) root.mainloop() </code></pre> <p>This creates a basic window with a black background, a title ("My Window"), and row 0 and column 0 are set to weight = 1.</p> <p>The code for this <code>Window()</code> class is below, along with an example setup. You can simply copy/paste this into your editor and it'll run as a standalone.</p> <pre class="lang-py prettyprint-override"><code>import tkinter as tk import os class Window(tk.Tk): def __init__(self, settings_file='./settings.ini'): self.window = super() self.window.__init__() self.window.bind('&lt;F11&gt;', self.toggleFullscreen) self.window.protocol('WM_DELETE_WINDOW', self.closing) ### the settings file is where your window properties are stored ### self.file = settings_file ### checking if settings file exists ### try: open(self.file) ### if settings file doesn't exist, it gets created ### except Exception as e: print('settings file not found.\n' 'writing initial settings file.') with open(self.file, 'w') as f: initial_settings = [ ### Create your default settings file file here ### '; display settings\n\n', 'fullscreen=False\n', 'resolution=720x480\n', 'screenres=%dx%d\n' % (self.winfo_screenwidth(), self.winfo_screenheight()), 'resizex=True\n', 'resizey=True\n\n' 'fontfamily=TkDefaultFont\n', 'fontsize=12' ] for i in initial_settings: f.write(i) open(self.file, 'w') ### ### reading the settings file with open(self.file) as f: settings = f.readlines() self.settings = settings self.update() ### this refreshes the window size and properties ### def update(self): with open(self.file) as f: settings = f.readlines() self.settings = settings self.font = (self.get('fontf')['fontfamily'], self.get('fonts')['fontsize']) self.window.resizable(self.get('rx')['resizex'], self.get('ry')['resizey']) self.window.geometry('%s' % self.get('res')['resolution']) self.window.overrideredirect(0) if self.get('fs')['fullscreen'] == 'True': self.window.geometry('%s' % self.get('screenres')['screenres']) self.toggleFullscreen(None) self.window.update() ### this function changes the window to be fullscreen or normal ### def toggleFullscreen(self, event=None): if self.get('fullscreen')['fullscreen'] == 'True' and event: self.set(fs = False) self.window.overrideredirect(0) return if self.get('fullscreen')['fullscreen'] == 'False' and event: if event: self.set(fs = True) self.window.overrideredirect(1) self.window.geometry('%sx%s+0+0' % (self.winfo_screenwidth(), self.winfo_screenheight())) return if not event: if self.get('fullscreen')['fullscreen'] == 'True': self.window.overrideredirect(1) self.window.geometry('%sx%s+0+0' % (self.winfo_screenwidth(), self.winfo_screenheight())) else: self.window.overrideredirect(0) self.window.update() ### last-minute cleanup before closing the window ### def closing(self): #self.set(fs=False) self.window.destroy() ### set the values in settings file to keyword arguments ### def set(self, **kwargs): ### shorthands for the set command ### if 'fs' in kwargs: kwargs['fullscreen'] = kwargs.pop('fs') if 'res' in kwargs: kwargs['resolution'] = kwargs.pop('res') if 'rx' in kwargs: kwargs['resizex'] = kwargs.pop('rx') if 'ry' in kwargs: kwargs['resizey'] = kwargs.pop('ry') for i in kwargs: for n, j in enumerate(self.settings): if j.lower().startswith(i): j = j.replace( j [j.find('=')+1:], str(kwargs[i]) + '\n' ) self.settings[n] = j with open(self.file, 'w') as f: for i in self.settings: f.write(i) self.update() ### search through the settings and pull the values of each argument ### def get(self, *args): args = ['fullscreen' if i == 'fs' else i for i in args] args = ['resolution' if i == 'res' else i for i in args] args = ['resizex' if i == 'rx' else i for i in args] args = ['resizey' if i == 'ry' else i for i in args] args = ['fontfamily' if i == 'fontf' else i for i in args] args = ['fontsize' if i == 'fonts' else i for i in args] results = {} ### get the rest of the text following the = sign in settings file ### for value in args: for i, j in enumerate(self.settings): if j.startswith(value): results[value] = j[j.find('=')+1:].strip() return results ### run a configure function for each keyword argument ### def config(self, **kwargs): ### title the window ### if 'title' in kwargs: self.title = kwargs['title'] self.window.title(kwargs.pop('title')) ### row configure ### if 'row' in kwargs: self.window.rowconfigure(kwargs['row'][0], weight = kwargs['row'][1]) kwargs.pop('row') ### column configure ### if 'column' in kwargs or 'col' in kwargs: try: kwargs['column'] = kwargs.pop('col') except: pass self.window.columnconfigure(kwargs['column'][0], weight = kwargs['column'][1]) kwargs.pop('column') self.window.configure(**kwargs) ### the following is an example to show how this class is used ### root = Window() ### creating a small, non-resizable root window that is windowed by default root.set(fs=False, res='240x160', rx=False, ry=False) ### basic styling and configuration with window title root.config(bg='black', bd=12, relief=tk.SUNKEN, title='Window') ### setting the default font size for the window root.set(fontsize=32) label = tk.Label(root, text='test', fg='white', bg=root['bg'], font=root.font) label.pack(fill = tk.BOTH, expand=True) ### You can toggle fullscreen by pressing F11 root.mainloop() </code></pre> <p>You can also add and change shorthands for the <code>set()</code> and <code>get()</code> methods using list comprehension, as shown in the source code.</p> <p>Any feedback on this would be highly appreciated, as I know there are a few things I'd like to improve!</p> <ul> <li><p>The code for implementing fullscreen is not very DRY, and I know there's probably a way around this.</p></li> <li><p>To use the <code>get()</code> function, you have to specify the key you're looking to pull.</p></li> </ul> <pre><code># example print(root.get('fs')['fullscreen']) </code></pre> <p>I know this can probably be fixed by changing the output from a dictionary to a list, so I'll do that soon.</p> <p>Either way, let me know what you think, or how I can improve this. I wanted to make this as a way of speeding up the rudimentary GUI creation process, and hopefully it can be used to get the ugly stuff out of the way faster.</p> <p>Thanks in advance!</p>
[]
[ { "body": "<p>Welcome to CodeReview! Good first post.</p>\n\n<h2>Comments</h2>\n\n<p>Having comments is great. Your convention is a little odd - there's no need for triple hashes. A single hash at the beginning is more common.</p>\n\n<h2>File handling</h2>\n\n<p>Your intention was good, but the execution could be improved. Firstly, at this level, don't <code>except Exception</code>. It's too broad. Let exceptions be exceptional. You'll want to instead catch something more specific, in this case <code>FileNotFoundError</code>.</p>\n\n<p>Another strategy for simplifying your code is, instead of opening the settings file twice, only open it once. Consider opening the file in <code>a</code> (append) mode, which will automatically create the file if it doesn't exist. Check the stream position, and if it's non-zero, the file has stuff, in which case you can seek to the beginning and try to read it. If the initial position is zero, then you know you have to write out defaults. Rather than writing out the default file contents in a pre-serialized format, write out the contents as serialized from an in-memory dictionary and don't read them back from the file. One 'gotcha' this avoids is that your existing file operations only explicitly close the file in two out of three cases.</p>\n\n<h2>Python 3 niceties</h2>\n\n<p>Rather than using the <code>%</code> string formatting operator, consider using interpolated, or \"f\" strings. That said, this:</p>\n\n<pre><code>'%s' % self.get('res')['resolution']\n</code></pre>\n\n<p>shouldn't have a format call at all. If the resolution is numeric, simply call <code>str</code>.</p>\n\n<h2>Stringly-typed options</h2>\n\n<p><code>'True'</code>, as a string, should not exist once the settings file has been deserialized. It should be a grown-up boolean variable. Then, for one thing, this:</p>\n\n<pre><code>if self.get('fullscreen')['fullscreen'] == 'True'\n</code></pre>\n\n<p>will simply be</p>\n\n<pre><code>if self.get('fullscreen')['fullscreen']\n</code></pre>\n\n<h2>Control structures</h2>\n\n<p>Somewhat heavy-handed use of return could be obviated:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if event:\n if self.get('fullscreen')['fullscreen']:\n # ...\n else:\n # ...\nelse:\n # ...\n</code></pre>\n\n<p>No returns needed.</p>\n\n<h2>Get</h2>\n\n<p>Your <code>args</code> filtration could be simplified. Maybe use a dict for those mappings.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>arg_map = {\n 'fs': 'fullscreen',\n 'res': 'resolution',\n 'resizex': 'rx',\n 'resizey': 'ry',\n 'fontfamily': 'fontf',\n 'fontsize': 'fonts'\n}\n\nargs = [arg_map.get(k, k) for k in args]\n</code></pre>\n\n<p>But why is this mapping occurring at all? Why doesn't <code>get</code> just accept the long-form arguments? Beyond that, why are you doing a prefix match on the configuration keys instead of the entire key?</p>\n\n<h2><code>except: pass</code></h2>\n\n<p>Never ever. Ever. For one thing, this renders Ctrl+C breaking impossible. Also, it defeats the entire purpose of the exception-handling system. If you know of a specific exception you're trying to address, catch that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T13:59:39.140", "Id": "440184", "Score": "0", "body": "Thanks for your input! I use the triple-hashes as a way of making the comments pop, which is a rather odd personal choice, I'll admit! I had no idea that append mode would check for the file's existence, which is nice (I'll also catch those exceptions as well). I always forget about f strings, thanks for reminding me! With the way I wrote it, I wasn't able to do booleans for the 'True' and 'False,' and I'm looking for a means to fix that as well. Thanks for the tips on control structure as well! The shorthands are for once people are used to the framework. I'll also cut out passing, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:02:35.280", "Id": "440185", "Score": "0", "body": "The usual way to \"make the comments pop\" is to use a good editor or IDE with highlighting. Comments will be in a different colour." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:10:16.567", "Id": "440190", "Score": "0", "body": "Sure thing, I'll try messing around with it :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:34:32.180", "Id": "440197", "Score": "0", "body": "By the way, what do you mean by writing the default contents from an in-memory dictionary? I haven't heard of serialized versus deserialized before today." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:36:26.863", "Id": "440210", "Score": "0", "body": "`# Create your default settings file` is followed by a serialized representation of your configuration file. Serialized data is one big long string or byte array representing a more complex data structure. Your configuration, fundamentally, isn't one string: it's a dictionary of key-value pairs. For most of the lifetime of the application, you'll want to hold onto the dictionary in memory and not the serialized representation, which will stay on disk." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:49:07.203", "Id": "440213", "Score": "0", "body": "Okay, cool, thanks! I just rewrote that segment to write/format ```settings.ini``` from a dictionary instead. Thanks for all your help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T17:28:48.117", "Id": "440229", "Score": "0", "body": "You're welcome, and feel free to tag me in a follow-up question if you want another round of review." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T01:40:37.563", "Id": "226469", "ParentId": "226458", "Score": "0" } } ]
{ "AcceptedAnswerId": "226469", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T20:37:08.130", "Id": "226458", "Score": "2", "Tags": [ "python", "gui", "tkinter", "framework", "tk" ], "Title": "Adding more functionality to tkinter for projects" }
226458
<p><strong>The exercise description:</strong></p> <blockquote> <p>Given a ‘words.txt’ file (attached) containing a newline-delimited list of dictionary words, please implement a small command line application capable to return all the anagrams from ‘words.txt’ for a given word. You can use any Scala library of your choice, no frameworks though.</p> </blockquote> <p>Note: the file contains words that are sometimes Uppercased or have random upper/lowercasing. Checking for an anagram should not consider casing.</p> <p><strong>My solution:</strong></p> <p>Main.scala</p> <pre class="lang-scala prettyprint-override"><code>import scala.io.Source import scala.util.Using object Main extends App { def isAnagram(word: String, anagram: String) : Boolean = word.toLowerCase.toSeq.sorted.unwrap == anagram.toLowerCase.toSeq.sorted.unwrap print("Type the word for which you wish to search anagrams: ") val word = scala.io.StdIn.readLine() Using(Source.fromResource("words.txt")){ source =&gt; print("Anagrams found: ") val anagrams = source.getLines().filter(possibleAnagram =&gt; isAnagram(word, possibleAnagram)).toList println(anagrams match { case _ :: _ =&gt; anagrams.mkString(", ") case _ =&gt; "none" }) } } </code></pre> <p>MainTest.scala</p> <pre class="lang-scala prettyprint-override"><code>import org.scalatest.FunSuite import org.scalatest.prop.TableDrivenPropertyChecks class MainTest extends FunSuite with TableDrivenPropertyChecks { test("anagram") { val parametersTable = Table( ("listen", "silent"), ("stressed", "desserts"), ("Dusty", "Study") ) forAll (parametersTable) { (word: String, anagram: String) =&gt; assert(Main.isAnagram(word, anagram) === true) } } test("not an anagram") { val parametersTable = Table( ("listen", "desserts"), ("stressed", "silent"), ("testing", "study") ) forAll (parametersTable) { (word: String, anagram: String) =&gt; assert(Main.isAnagram(word, anagram) === false) } } } </code></pre> <p>Using <code>scalatest</code> library for writing the tests.</p> <p><strong>Stuff I considered when writing the code:</strong></p> <ul> <li>having data driven tests that cover all the basic corner cases</li> <li>performance - the data is read from the file and processed in a streaming fashion</li> <li>readability and conciseness - I tried to apply this as much as my Scala knowledge allowed me</li> </ul> <p><strong>Feedback I received from a third party:</strong></p> <p>Was told that this code is not good enough without getting any concrete explanation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T21:57:37.453", "Id": "440093", "Score": "0", "body": "Welcome to Code Review! Your question would benefit from an explanation of how you went about solving the problem (i.e. how your code works and perhaps why you did it that way)." } ]
[ { "body": "<p>I'm going to review your <code>Main</code> code and let someone else address the <code>Test</code> code.</p>\n\n<p>I'll start with a few minor issues.</p>\n\n<p>Breaking up long lines often makes them easier to scan/parse/comprehend.</p>\n\n<pre><code>def isAnagram(word: String, anagram: String) : Boolean =\n word.toLowerCase.toSeq.sorted.unwrap == anagram.toLowerCase.toSeq.sorted.unwrap\n</code></pre>\n\n<p>Also, you're using <code>.toSeq</code> to get to the non-deprecated <code>.sorted</code> method, but there's no reason to <code>.unwrap</code> it to get back to a <code>String</code>. The <code>==</code> comparison will work on a <code>WrappedString</code>.</p>\n\n<p><code>Using.apply()</code> returns a <code>Try[A]</code>, which your code ignores. If an exception is thrown (<code>words.txt</code> isn't where it should be?) then your app silently returns without reporting any errors. You might want to consider <code>Using.resource()</code> instead. It won't try to catch any exceptions.</p>\n\n<p>Using pattern matching just to determine if <code>anagrams</code> is populated or not seems a bit bizarre. In fact, it doesn't need to be a <code>List</code> at all.</p>\n\n<pre><code>val anagrams = source.getLines()\n .filter(isAnagram(word, _))\n .mkString(\", \")\n\nif (anagrams.isEmpty) println(\"none\")\nelse println(anagrams)\n</code></pre>\n\n<p>A big, <strong>big</strong>, problem with your algorithm is that the user-input, <code>word</code>, is processed for comparison (<code>toLowerCase</code> and <code>toSeq</code> and <code>sorted</code>) for <em>every</em> word in the dictionary. (<em>*Ouch!*</em>) It should only be done once.</p>\n\n<p>But my biggest issue with the design is your choice of user experience (UX). Prompting for user input has many pitfalls. I won't go into the whole rigamarole about using the IO monad in an FP context, instead I'll just point out that simplifying the user I/O can greatly enhance the app's utility.</p>\n\n<p>What if the user wants to count the number of anagrams for a given word? If your app had a small and simple usage profile (<code>usage: anagrams &lt;word&gt;</code>) then the task would be easy.</p>\n\n<pre><code>%%&gt; anagrams Star | wc -w\n5\n%%&gt;\n</code></pre>\n\n<p>From there you can imagine simple feature enhancements to make it more useful.</p>\n\n<pre><code>%%&gt; anagrams Star bets ENDING\nStar: arts, rats, tars, tsar\nbets: best\nENDING: ginned\n%%&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T22:31:23.907", "Id": "226530", "ParentId": "226459", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T20:57:55.890", "Id": "226459", "Score": "2", "Tags": [ "scala" ], "Title": "Return all anagrams for a word matched against a list of words in a file" }
226459
<p>In recent months I have been trying to figure out how in the world one can mimic the functionality of Excel's New <code>Dynamic Arrays</code> exclusively in <code>VBA</code>. There are tricky ways to do this using the window's API, (see <a href="http://mikejuniperhill.blogspot.com/2013/05/returning-dynamic-array-from-vba-udf.html" rel="nofollow noreferrer">this</a> link), and I have also found that one can utilize ADO with <code>Querytables</code> (see <a href="https://stackoverflow.com/questions/23433096/using-a-udf-in-excel-to-update-the-worksheet/56597968#56597968">this</a> link), which IMO, is a more stable implementation than using <code>Win 32</code> timers. However, both of these require external functions/libraries, and I wanted to find another way. I knew that spooky things happen when using VBA's <code>Evaluate</code> function, so I started piddling around with it here and there. I had some free time over the weekend and decided that I would test a bunch different ideas using <code>Evaluate</code>, when all of the sudden, it happened...it worked!</p> <p>What I have below is by no means the final product, nor is it pretty, but I was too excited to Not post it. </p> <p><strong>EDIT:</strong> @JonPeltier pointed out that <code>GetDynamicArray1D</code> was removing the last element of the array when sending it to the sheet, so I updated the <code>ArrayToSheet1D</code> to the following: </p> <pre><code>Private Sub ArrayToSheet1D(rngOut As Range, ByVal boolToRow As Boolean) 'if zero Based If LBound(arryVariant, 1) = 0 Then If boolToRow Then '1-D Arry to 1 Row rngOut.Resize(1, UBound(arryVariant, 1) + 1).Value2 = _ Application.Transpose(Application.Transpose(arryVariant)) Else '1-D Arry to 1 column rngOut.Resize(UBound(arryVariant, 1) + 1).Value2 = _ Application.Transpose(arryVariant) End If Else If boolToRow Then '1-D Arry to 1 Row rngOut.Resize(1, UBound(arryVariant, 1)).Value2 = _ Application.Transpose(Application.Transpose(arryVariant)) Else '1-D Arry to 1 column rngOut.Resize(UBound(arryVariant)).Value2 = _ Application.Transpose(arryVariant) End If End If End Sub </code></pre> <p>Everything else in the original code should stay the same. </p> <p><strong>Original Code:</strong></p> <pre><code>Option Explicit Private arryVariant As Variant Private Const ERROR_SPILL As String = "#SPILL" Public Function GetDynamicArray1D(ParamArray arrIn() As Variant) As Variant Dim strRangeFormulaOut As String, strRangeAddress As String If RngHasData(Application.Caller.Address, UBound(arrIn) + 1) Then GetDynamicArray1D = ERROR_SPILL: Exit Function arryVariant = CVar(arrIn) 'Remove the first value arryVariant = Filter(arryVariant, arryVariant(0), False) strRangeAddress = Application.Caller.Offset(1, 0).Address(False, False) strRangeFormulaOut = "ArrayToSheet1D(" &amp; strRangeAddress &amp; "," &amp; False &amp; ")" Evaluate strRangeFormulaOut GetDynamicArray1D = arrIn(0) End Function Public Function SortValues(ByVal rngIn As Range, ByVal lngColIndex As Long, _ Optional boolAscending As Boolean = True) As Variant Dim strRngAddressBelow As String, strRngAddressToRight As String Dim varValue As Variant, arryTopRow As Variant If RngHasData(Application.Caller.Address, rngIn.Rows.Count) Then SortValues = ERROR_SPILL: Exit Function arryVariant = rngIn.Value QuickSortArrAscDesc arryVariant, lngColIndex, , , boolAscending arryTopRow = Application.Index(arryVariant, 1, 0) 'get first value after sorting varValue = arryVariant(1, 1) arryTopRow = RemoveElementFromArray1D(arryTopRow, 1) arryVariant = DeleteRowFromArray(arryVariant, 1) strRngAddressBelow = Application.Caller.Offset(1, 0).Address(False, False) strRngAddressToRight = Application.Caller.Offset(0, 1).Address(False, False) Evaluate "ArrayToSheet2D(" &amp; strRngAddressBelow &amp; ")" arryVariant = arryTopRow Evaluate "ArrayToSheet1D(" &amp; strRngAddressToRight &amp; "," &amp; True &amp; ")" SortValues = varValue End Function 'Helper Functions Private Sub ArrayToSheet1D(rngOut As Range, ByVal boolToRow As Boolean) If boolToRow Then rngOut.Resize(1, UBound(arryVariant)).Value2 = Application.Transpose(Application.Transpose(arryVariant)) Else rngOut.Resize(UBound(arryVariant)).Value2 = Application.Transpose(arryVariant) End If End Sub Private Sub ArrayToSheet2D(rngOut As Range) rngOut.Resize(UBound(arryVariant, 1), UBound(arryVariant, 2)).Value2 = arryVariant End Sub Private Function StripText(ByVal strIn As String) As Long With CreateObject("vbscript.regexp") .Global = True .Pattern = "[^\d]+" StripText = CLng(.Replace(strIn, vbNullString)) End With End Function Private Function StripNumbers(ByVal strInPut As String, Optional ByVal strReplacementVal As String) As String With CreateObject("VBScript.RegExp") .Global = True .Pattern = "\d+" StripNumbers = .Replace(strInPut, strReplacementVal) End With End Function Private Function RemoveElementFromArray1D(ByRef arryIn As Variant, _ ByVal lngIndex As Long) As Variant Dim i As Long, k As Long Dim arryOut As Variant ReDim arryOut(LBound(arryIn) To (UBound(arryIn, 1) - 1)) For i = LBound(arryIn) To UBound(arryIn) If i &lt;&gt; lngIndex Then k = k + 1 arryOut(k) = arryIn(i) End If Next i RemoveElementFromArray1D = arryOut End Function Private Function DeleteRowFromArray(ByRef arryIn As Variant, _ ByVal lngRowIndex As Long) As Variant Dim i As Long, j As Long, k As Long Dim arryOut As Variant ReDim arryOut(LBound(arryIn, 1) To (UBound(arryIn, 1) - 1), _ LBound(arryIn, 2) To UBound(arryIn, 2)) For i = LBound(arryIn, 1) To UBound(arryIn, 1) If i &lt;&gt; lngRowIndex Then k = k + 1 For j = LBound(arryIn, 2) To UBound(arryIn, 2) arryOut(k, j) = arryIn(i, j) Next j End If Next i DeleteRowFromArray = arryOut End Function Private Function RngHasData(ByVal strCallerAddress As String, ByVal lngRowCount As Long) As Boolean Dim strSpillRng As String If lngRowCount = 1 Then Exit Function 'don't need to check strSpillRng = GetSpillRange(strCallerAddress, lngRowCount) If Application.CountA(ActiveSheet.Range(strSpillRng)) &gt; 0 Then RngHasData = True End Function Private Function GetSpillRange(ByVal strCallAddress As String, ByVal lngRowCount As Long) As String Dim strRangeBegin As String Dim lngStartRowBelow As Long, lngEndRowBelow As Long strRangeBegin = StripNumbers(CStr(Split(strCallAddress, ":")(0))) lngStartRowBelow = StripText(CStr(Split(strCallAddress, ":")(0))) + 1 lngEndRowBelow = lngStartRowBelow + lngRowCount - 2 GetSpillRange = strRangeBegin &amp; CStr(lngStartRowBelow) &amp; ":" &amp; strRangeBegin &amp; CStr(lngEndRowBelow) End Function 'Adapted From Nigel Heffernan's Post 'https://stackoverflow.com/questions/4873182/sorting-a-multidimensionnal-array-in-vba Public Sub QuickSortArrAscDesc(ByRef arrySource As Variant, ByVal lngSortCol As Long, _ Optional lngMin As Long = -1, _ Optional lngMax As Long = -1, _ Optional boolAscending As Boolean = True) Dim varPivot As Variant, i As Long, j As Long, lngColTemp As Long Dim arrRowTemp As Variant If IsEmpty(arrySource) Then Exit Sub If InStr(TypeName(arrySource), "()") &lt; 1 Then Exit Sub If lngMin = -1 Then lngMin = LBound(arrySource, 1) If lngMax = -1 Then lngMax = UBound(arrySource, 1) If lngMin &gt;= lngMax Then Exit Sub i = lngMin j = lngMax varPivot = Empty varPivot = arrySource(Int((lngMin + lngMax) / 2), lngSortCol) Do While i &lt;= j If boolAscending Then Do While arrySource(i, lngSortCol) &lt; varPivot i = i + 1 Loop Else Do While arrySource(i, lngSortCol) &gt; varPivot i = i + 1 Loop End If If boolAscending Then Do While arrySource(j, lngSortCol) &gt; varPivot j = j - 1 Loop Else Do While arrySource(j, lngSortCol) &lt; varPivot j = j - 1 Loop End If If i &lt;= j Then For lngColTemp = LBound(arrySource, 2) To UBound(arrySource, 2) arrRowTemp = arrySource(i, lngColTemp) arrySource(i, lngColTemp) = arrySource(j, lngColTemp) arrySource(j, lngColTemp) = arrRowTemp Next arrRowTemp = Empty i = i + 1 j = j - 1 End If Loop If lngMin &lt; j Then QuickSortArrAscDesc arrySource, lngSortCol, lngMin, j, boolAscending If i &lt; lngMax Then QuickSortArrAscDesc arrySource, lngSortCol, lngMax, j, boolAscending End Sub </code></pre> <p><strong>SortValues Example:</strong></p> <p><a href="https://i.stack.imgur.com/wEx1V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wEx1V.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/tHfWs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tHfWs.png" alt="enter image description here"></a></p> <p><strong>GetDynamicArray1D Example:</strong> </p> <p><a href="https://i.stack.imgur.com/7ZcdM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7ZcdM.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/6KPys.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6KPys.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T22:34:00.970", "Id": "440101", "Score": "1", "body": "While outputting a `#SPILL` string *looks* like the thing, I would recommend outputting an actual existing/supported `Error` type (e.g. `CVErr(xlErrValue)`), so that native functions like `IsError` still work correctly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T23:12:17.940", "Id": "440103", "Score": "0", "body": "So, IIUC, the functions return actual arrays that can be fed to array-accepting functions, correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T23:35:39.523", "Id": "440105", "Score": "0", "body": "Sortvalues can be fed a range, which is converted into an array, sorted, and then sent back to the sheet in the format needed. GetDynamicArray1d can be fed values in the formula arguments (not range) and it will also return an array to the sheet; it’s more so for proof of concept really." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T23:42:27.230", "Id": "440106", "Score": "1", "body": "I can't wait to play with it, wondering if e.g. INDEX could wrap SORTVALUES =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T23:57:21.120", "Id": "440110", "Score": "1", "body": "@MathieuGuindon If this can be object oriented, while at the same time implementing more error checking procedures, looking at formula precedent and dependent relationships, etc., some really cool stuff could be done with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T12:41:57.773", "Id": "440169", "Score": "0", "body": "Why does `GetDynamicArray1D` skip the last element of the array?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:42:37.733", "Id": "440199", "Score": "1", "body": "@JonPeltier Because the array is zero-based, range.resize is cutting off the last element. See my edit for details." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T19:31:46.087", "Id": "440254", "Score": "0", "body": "Minor thing but all the areas where you concatenate strings could be neatened up a fair bit with this lightweight [`printf` function](https://stackoverflow.com/a/17233834/6609896) - so `\"ArrayToSheet1D(\" & strRngAddressToRight & \",\" & True & \")\"` becomes `printf(\"ArrayToSheet1D({0},TRUE)\", strRngAddressToRight)` or `strRangeBegin & CStr(lngStartRowBelow) & \":\" & strRangeBegin & CStr(lngEndRowBelow)` to `printf(\"{0}{1}:{0}{2}\", strRangeBegin, lngStartRowBelow, lngEndRowBelow)`" } ]
[ { "body": "<h2>QuickSortArrAscDesc</h2>\n\n<p><code>QuickSortArrAscDesc</code> does not work if there are repeat values. Although there are clear improvements over the original, a couple of changes are causing the partitions from combing properly.</p>\n\n<p><strong>Current</strong></p>\n\n<blockquote>\n<pre><code> varPivot = arrySource(Int((lngMin + lngMax) / 2), lngSortCol)\n</code></pre>\n</blockquote>\n\n<p><strong>Original</strong></p>\n\n<blockquote>\n<pre><code> varMid = SortArray((lngMin + lngMax) \\ 2, lngColumn)\n</code></pre>\n</blockquote>\n\n<p>The Current code rounds of the index by surrounding it by <code>Int()</code>. e.g. <code>Array(...)(1.5)</code> returns the 3rd element where <code>Array(...)(Int(1.5))</code> will return the 2nd element. </p>\n\n<p><strong>Current</strong></p>\n\n<blockquote>\n<pre><code>If i &lt; lngMax Then QuickSortArrAscDesc arrySource, lngSortCol, lngMax, j, boolAscending\n</code></pre>\n</blockquote>\n\n<p><strong>Original</strong></p>\n\n<blockquote>\n<pre><code>If (i &lt; lngMax) Then Call QuickSortArray(SortArray, i, lngMax, lngColumn)\n</code></pre>\n</blockquote>\n\n<p>The Current code is testing <code>i</code> but passing <code>j</code> in as a parameter.</p>\n\n<blockquote>\n<pre><code>If boolAscending Then\n</code></pre>\n</blockquote>\n\n<p>This <code>If ...Else</code> clause was repeated twice which makes it difficult to compare the Ascending and Descending variations of the code. I also found that the original was easier to read because it keep the <code>&lt;&gt;</code> consistent between the <code>i</code> and <code>j</code> loops.</p>\n\n<h2>Refactored QuickSortArrAscDesc</h2>\n\n<pre><code>Public Sub ReversibleQuickSort(ByRef arrySource As Variant, ByVal lngSortCol As Long, _\n Optional lngMin As Long = -1, _\n Optional lngMax As Long = -1, _\n Optional boolAscending As Boolean = True)\n\n Dim varPivot As Variant, i As Long, j As Long, lngColTemp As Long\n Dim arrRowTemp As Variant\n\n If IsEmpty(arrySource) Then Exit Sub\n\n If InStr(TypeName(arrySource), \"()\") &lt; 1 Then Exit Sub\n\n If lngMin = -1 Then lngMin = LBound(arrySource, 1)\n\n If lngMax = -1 Then lngMax = UBound(arrySource, 1)\n\n If lngMin &gt;= lngMax Then Exit Sub\n\n i = lngMin\n j = lngMax\n\n varPivot = Empty\n varPivot = arrySource(((lngMin + lngMax) / 2), lngSortCol)\n\n Do While i &lt;= j\n If boolAscending Then\n Do While arrySource(i, lngSortCol) &lt; varPivot\n i = i + 1\n Loop\n Do While varPivot &lt; arrySource(j, lngSortCol)\n j = j - 1\n Loop\n Else\n Do While arrySource(i, lngSortCol) &gt; varPivot\n i = i + 1\n Loop\n Do While varPivot &gt; arrySource(j, lngSortCol)\n j = j - 1\n Loop\n End If\n\n If i &lt;= j Then\n For lngColTemp = LBound(arrySource, 2) To UBound(arrySource, 2)\n arrRowTemp = arrySource(i, lngColTemp)\n arrySource(i, lngColTemp) = arrySource(j, lngColTemp)\n arrySource(j, lngColTemp) = arrRowTemp\n Next\n arrRowTemp = Empty\n i = i + 1\n j = j - 1\n End If\n Loop\n\n If lngMin &lt; j Then ReversibleQuickSort arrySource, lngSortCol, lngMin, j, boolAscending\n If i &lt; lngMax Then ReversibleQuickSort arrySource, lngSortCol, i, lngMax, boolAscending\nEnd Sub\n</code></pre>\n\n<h2>Test</h2>\n\n<p>Test Data</p>\n\n<p><a href=\"https://i.stack.imgur.com/vOq0R.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vOq0R.png\" alt=\"Test Data\"></a></p>\n\n<p>Excuse the funky test code. It isn't pretty but it was effective. </p>\n\n<pre><code>Sub TestQuickSorts()\n\n Dim Values\n Dim items\n Values = [A2:C9]\n\n Debug.Print \"QuickSortArray Results\"\n [G2:I9].Clear: [g2].Formula = \"=SortValues(A2:C9,3)\"\n items = [I2:I9]\n items = WorksheetFunction.Transpose(items)\n Debug.Print \"Ascending: \"; Join(items)\n\n [G2:I9].Clear: [g2].Formula = \"=SortValues(A2:C9,3,False)\"\n items = [I2:I9]\n items = WorksheetFunction.Transpose(items)\n Debug.Print \"Descending: \"; Join(items)\n\n Debug.Print vbNewLine; \"ReversibleQuickSort Results\"\n ReversibleQuickSort Values, 3, , , True\n items = WorksheetFunction.Index(Values, 0, 3)\n items = WorksheetFunction.Transpose(items)\n Debug.Print \"Ascending: \"; Join(items)\n\n ReversibleQuickSort Values, 3, , , False\n items = WorksheetFunction.Index(Values, 0, 3)\n items = WorksheetFunction.Transpose(items)\n Debug.Print \"Descending: \"; Join(items)\n\nEnd Sub\n</code></pre>\n\n<h2>Results</h2>\n\n<p><a href=\"https://i.stack.imgur.com/i7iZK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/i7iZK.png\" alt=\"Immediate Window Results\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T11:23:31.160", "Id": "440654", "Score": "0", "body": "I caught the extra `If ...Else` a few minutes after I after I made the first edit, and I planned to make another edit, but work projects this week have held my mind hostage, so I completely forgot, lol! Excellent catch on the pivot calculation and on the recursive calls!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T13:49:21.413", "Id": "440675", "Score": "1", "body": "Thank you. Nice work! I know how much a pain it is to work with `Application.Caller`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-23T02:01:07.667", "Id": "226661", "ParentId": "226463", "Score": "3" } } ]
{ "AcceptedAnswerId": "226661", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T22:28:09.523", "Id": "226463", "Score": "6", "Tags": [ "array", "vba", "excel" ], "Title": "Excel's Dynamic Array Functions...In VBA (No Win 32)" }
226463
<p><strong>Part 1: General Cleanup</strong></p> <p><em>(Edit: Part 2 is <a href="https://codereview.stackexchange.com/questions/226786/work-order-spatial-query-part-2">here</a>.)</em></p> <hr> <p>I have a script in a <strong>Work Order Management System</strong> (<a href="https://www.ibm.com/products/maximo" rel="nofollow noreferrer">Maximo</a>) that performs a <strong><a href="https://stackoverflow.com/questions/56587515/maximo-spatial-query">spatial query</a></strong>.</p> <p>Details:</p> <ol> <li>Takes the X&amp;Y coordinates of a work order in Maximo</li> <li><a href="https://i.stack.imgur.com/dO2nk.png" rel="nofollow noreferrer">Generates a URL</a> from the coordinates (including other spatial query information)</li> <li>Executes the URL via a separate script/library (LIB_HTTPCLIENT)</li> <li>Performs a <strong>spatial query</strong> in an <a href="https://enterprise.arcgis.com/en/server/10.5/publish-services/windows/what-is-a-feature-service-.htm" rel="nofollow noreferrer">ESRI REST feature service</a> (a separate <a href="https://www.esri.com/en-us/arcgis/about-arcgis/overview" rel="nofollow noreferrer">GIS system</a>)</li> <li><a href="https://i.stack.imgur.com/xmJXS.png" rel="nofollow noreferrer">JSON text</a> is returned to Maximo with the attributes of the zone that the work order intersected</li> <li>The zone number is parsed from the JSON text via a separate script/library (LIB_PARSE_JSON)</li> <li>Inserts the zone number into the work order record</li> </ol> <hr> <p><strong>Jython main automation script</strong></p> <pre class="lang-python prettyprint-override"><code>from psdi.mbo import MboConstants from java.util import HashMap #Get the y and x coordinates(UTM projection) from the WOSERVICEADDRESS table via the SERVICEADDRESS system relationship #The datatype of the LatitydeY and LongitudeX is decimal: 1234567.8335815760, 123456.4075621164 #Convert the decimals to integers, and then strings, for the purpose of generating the URL (I don't think the URL can have decimal places) laty = str(mbo.getInt("SERVICEADDRESS.LatitudeY")) longx = str(mbo.getInt("SERVICEADDRESS.LONGITUDEX")) #Verify if the numbers are legitimate UTM coordinates if len(laty) == 7 and len(longx) == 6: #Assemble the URL (including the longx and the laty). Note: The coordinates are flipped in the url url="http://something.com/arcgis/rest/services/something/Zones/MapServer/15/query?geometry=" + longx + "%2C" + laty + "&amp;geometryType=esriGeometryPoint&amp;spatialRel=esriSpatialRelIntersects&amp;outFields=*&amp;returnGeometry=false&amp;f=pjson" #Get the JSON text from the feature service (the JSON text contains the zone value) ctx = HashMap() ctx.put("url",url) service.invokeScript("LIB_HTTPCLIENT",ctx) json_text = str(ctx.get("response")) #Parse the zone value from the JSON text ctx = HashMap() ctx.put("json_text",json_text) service.invokeScript("LIB_PARSE_JSON",ctx) parsed_val = str(ctx.get("parsed_val")) #Enter the zone value into the zone field in the work order mbo.setValue("DESCRIPTION","Waste Zone: "+parsed_val,MboConstants.NOACCESSCHECK) </code></pre> <p><strong>Jython library (LIB_HTTPCLIENT)</strong></p> <pre><code>from psdi.iface.router import HTTPHandler from java.util import HashMap from java.lang import String handler = HTTPHandler() map = HashMap() map.put("URL",url) map.put("HTTPMETHOD","GET") responseBytes = handler.invoke(map,None) response = String(responseBytes,"utf-8") </code></pre> <p><strong>JavaScript library (LIB_PARSE_JSON)</strong></p> <pre><code>#The field name (ZONE) is hardcoded. I'm not sure if this is best practice or not. var obj = JSON.parse(json_text); parsed_val = obj.features[0].attributes.ZONE </code></pre> <hr> <p>How can this code be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T01:04:30.337", "Id": "440111", "Score": "0", "body": "Jython... I know nothing about Maximo/PSDI but it already makes me sad. Are you able to use \"real Python libraries\" like Requests?" } ]
[ { "body": "<h2>Functions are your friend</h2>\n\n<p>Even in Jython, functions are a valid construct. They allow for scope, so that you can better reason about temporary variables; give better stack traces when things go wrong; increase testability; etc. So you should move your code into some functions.</p>\n\n<h2>Invert your logic</h2>\n\n<p>This:</p>\n\n<pre><code>if len(laty) == 7 and len(longx) == 6:\n</code></pre>\n\n<p>should probably be inverted, and something done about it, i.e.</p>\n\n<pre><code>if len(laty) != 7 || len(longx) != 6:\n # throw, or at least print...\n# continue on with the rest of the function\n</code></pre>\n\n<h2>If you had requests...</h2>\n\n<p>then this:</p>\n\n<pre><code>url=\"http://something.com/arcgis/rest/services/something/Zones/MapServer/15/query?geometry=\" + longx + \"%2C\" + laty + \"&amp;geometryType=esriGeometryPoint&amp;spatialRel=esriSpatialRelIntersects&amp;outFields=*&amp;returnGeometry=false&amp;f=pjson\"\n</code></pre>\n\n<p>could be fairly reduced in insanity. The query params can be formed as a dictionary passed to the <code>get</code> method.</p>\n\n<h2>PEP8</h2>\n\n<p>Use any kind of linter or modern IDE, and it will give you suggestions on how to reformat this thing to follow Python formatting standards (PEP8). The most obvious thing it will notice is lack of spaces after commas.</p>\n\n<p>Otherwise - perhaps you should provide some context about why this thing exists in Jython.</p>\n\n<h2>Suggested</h2>\n\n<p>I don't know whether this will work, because I don't have your setup; so you'll probably have to tweak it.</p>\n\n<pre><code>from psdi.mbo import MboConstants\nfrom java.util import HashMap\nfrom urllib import urlencode\nfrom urlparse import urlunparse, ParseResult\n\n\ndef get_coords():\n \"\"\"\n Get the y and x coordinates(UTM projection) from the WOSERVICEADDRESS table\n via the SERVICEADDRESS system relationship.\n The datatype of the LatitydeY and LongitudeX is decimal, i.e.\n 1234567.8335815760, 123456.4075621164.\n \"\"\"\n laty = mbo.getDouble(\"SERVICEADDRESS.LatitudeY\")\n longx = mbo.getDouble(\"SERVICEADDRESS.LONGITUDEX\")\n return laty, longx\n\n\ndef is_valid(laty, longx):\n \"\"\"\n Verify if the numbers are legitimate UTM coordinates\n \"\"\"\n return (0 &lt;= laty &lt;= 10e6 and\n 167e3 &lt;= longx &lt;= 833e3)\n\n\ndef make_url(laty, longx):\n \"\"\"\n Assemble the URL (including the longx and the laty). Note: The coordinates\n are flipped in the url\n \"\"\"\n\n query = {\n 'geometry': '%d,%d' % (laty, longx),\n 'geometryType': 'esriGeometryPoint',\n 'spatialRel': 'esriSpatialRelIntersects',\n 'outFields': '*', # You should narrow this if you only care about work zone.\n 'returnGeometry': 'false',\n 'f': 'pjson'\n }\n\n parts = ParseResult(scheme='http',\n netloc='something.com',\n path='/arcgis/rest/services/something/Zones/MapServer'\n '/15/query',\n query=urlencode(query),\n fragment='')\n\n url = urlunparse(parts)\n return url\n\n\ndef fetch_waste_zone(url):\n # Get the JSON text from the feature service (the JSON text contains the \n # zone value)\n ctx = HashMap()\n ctx.put(\"url\", url)\n service.invokeScript(\"LIB_HTTPCLIENT\", ctx)\n json_text = str(ctx.get(\"response\"))\n\n # Parse the zone value from the JSON text\n ctx = HashMap()\n ctx.put(\"json_text\", json_text)\n service.invokeScript(\"LIB_PARSE_JSON\", ctx)\n parsed_val = str(ctx.get(\"parsed_val\"))\n\n return parsed_val\n\n\ndef main():\n laty, longx = get_coords()\n if not is_valid(laty, longx):\n print('Invalid coordinates')\n return\n\n url = make_url(laty, longx)\n waste_zone = fetch_waste_zone(url)\n\n # Enter the zone value into the zone field in the work order\n mbo.setValue(\"DESCRIPTION\", \"Waste Zone: \" + waste_zone,\n MboConstants.NOACCESSCHECK)\n\n\nmain()\n</code></pre>\n\n<p>Note:</p>\n\n<ul>\n<li>There are functions</li>\n<li>The functions contain <code>\"\"\"docstrings\"\"\"</code> at the top</li>\n<li>You should preserve the UTM coordinates as doubles until it's necessary to format them as integers in the URL string</li>\n<li>UTM coordinates have real limits that you should use - not just string length</li>\n<li>Even if you don't have <code>requests</code>, you can still do somewhat saner query string formation via dictionary</li>\n<li>If the coordinates are invalid, do something - maybe print, definitely quit</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T01:43:37.017", "Id": "440115", "Score": "0", "body": "Good question! Rather than you, the developer, having to write out the long-form URL manually - including ampersands, escape characters if needed, etc., you compose a logic-friendly dictionary. This is more maintainable and less prone to error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T01:48:14.427", "Id": "440117", "Score": "0", "body": "Fine; but that doesn't mean that you can't write sub-routines (which you still should). Subroutines can still use global variables when needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T01:56:28.250", "Id": "440119", "Score": "4", "body": "It's not frowned upon, per se, but it's also not doing you any favours. I seem to remember Jython being stuck in a very old version of Python with fairly poor compatibility to external Python libraries, coupled with awkward access to Java constructs. As a small scripting language embedded in Java it's fine, but you're better to either go full Java or full Python, if you can." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T12:05:54.980", "Id": "440163", "Score": "0", "body": "I'll post an example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T12:35:26.927", "Id": "440167", "Score": "0", "body": "@User1973 edited" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T21:54:03.993", "Id": "440280", "Score": "0", "body": "Your suggestions are generally working great! Thanks! Unfortunately, I don't think I have the `urllib` or `urlparse` \n libraries available to me: https://www.ibm.com/developerworks/community/forums/html/topic?id=8fb23587-b670-4b62-82dd-8560d8398cae#repliesPg=0" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T22:44:20.007", "Id": "440284", "Score": "0", "body": "Because it doesn't require writing as many zeros." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-26T18:58:16.613", "Id": "441217", "Score": "0", "body": "I like many of these suggestions. However, regarding PEP8 and using python libraries, I recommend against these. Scripts run within Maximo, a COTS product, in a JVM, with access to hosts of Java libraries and Maximo's API. As such, and since most code will be interacting with APIs that follow Java formatting conventions, I recommend using Java conventions instead of mixing Java for APIs with python for script-local variables. For better interoperability/less \"surprises\" and not jeopardizing support, use the APIs already available instead of making available python ones which do the same." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T01:13:26.473", "Id": "226468", "ParentId": "226466", "Score": "5" } } ]
{ "AcceptedAnswerId": "226468", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T23:17:42.717", "Id": "226466", "Score": "6", "Tags": [ "python", "javascript", "json", "geospatial", "jython" ], "Title": "Work order spatial query (Part 1)" }
226466
<p>Here's a Quicksort I had fun writing and improving, so I thought I'd post it here. In my (brief) testing it's about 15% to 20% faster than Java's <code>Arrays.sort()</code>.</p> <p>The sort routine is a fairly vanilla Quicksort. The main improvements are to the pivot selection, and the Quicksort switches to an Insertion Sort for small sub arrays.</p> <p>The pivot selection is pretty basic. Mostly I just use more data points than "middle of three." Actually I call a "middle of three" algorithm three times, then I just take the middle of those points as a decent pivot. More samples means more chances of getting a good pivot for Quicksort, which helps it immensely.</p> <p>The other interesting idea in the pivot selection is which nine points to consider when taking the middle of three. I compute an offset to spread the points around more. Most data comes from an already sorted source. So sampling three points adjacent to each other might not actually sample random points. So I spread the offset throughout the array to try to obtain a better selection of input points.</p> <p>That's it, please enjoy.</p> <pre><code>package SimpleUtils.sort; import java.util.Comparator; /** Sort utilities. * * @author Brenden Towey */ public class Sort { /** * Sorts an array of Comparable. Null values are moved to the end of the * array by this routine, so arrays containing null values can be safely * sorted. * * @param &lt;T&gt; Any Comparable. * @param table The array to be sorted. * @return The number of non-null elements in the array. */ public static &lt;T extends Comparable&lt;? super T&gt;&gt; int sort( T[] table ) { int newLength = moveNullsToEnd( table ); quickSort( table, Comparator.naturalOrder(), 0, newLength - 1 ); return newLength; } /** * Moves null values to the end of an array. This is done in * preparation for sorting to remove nulls from the array. The * idea of moving nulls to the end of an array is synonymous with compacting * the array by moving all non-null elements to the beginning. * * &lt;p&gt;This method returns the number of non-null elements in the array. * The index of the last non-null element will be the one less than the * return value. * * @param table Table to move nulls to end. * @return The number of non-null elements. */ public static int moveNullsToEnd( Object[] table ) { int end = table.length-1; for( int i = 0 ;; ) { while( i &lt; table.length &amp;&amp; table[i] != null ) i++; if( i == table.length ) break; while( table[end] == null ) end--; if( i &lt; end ) { table[i] = table[end]; table[end] = null; } else break; } return end+1; } /** * A quicksort implementation for arrays. Null values are not checked by * this method. Therefore a "null safe" Comparator must be used, such * as {@code Comparator.nullsFirst()}, or the array range to be sorted * must be free of nulls. * * @param &lt;T&gt; Any type. * @param comp A Comparator for T. * @param table An array of T to sort. * @param first First element in the (sub) array to sort, inclusive. * @param last Last element in the (sub) array to sort, inclusive. */ public static &lt;T&gt; void quickSort( T[] table, Comparator&lt;T&gt; comp, int first, int last ) { // System.out.println( "first="+first+", last="+last+" table="+Arrays.deepToString( table ) ); // The value of INSERT is empirically determined. Basically smaller values // are assumed to be better, up to a point, then they get worse. // In testing, sort times are quite close, differing only by few // tens of milliseconds over one million elements. // 10 is used here as it "theorectically" should be good all other // things being equal, and its times were generally smaller than other // numbers, although only slightly. final int INSERT = 10; if( last - first &lt; INSERT ) insertionSort( table, comp, first, last ); else { int pivot = partition( table, comp, first, last ); quickSort( table, comp, first, pivot - 1 ); quickSort( table, comp, pivot + 1, last ); } } /** * A stable insertion sort. This routine does not check for nulls before * sorting. Therefore a "null-safe" comparator must be used, such as * {@code Comparator.nullsLast()}, or the array range must be free of * null values. * * @param &lt;T&gt; Any type. * @param table An array to be sorted. * @param comp A Comparator to use. * @param first The first element to sort, inclusive. * @param last The last element to sort, inclusive. * * @throws ArrayIndexOutOfBoundsException if either first or last are beyond the * bounds of the array table. * @throws NullPointerException if the array contains nulls and a "null-safe" * Comparator is not used. * * @throws NullPointerException if table or any element is null. */ public static &lt;T&gt; void insertionSort( T[] table, Comparator&lt;T&gt; comp, int first, int last ) { for( int i = first+1; i &lt; last+1; i++ ) { T temp = table[i]; int j = i-1; for( ; (j &gt;= 0) &amp;&amp; comp.compare( table[j], temp ) &gt; 0; j-- ) { table[j+1] = table[j]; } table[j+1] = temp; } } /** * Partition for quicksort. * * @param &lt;T&gt; Any type. * @param table An array to sort. * @param comp Comparator to use. * @param first Index of first element to sort, inclusive. * @param last Index of last element to sort, inclusive. * @return */ private static &lt;T&gt; int partition( T[] table, Comparator&lt;T&gt; comp, final int first, final int last ) { int pivotIndex = getPivotIndex( table, comp, first, last ); T pivot = table[ pivotIndex ]; swap( table, first, pivotIndex ); int lower = first+1; int upper = last; do { while( (lower &lt; upper) &amp;&amp; comp.compare( pivot, table[lower] ) &gt;= 0 ) lower++; while( comp.compare( pivot, table[upper] ) &lt; 0 ) upper--; if( lower &lt; upper ) swap( table, lower, upper ); } while( lower &lt; upper ); swap( table, first, upper ); return upper; } /** * Finds a pivot index by comparing up to nine values, to * determine the middle of those nine. * * @param &lt;T&gt; This works out to "anything that is Comparable" * @param table Array of Comparable. * @param first index of array to start looking for pivot. * @param last index of array of last value to consider for pivot. * @return The index of the pivot to use.s */ private static &lt;T&gt; int getPivotIndex( T[] table, Comparator&lt;T&gt; comp, int first, int last ) { int middle = (last+first) &gt;&gt;&gt; 1; // divide by 2 // if less than 9 total just return the middle one if( last - first &lt; 9 ) return middle; // compute an offset to create a wider range of values int offset = (last-first) &gt;&gt;&gt; 3; // divide by 8 // if 9 or more then we have nine values we can consider int mid1 = mid( table, comp, first, first + offset, first + offset * 2 ); int mid2 = mid( table, comp, middle - offset, middle, middle + offset ); int mid3 = mid( table, comp, last, last - offset, last - offset * 2 ); return mid( table, comp, mid1, mid2, mid3 ); } /** * Find the middle value out of three, for an array of Comparable. * * @param &lt;T&gt; Any type with a Comparator. * @param table A table of type T. * @param comp A Comparator for type T. * @param first index of first element to compare. * @param second index of second element to compare. * @param third index of third element to compare. * @return index of middle element. */ // package private for testing static &lt;T&gt; int mid( T[] table, Comparator&lt;T&gt; comp, int first, int second, int third ) { T firstv = table[first]; T secondv = table[second]; T thirdv = table[third]; // return (a &gt; b) ^ (a &gt; c) ? a : (a &gt; b) ^ (b &gt; c) ? c : b; boolean aGTb = comp.compare( firstv, secondv ) &gt; 0; boolean aGTc = comp.compare( firstv, thirdv ) &gt; 0; boolean bGTc = comp.compare( secondv, thirdv ) &gt; 0; return (aGTb ^ aGTc) ? first : (aGTb ^ bGTc) ? third : second; } /** * Swaps two references in an array. * * @param table Array to swap elements. * @param s1 index of first element to swap. * @param s2 index of second element to swap. * * @throws IndexOutOfBoundsException if either index is outside of the * bounds of the array. */ public static void swap( Object[] table, int s1, int s2 ) { Object temp = table[s1]; table[s1] = table[s2]; table[s2] = temp; } } </code></pre> <p><strong>Edit:</strong> I wanted to update this with new performance measurements. Regarding a suggestion:</p> <p><em>Postpone insertion sort until the recursive phase completes. The array now is "almost" sorted; each element is within k steps from its final destination. Insertion sorting the entire array is still O(Nk) (each element takes at most k swaps), but it is done in a single function invocation</em></p> <p>I tested this and got no improvement. In fact sort speed reduced considerably. As is, the quicksort above gives around 15% to 20% improvement over the built-in <code>Arrays.sort()</code>. By eliminating the call to the insertion sort and only calling it once at the very end of all partitions, speed improvement goes down to 7% to 0% or even a little less. So this turns out to be a mis-optimisation.</p> <p>What I think is going on is that the temporal locality of reference provided by various CPU hardware caches is providing non-linear preformance. Even though we did eliminate 100,000 method calls, those method calls were previously made with "fresh data" still in the cache. When the insertion sort is delayed until the very end of all partitioning, some of that data has gone "stale" and is no longer in the cache. It has to be re-fetched from main memory.</p> <p>I think it was Knuth who said to always test performance, and I think we've re-proven his admonishment here. Even though the optimization sounded good on paper, hardware provided non-linear performance which invalidated our simple intuitive analysis.</p>
[]
[ { "body": "<ul>\n<li><p>You may want to eliminate the tail call to quickSort (Java itself does not optimize tail recursion).</p>\n\n<p>Along the same line, it is beneficial to recur into a smaller partition, while looping over the larger one.</p></li>\n<li><p>Insertion sort implementation is suboptimal. The inner loop tests <em>two</em> conditions at each iteration. If you split the loop into two, depending on how <code>temp</code> compares to <code>table[0]</code>, each one needs to test only one condition. In pseudocode,</p>\n\n<pre><code> temp = table[i]\n if temp &lt; table[0]\n // table[i] will land at index 0. Don't bother testing values.\n for (j = i; j &gt; 0; --j)\n table[j] = table[j-1];\n else\n // table[0] is a natural sentinel. Don't bother testing indices.\n for (j = i; table[j - 1] &gt; temp; --j)\n table[j] = table[j-1];\n table[j] = temp;\n</code></pre></li>\n<li><p>Your setup allows one more quite subtle optimization. The insertion sorts are working on the <span class=\"math-container\">\\$\\frac{N}{k}\\$</span> arrays of <span class=\"math-container\">\\$k\\$</span> elements, resulting in <span class=\"math-container\">\\$O(Nk)\\$</span> time complexity. Postpone insertion sort until the recursive phase completes. The array now is \"almost\" sorted; each element is within <span class=\"math-container\">\\$k\\$</span> steps from its final destination. Insertion sorting the entire array is still <span class=\"math-container\">\\$O(Nk)\\$</span> (each element takes at most <span class=\"math-container\">\\$k\\$</span> swaps), but it is done in a single function invocation, rather than <span class=\"math-container\">\\$\\frac{N}{k}\\$</span> invocations your code makes.</p>\n\n<p>If you are sorting a million-strong array, this spares you 100000 function invocations.</p>\n\n<p>Besides, after the first <span class=\"math-container\">\\$k\\$</span> rounds, the minimal element is placed correctly, and you may fall into the unguarded branch unconditionally.</p></li>\n<li><p>I don't see how <code>last - first &lt; 9</code> may ever be true. The code never calls <code>partition</code> (and consequently <code>getPivotIndex()</code>) for the ranges that small. Since it is a private method, nobody else would call it either.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:06:51.933", "Id": "440187", "Score": "0", "body": "Thanks for the review! Regarding `last - first < 9`, it's there because I was experimenting with different values for `INSERT`. I can change `INSERT` to any value from 0 on up and the code still works. So `last - first < 9` just catches the condition where someone has changed the value of `INSERT`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:52:36.520", "Id": "440203", "Score": "0", "body": "Now you've got me looking at the insertion sort and I think `j >= 0` is a mistake. I should be comparing vs `first`, not 0. The code I wrote could advance `j` to values less than `first`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T16:29:48.020", "Id": "440534", "Score": "0", "body": "`Postpone insertion sort until the recursive phase completes.` Wow, that is a pretty cool optimization. I think I might have to actually test that out and see if there's speed improvements in the stress tester. Thanks for that!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-28T15:02:22.947", "Id": "441585", "Score": "0", "body": "I tested your suggestion to move the insertion sort to the end of the quicksort implementation, only calling it once instead of once per end of partition. The result was a slower sort time. I think that cache is providing non-linear performance, and delaying the insertion sort turns out to not be an optimization, unfortunately. See my updated question for a bit more info." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T05:00:05.700", "Id": "226472", "ParentId": "226467", "Score": "4" } }, { "body": "<h3>Formatting</h3>\n\n<p>In idiomatic java,</p>\n\n<ul>\n<li>curly braces go on the same line, not a newline</li>\n<li>optional curly braces are always used. This provides consistency and reduces the risk of forgetting to add them when refactoring.</li>\n<li>there is no whitespace after an <code>(</code> or before a <code>)</code></li>\n<li>there is whitespace after control flow keywords (<code>for</code>, <code>while</code>, etc)</li>\n<li>ALL_CAPS are used only for constant member variables</li>\n</ul>\n\n<h3>Readability</h3>\n\n<p>It would be preferable to use <code>final</code>where possible to clarify intent and improve readability.</p>\n\n<p>All your methods refer to a <code>T[]</code> as a \"table\", but arrays are not the same thing as tables.</p>\n\n<p>Don't use random abbreviations. Is a <code>comp</code> a <code>comparison</code> or a <code>Comparator</code>? I don't want to have to guess. Variables should clearly indicate what they hold. Something like <code>aGTb</code> is gibberish. Use a descriptive name.</p>\n\n<h3>Design</h3>\n\n<p>It's unclear to me that there's value in offering <code>sort</code>, given the existence of <code>Arrays.sort</code>.</p>\n\n<p>If you're trying to write a generally useful sorting class that provides some advantage over what already exists in the API, not supporting <code>List</code>s also seems like a major oversight.</p>\n\n<p>All your public methods throw a <code>NullPointerException</code> when the array or comparator parameters are <code>null</code>, and that's not documented anywhere. Either write a permissive library that can sort a <code>null</code> array (just return it), or document that you're going to fail-fast on <code>null</code> inputs. Failing fast on a null comparator is probably correct, but should be documented.</p>\n\n<p>Moving all the nulls to the end is an arbitrary decision. Clients should be able to pass in their own <code>Comparator</code> into <code>sort</code>. They can then decide how to handle nulls themselves.</p>\n\n<p>It's unclear to me that there's any performance benefit on sorting out the nulls first vs. doing it in the <code>Comparator</code>.</p>\n\n<p><code>moveNullsToEnd</code> and <code>swap</code> are both methods that act on an array, and have no special relationship to sorting algorithms. Either you don't want to expose them for use elsewhere, and they should be <code>private</code>, or you want to expose them and they should be in a different, more appropriate utility class.</p>\n\n<p>It would be preferable if all your methods used generics for consistency with the rest of the API, rather than switching back and forth between <code>Object</code> and <code>T</code>.</p>\n\n<p>If this is intended for real use, it would be nice to have multiple different methods with reasonable defaults, such as in <code>Arrays.sort()</code> and <code>Collections.sort()</code>.</p>\n\n<h3>Implementation</h3>\n\n<p>Since you're not promising a stable sort, <code>moveNullsToEnd</code> is way more complex than it needs to be. Walk the array once. Every time you see a null, swap it with the last non-null value. Alternately, if you want a stable sort in-place, walk the array once with two counters, a write index and a read index. Every time you see a null, increment the read an extra time. Otherwise, move from the read index to the write index. When read reaches the end, write nulls the rest of the way.</p>\n\n<p><code>moveNullsToEnd</code> fails on an array with only null elements.</p>\n\n<p>Don't leave commented-out code in your codebase. Use a logger if you need to and remove it.</p>\n\n<p>The <code>quickSort</code> method doesn't perform a quicksort, but rather an amalgam of quicksort and insertion sort. It's not by accident that the java library methods are labeled the generic <code>sort</code>. </p>\n\n<p><code>insertionSort</code> would be easier to read with a <code>while</code> loop and a decrement inside it, mostly due to the complex comparison which eats most of the <code>for</code> declaration. The <code>j--</code> gets lost at the end. Better from a performance standpoint would be @vnp's recommendation.</p>\n\n<p>I don't feel like getting too deep into the weeds of sorting implementations, so I'm going to leave it there. Below find stable and unstable implementations of <code>moveNullsToEnd</code>.</p>\n\n<pre><code>private static &lt;T&gt; int moveNullsToEndStable(final T[] array) {\n int writeIndex = 0;\n\n for (int readIndex = 0; readIndex &lt; array.length; readIndex++) {\n if (array[readIndex] == null) {\n continue;\n }\n array[writeIndex] = array[readIndex];\n writeIndex++;\n }\n\n final int returnValue = writeIndex;\n for ( ; writeIndex &lt; array.length; writeIndex++) {\n array[writeIndex] = null;\n }\n\n return returnValue;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:16:33.830", "Id": "440193", "Score": "2", "body": "I don't think your `moveNullsToEndUnstable` works. In the case where there's a null in the middle of the array and also at the end (`back`) then the first swap does nothing, leaving the array as it was. This would break the rest of the code and the constraint of actually moving nulls to the end. The second while loop in my version is there to find the first non-null element at the end of the array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:27:34.213", "Id": "440196", "Score": "0", "body": "@markspace Yes, that was an oversight. I corrected the posted code. Though it's now closer in visual complexity to your original, I still think there's value in not having nested loops." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:39:11.747", "Id": "440198", "Score": "2", "body": "Still doesn't work, unfortunately. Your code now finds the first non-null at the end of the array, but there's no guarantee that the value after that first non-null will also be non-null. For each null value found in the `front`, you must find a non-null to swap it with. The nested loops are required for correctness. (Part of the reason some of these routines are `public` is that I did test them rather extensively. Nested loops are required here, I'm pretty sure of that.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:48:52.347", "Id": "440202", "Score": "0", "body": "Yeah, on reflection, I believe you are correct. You always have to worry about null-null pairings. Boo!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:53:29.253", "Id": "440204", "Score": "0", "body": "Other than that sanfu, it was an good review. Thanks!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:07:23.507", "Id": "226490", "ParentId": "226467", "Score": "3" } }, { "body": "<p>I don't know how to read java code (I'm a python person), but reading your post, I have a few suggestions for you. (Sorry if you have already done these, as I've said I don't know java.)</p>\n<ol>\n<li>It sounds like you are doing median of 9 every single time. I'd suggest doing median of 3 if the list size is less than 128, and if it's between 128-8192, median of 9 (evenly spread out), and if the list size is greater than 8192, median of 27, or whatever odd number you like.\n<strong>EDIT</strong>: considering this again, I'd suggest you use bit_length instead. It adapts for much larger lists, and for smaller lists too.</li>\n<li>This might not be an improvement, but it's worth a try. If the pivot was horrible (the size of lst1 was more than 8x or less than 1/8 of the size of lst2), you can choose a random pivot instead. This will guarantee that you will not go to O(N^2) time.</li>\n<li>If you really care about improving your time, you can consider using sorting networks instead of insertion sort because they are up to 2x faster.</li>\n</ol>\n<p>That's it for now. I might edit it again later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T14:49:51.353", "Id": "508733", "Score": "0", "body": "Regarding using a median of 3 for sizes of 127 or less, or using a median of 27 for sizes over 8192: have you tested these ideas? Do they work? About what speed improvements do you measure?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:45:14.323", "Id": "508773", "Score": "0", "body": "Yes, I have tested these ideas. They do work, they gave me about a 5-10% improvement on my computer. However, I think using the median of [double length of binary representation of length of list minus 1] evenly spread out values in the list would be best. It adapts for different size lists without more if statements, and is quite simple." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-22T03:56:13.597", "Id": "257501", "ParentId": "226467", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-19T23:33:12.600", "Id": "226467", "Score": "9", "Tags": [ "java", "sorting" ], "Title": "Quicksort with Insertion Sort and Improved Pivot Selection" }
226467
<p>I initially started searching for a PHP script which would output PHP errors, to the JavaScript console. As the Default behaviour is just to spit them out anywhere and displace everything else. </p> <p>Although that was not successful, this is the code I have put together so far. Can anyone please review it and say if it can be shortened or optimized? The CSS Class I have added onto the errors just adds <code>position: relative</code> and a value in my external CSS file.</p> <p>=> ( Would be better to have position Absolute, but then all the errors overlap regardles of any breaks, n/ lines or PHP_EOL, may get changed to a float I'm not sure yet => They would be better because they don't take up any physical space or cause displacement).</p> <p>Sure this Can be shortened or optimized somehow. But PHP is not my strong point &amp; struggling.</p> <p>Are there any security issues with using this? Are they any errors in my Arrays? </p> <pre><code>&lt;?php // ::=&gt; ErrorHandler.php [File]; class MyError { protected static $collected = array(); public static function getCollectedErrors() { return self::$collected; } protected static function addError($key, $error) { if (!isset(self::$collected[$key])) self::$collected[$key] = array(); self::$collected[$key][] = $error; } // CATCHABLE ERRORS public static function captureNormal( $number, $message, $file, $line ) { // Insert all in one table $error = array( 'type' =&gt; $number, 'message' =&gt; $message, 'file' =&gt; $file, 'line' =&gt; $line ); // Display content $error variable self::addError('error', $message . " at " . $file . ':' . $line); } public static function captureException( $exception ) { // Display content $exception variable self::addError('exception', $exception); } // UNCATCHABLE ERRORS public static function captureShutdown( ) { $error = error_get_last( ); if( $error ) { ## IF YOU WANT TO CLEAR ALL BUFFER, UNCOMMENT NEXT LINE: # ob_end_clean( ); // Display content $error variable self::addError('shutdown', $error); } else { self::addError('shutdown', '&lt;none&gt;'); return true; } } } set_error_handler(array( 'MyError', 'captureNormal' )); set_exception_handler(array( 'MyError', 'captureException' )); register_shutdown_function(array( 'MyError', 'captureShutdown' )); ?&gt; </code></pre> <p>&amp; in my index &amp; sub-pages =></p> <pre><code>&lt;?php // &gt;&gt;&gt;&gt;&gt;&gt;&gt; Add if Admin Statement in Here &amp; Password Match &amp; Cookie, csrf check. $errors = MyError::getCollectedErrors(); // This is Linked to ErrorHandlers.php foreach ($errors as $category =&gt; $items) { echo "&lt;strong class=\"dispLow\" style=\"display:block; position:relative; max-width:248px; text-wrap:wrap; z-index:2000; background:yellow;\"&gt;" . $category . ": &lt;/strong&gt;&lt;br/&gt;"; // I added class dispLow to the outputted errors with \ escape... foreach ($items as $error) { echo "&lt;br&gt;Error:" . $error . $catergory . $items . $file . $line . "&lt;br/&gt;" .PHP_EOL; } } ?&gt; </code></pre> <p><em>Related Questions I could find:</em></p> <p><strong>>></strong> <a href="https://codereview.stackexchange.com/questions/61624/error-handler-in-php?rq=1">Php Error Handler/Logger</a><br> <strong>>></strong> <a href="https://stackoverflow.com/questions/30357773/how-to-echo-or-print-to-the-js-console-with-php">Echo to Console</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T07:04:15.553", "Id": "466245", "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)*. Please post a new question instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-22T08:09:40.353", "Id": "466249", "Score": "0", "body": "Try tracy debug panel" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T01:40:15.873", "Id": "466334", "Score": "0", "body": "@Mast If I post a New question with The Exact same code it will just get deleted as a duplicate, I only edited the question to remove some of the whitespace & fix the indentation issus, So that it is more legible for other people viewing this post? Is that not allowed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T01:40:38.910", "Id": "466335", "Score": "0", "body": "@slepic is this available for firefox?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-02-23T07:06:20.273", "Id": "466342", "Score": "0", "body": "So don't post a new question with the exact same code. Use the current reviews to improve the code and *then* post a new question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-13T13:38:15.463", "Id": "468355", "Score": "0", "body": "https://craig.is/writing/chrome-logger does what you're looking for" } ]
[ { "body": "<p>First off I must say that the indentation is quite inconsistent and makes reading this code challenging. While most of the inconsistencies appear to be indentation on braces, the indentation on comments also seems a bit wonky. While I don't adhere to everything in it, I suggest following <a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PSR-2</a> - especially using 4 spaces for indentation. </p>\n\n<p>One thing I observed in the sample usage code is that <code>$file</code> and <code>$line</code> are <code>NULL</code>. Perhaps you were intending to use those from the array <code>$error</code>. I also noticed <code>captureNormal()</code> stores an array in the variable <code>$error</code> but that doesn't appear to be used after it is declared (despite the comment on the next line: <code>Display content $error variable</code>). Maybe you took the usage of <code>$error</code> out of that static method and moved it into the other file?</p>\n\n<blockquote>\n<pre><code>public static function captureNormal( $number, $message, \n $file, $line )\n {\n // Insert all in one table\n $error = array( 'type' =&gt; $number, \n 'message' =&gt; $message, \n 'file' =&gt; $file, \n 'line' =&gt; $line \n );\n // Display content $error variable\n self::addError('error', $message . \" at \" . $file . \n ':' . $line);\n }\n</code></pre>\n</blockquote>\n\n<p>To avoid the need to escape double quotes in the HTML, you could use a different delimiting method like <a href=\"https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc\" rel=\"nofollow noreferrer\">heredoc</a> or <a href=\"https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc\" rel=\"nofollow noreferrer\">nowdoc</a>. And perhaps it would be simpler to move the styles into CSS.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-09T20:17:09.097", "Id": "227740", "ParentId": "226473", "Score": "2" } }, { "body": "<p>Fixing the white space alone will improve readability.</p>\n\n<p>Use private variables instead of protected when you don't plan to use the variable in an extended class.</p>\n\n<p>Use curly braces even when the executed code is only one line long.</p>\n\n<p>If you want to display the errors in a console, you can use <code>console.log</code> inside of a <code>&lt;script&gt;</code>. Such as this:</p>\n\n<pre><code>$errorMessage;\n\nforeach ($items as $error) \n{\n $errorMessage .= \"Error:\" . $error . $catergory . \n $items . $file .\n $line . \"\\n\";\n}\n\necho \"&lt;script&gt; console.log('\" . $errorMessage . \"'); &lt;/script&gt;\";\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-11T00:51:31.463", "Id": "227822", "ParentId": "226473", "Score": "4" } }, { "body": "<ul>\n<li>As others have mentioned, your tabbing has quite the negative impact on readability.</li>\n<li>As dusty stated, you can safely declare <code>$collection</code> as <code>private</code>.</li>\n<li>There is no reason to check if the <code>$collected</code> class object is declared or if the designated <code>$key</code> exists before pushing an element into it. Just push that sucker in there!</li>\n<li>In <code>captureShutdown()</code> method there is some redundant scripting which can be easily cleaned up with the coalescing operator like this: <code>self::addError('shutdown', error_get_last() ?? '&lt;none&gt;');</code>. You are declaring a <code>return</code> value, but the static call is not doing anything with it -- so it can be omitted.</li>\n<li>On second thought, I actually don't like the fact that sometimes the <code>captureShutdown()</code> method conditionally passes a string or an array as the second parameter of <code>addError</code>. I would prefer this class to generate consistently typed items in <code>$collected</code> so that pumping the data into the view is cleaner. For those who are not instantly aware, <a href=\"https://www.php.net/manual/en/function.error-get-last.php\" rel=\"nofollow noreferrer\">error_get_last()</a> returns <code>null</code> or an array with the keys: <code>type</code>, <code>message</code>, <code>file</code> and <code>line</code>. Instead of <code>error_get_last() ?? '&lt;none&gt;'</code>, maybe it would be better to craft a very human/English string for either outcome.</li>\n</ul>\n\n<p>Your class: </p>\n\n<pre><code>class MyError\n{\n private static $collected = [];\n\n public static function getCollectedErrors()\n {\n return self::$collected;\n }\n\n private static function addError($key, $error)\n {\n self::$collected[$key][] = $error;\n }\n\n public static function captureNormal($number, $message, $file, $line)\n {\n self::addError('error', \"{$number}: {$message} at {$file}:{$line}\");\n }\n\n public static function captureException($exception) \n {\n self::addError('exception', $exception);\n }\n\n public static function captureShutdown()\n {\n // self::addError('shutdown', error_get_last() ?? '&lt;none&gt;');\n $lastError = error_get_last();\n if ($lastError) {\n $message = \"{$lastError['type']}: {$lastError['message']}\"\n . \" at {$lastError['file']}:{$lastError['line']}\";\n } else {\n $message = \"No errors present at shutdown\";\n }\n self::addError('shutdown', $message);\n }\n}\n\nset_error_handler(['MyError', 'captureNormal']);\nset_exception_handler(['MyError', 'captureException']);\nregister_shutdown_function(['MyError', 'captureShutdown']);\n</code></pre>\n\n<ul>\n<li>I have concerns about your mixing of strings and array in the <code>echo</code> of your inner <code>foreach()</code> -- that can't be working out well.</li>\n<li>Move all of your inline styles to an external stylesheet to make the markup more readable.</li>\n</ul>\n\n<p>Your content:</p>\n\n<pre><code>$errors = MyError::getCollectedErrors();\n$messages = '';\nforeach ($errors as $category =&gt; $message) {\n $messages .= \"&lt;div&gt;&lt;h3 class=\\\"category\\\"&gt;{$category}&lt;/h3&gt;\";\n $messages .= '&lt;div&gt;' . implode('&lt;/div&gt;&lt;div&gt;', $message) . '&lt;/div&gt;&lt;/div&gt;';\n}\nif ($messages) {\n echo '&lt;div id=\"draggableErrorModal\"&gt;\n &lt;div id=\"draggableErrorModalHeader\"&gt;\n Draggable Error Modal\n &lt;/div&gt;\n &lt;div id=\"draggableErrorModalClose\"&gt;&amp;times;&lt;/div&gt;\n &lt;div id=\"draggableErrorModalBody\"&gt;' . $messages . '&lt;/div&gt;\n &lt;/div&gt;';\n}\n</code></pre>\n\n<p>Okay, I whipped up a basic modal with a few little UX niceties via pure javascript and css such as the ability to be dragged, resized, and closed so that the notification is always in your face but also very easy to tuck away to reveal the page content. You can style it to your heart's content. Have a play.</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>if (document.getElementById(\"draggableErrorModal\")) {\n document.getElementById(\"draggableErrorModalClose\").addEventListener('click', function(){\n document.getElementById(\"draggableErrorModal\").style.display = 'none';\n });\n \n dragElement(document.getElementById(\"draggableErrorModal\"));\n\n function dragElement(errorModal) {\n let pos1 = 0,\n pos2 = 0,\n pos3 = 0,\n pos4 = 0;\n \n document.getElementById(errorModal.id + \"Header\").onmousedown = dragMouseDown;\n\n function dragMouseDown(e) {\n e = e || window.event;\n e.preventDefault();\n // get the mouse cursor position at startup:\n pos3 = e.clientX;\n pos4 = e.clientY;\n document.onmouseup = closeDragElement;\n // call a function whenever the cursor moves:\n document.onmousemove = elementDrag;\n }\n\n function elementDrag(e) {\n e = e || window.event;\n e.preventDefault();\n // calculate the new cursor position:\n pos1 = pos3 - e.clientX;\n pos2 = pos4 - e.clientY;\n pos3 = e.clientX;\n pos4 = e.clientY;\n // set the element's new position:\n errorModal.style.top = (errorModal.offsetTop - pos2) + \"px\";\n errorModal.style.left = (errorModal.offsetLeft - pos1) + \"px\";\n }\n\n function closeDragElement() {\n // stop moving when mouse button is released:\n document.onmouseup = null;\n document.onmousemove = null;\n }\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#draggableErrorModal {\n position: absolute;\n z-index: 9;\n background-color: white;\n border: 1px solid #ff5500;\n top: 0;\n left: 0;\n resize: both;\n overflow: auto;\n}\n\n#draggableErrorModalHeader {\n padding: 10px;\n text-align: center;\n cursor: move;\n background-color: lightgrey;\n color: #ff8800;\n}\n\n#draggableErrorModalClose {\n position: absolute;\n z-index: 10;\n top: 2px;\n right: 4px;\n font-size: 30px;\n cursor: pointer;\n}\n\n#draggableErrorModalBody {\n padding: 20px;\n}\n\n#draggableErrorModalBody div:nth-child(odd) {\n background-color: #efefef;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;body&gt;\n&lt;div class=\"regularContent\"&gt;content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content content&lt;/div&gt;\n&lt;div id=\"draggableErrorModal\"&gt;\n &lt;div id=\"draggableErrorModalHeader\"&gt;\n Draggable Error Modal\n &lt;/div&gt;\n &lt;div id=\"draggableErrorModalClose\"&gt;&amp;times;&lt;/div&gt;\n &lt;div id=\"draggableErrorModalBody\"&gt;\n &lt;div&gt;Message 1: This is where your&lt;br&gt;errors will be.&lt;/div&gt;\n &lt;div&gt;Message 2: This is where your errors will be.&lt;/div&gt;\n &lt;div&gt;Message 3: Your errors will be here and the modal can be resized and closed entirely.&lt;/div&gt;\n &lt;div&gt;Message 4: This is where your&lt;br&gt;errors will be.&lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;/body&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-03-13T12:53:57.253", "Id": "238824", "ParentId": "226473", "Score": "3" } } ]
{ "AcceptedAnswerId": "238824", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T05:46:32.873", "Id": "226473", "Score": "4", "Tags": [ "php", "object-oriented", "css", "error-handling" ], "Title": "PHP display Error Wanings Yellow @ bottom of Page with PHP_EOL" }
226473
<p>I use this function to to do some calculations based on 4 select inputs and one number input, I don't have experience in Js, I did some research in w3schools then I ended up with the function below. The Js function is working exactly as I want, but I feel it is not the perfect syntax and it could be shorter and somehow cleaner, any advice would be appreciated.</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>function calculate() { var x = parseFloat(document.getElementById("Lang_from").value); var y = parseFloat(document.getElementById("Lang_to").value); var q = parseFloat(document.getElementById("quantity").value); var s = parseFloat(document.getElementById("subject").value); var f = parseFloat(document.getElementById("file_type").value); var xx = document.getElementById('Lang_from').selectedOptions[0].text; var yy = document.getElementById('Lang_to').selectedOptions[0].text; var ff = document.getElementById('file_type').selectedOptions[0].text; var ss = document.getElementById('subject').selectedOptions[0].text; document.getElementById("total_price").innerHTML = (x + y) * q + (s + f); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"&gt; &lt;html&gt; &lt;body&gt; &lt;div class="pricing_row"&gt; &lt;div class="pricing_column"&gt; &lt;div class="form-group"&gt; &lt;h4 class="pricing_lable"&gt;From&lt;/h4&gt; &lt;select id="Lang_from" name="Lang_from" value="" class="form-control pricing_input"&gt; &lt;option id="en2ar" value="0.025"&gt;English&lt;/option&gt; &lt;option&gt;German&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;h4 class="pricing_lable"&gt;To&lt;/h4&gt; &lt;select id="Lang_to" name="Lang_to" value="" class="form-control pricing_input"&gt; &lt;option value="0.025"&gt;German&lt;/option&gt; &lt;option&gt;English&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="pricing_column"&gt; &lt;div class="form-group"&gt; &lt;h4 class="pricing_lable"&gt;File type&lt;/h4&gt; &lt;select id="file_type" name="file_type" value="" class="form-control pricing_input"&gt; &lt;option value="0"&gt;TXT&lt;/option&gt; &lt;option value="3"&gt;MS word&lt;/option&gt; &lt;option value="5"&gt;PDF (+5$)&lt;/option&gt; &lt;option value="10"&gt;Hand Writing&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;h4 class="pricing_lable"&gt;Subject&lt;/h4&gt; &lt;select id="subject" name="subject" value="" class="form-control pricing_input"&gt; &lt;option value="0"&gt;General&lt;/option&gt; &lt;option value="10"&gt;Technical / IT&lt;/option&gt; &lt;option value="15"&gt;Medical&lt;/option&gt; &lt;option value="5"&gt;Press&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="pricing_column"&gt; &lt;div class="form-group"&gt; &lt;h4 class="pricing_lable"&gt;Word count&lt;/h4&gt; &lt;input type="number" id="quantity" name="quantity" min="500" value="1000" class="form-control pricing_input pricing_input_number"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;button id="calculate" type="button" class="btn btn-primary pricing_btn_calc" onclick="calculate()"&gt;Calculate&lt;/button&gt; &lt;div id="total_price"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T16:42:38.717", "Id": "440224", "Score": "0", "body": "Just a quick tip that using [destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) with the [HTMLFormElement API](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement) can shorten code (i.e. `const [from, to, fileType, subject, quantity] = Array.from(form.elements).map(el => Number(el.value))` where `form` is a reference to a `<form>` element, which would be the appropriate semantic element for user input controls." } ]
[ { "body": "<h3>Access elements via ID</h3>\n\n<p>You can get access to elements directly via their ID, if you ensure that each elements <code>id</code> and or <code>name</code> is unique withing the page and JavaScripts global scope.</p>\n\n<pre><code>var x = parseFloat(document.getElementById(\"Lang_from\").value);\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>var x = parseFloat(Lang_from.value);\n</code></pre>\n\n<p>In the example at the bottom I have removed all the names from the HTML. You have not indicated that this is a submit-able form and thus you can do without the extra markup.</p>\n\n<p><strong>Note</strong> that forms do provide additional information for clients with special needs. For content that faces the world (public) always consider <a href=\"https://developer.mozilla.org/en-US/docs/Learn/Accessibility\" rel=\"nofollow noreferrer\">Accessibility</a>. Dealing with font end interaction (not using forms) you should be familiar with <a href=\"https://developer.mozilla.org/en-US/docs/Learn/Accessibility/WAI-ARIA_basics\" rel=\"nofollow noreferrer\">WAI-ARIA</a> and how it makes content meaningful and accessible to everyone .</p>\n\n<h3>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"nofollow noreferrer\"><code>Number</code></a> rather than <code>parseFloat</code></h3>\n\n<p>Rather than use <code>parseFloat</code> use <code>Number</code> to convert a string number to a Number type</p>\n\n<pre><code>var x = parseFloat(Lang_from.value);\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>var x = Number(Lang_from.value);\n</code></pre>\n\n<p>or you can coerce a string representing a number using an operator. Commonly <code>+</code> is used</p>\n\n<pre><code>var x = + Lang_from.value;\n</code></pre>\n\n<p>JavaScripts has automatic <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Type_coercion\" rel=\"nofollow noreferrer\">type coercion</a> and will force the string to a number, Note that + will not work as <code>var x = \"10\" + Lang_from.value;</code> as the type is set by \"10\" and <code>+</code> can operate on strings (concats)</p>\n\n<h3>Define appropriate variable types</h3>\n\n<p>The variables you use are never modified. JS has several variable types. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var\" rel=\"nofollow noreferrer\"><code>var</code></a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\"><code>let</code></a>, and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a>. Get in a habit of using the most appropriate type, for variables that do not change or should not change use <code>const</code></p>\n\n<pre><code>const x = +Lang_from.value;\n</code></pre>\n\n<h3>Naming is an important programming skill to master</h3>\n\n<p>Always pay special care to the names you use.</p>\n\n<p>Some of your variable names have absolutely no relationship to their content (eg <code>x</code>, <code>y</code>, and maybe <code>f</code>) </p>\n\n<p>Using abbreviations is OK and can reduce clutter, using the first letter of each word in the ID is OK (BUT DEFINING NAME and USING NAME must be no more than a page of apart, as the need to hunt for meaning is a distraction that aids bugs getting in)</p>\n\n<pre><code>const lf = +Lang_from.value;\nconst lt = +Lang_to.value;\nconst q = +quantity.value;\nconst s = +subject.value;\nconst ft = +file_type.value;\n</code></pre>\n\n<h3>Avoid intermediates if possible</h3>\n\n<p>Rather than the many names, calculate the <code>total</code> as you access the data.</p>\n\n<pre><code>var total = (+Lang_from.value) + (+Lang_to.value); // The extra + to coerce to number\ntotal *= quantity.value; // *= same as total = total * quantity.value;\n // The extra + not ended if the operation on the value is\n // not +\ntotal += +subject.value;\ntotal += +file_type.value;\n</code></pre>\n\n<h3>NO! don't do this... <code>&lt;button onclick=\"functionName()\"&gt;</code></h3>\n\n<p>Avoid putting code within the markup. The event listener for <code>calculate</code> should be added via JavaScript when the page has loaded. Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload\" rel=\"nofollow noreferrer\"><code>\"load\"</code></a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event\" rel=\"nofollow noreferrer\"><code>\"DOMContentLoaded\"</code></a> events </p>\n\n<pre><code>addEventListener(\"load\", function() { // waits for the page to load\n calculate.addEventListener(\"click\", calculateTotal);\n});\n\n// or using arrow function and a slightly earlier event that fires when \n// all the HTML content has loaded and been parsed (image and the like may not be ready)\naddEventListener(\"DOMContentLoaded\", () =&gt; { // waits for the page to load\n calculate.addEventListener(\"click\", calculateTotal);\n});\n\n\n// NOTE that the element id is calculate which conflicted with the JavaScript function \n// name calculate. I renamed the function to calculateTotal ( which I would have done\n// even if there was no name conflict)\n</code></pre>\n\n<h3>Loose ends are bad practice</h3>\n\n<p>Keep the code clean and do not include code that has no purpose. You have 5 variables that get the selections yet you don't use them. They should not be in the function. If you put them their because you intend to use them at another time, finish the code or add a comment with that code eg <code>/* Todo: Show selection names */</code> else the code is considered incomplete (easy to forget or worse)</p>\n\n<h3>Use appropriate properties</h3>\n\n<p>When adding content to an element and it is just text (no HTML content) use the node property <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent\" rel=\"nofollow noreferrer\"><code>Node.textContent</code></a> to set the text. (Elements inherit properties from Node so can be used on most elements)</p>\n\n<h2>Example</h2>\n\n<h3>Basic Markup only</h3>\n\n<p>I have removed all irrelevant information from the Markup, (forms, styling wrappers, name/id duplicates, property duplicates, class name)</p>\n\n<p>I removed the references to the CSS styles. Looking good is important, but start at the core and work up, don't start with looking good, that is why we have CSS, to seperate the two.</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>\"use strict\";\naddEventListener(\"DOMContentLoaded\", () =&gt; {\n calculate.addEventListener(\"click\", calculateTotal);\n});\n\nfunction calculateTotal() {\n var total = (+Lang_from.value) + (+Lang_to.value); \n total *= quantity.value; \n total += (+subject.value) + (+file_type.value);\n total_price.textContent = \"$\" + total.toFixed(2);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;h4&gt;From&lt;/h4&gt;\n&lt;select id=\"Lang_from\"&gt;\n &lt;option value=\"0.025\"&gt;English&lt;/option&gt;\n &lt;option&gt;German&lt;/option&gt;\n&lt;/select&gt;\n&lt;h4&gt;To&lt;/h4&gt;\n&lt;select id=\"Lang_to\"&gt;\n &lt;option value=\"0.025\"&gt;German&lt;/option&gt;\n &lt;option&gt;English&lt;/option&gt;\n&lt;/select&gt;\n&lt;h4&gt;File type&lt;/h4&gt;\n&lt;select id=\"file_type\"&gt;\n &lt;option value=\"0\"&gt;TXT&lt;/option&gt;\n &lt;option value=\"3\"&gt;MS word&lt;/option&gt;\n &lt;option value=\"5\"&gt;PDF (+5$)&lt;/option&gt;\n &lt;option value=\"10\"&gt;Hand Writing&lt;/option&gt;\n&lt;/select&gt;\n&lt;h4&gt;Subject&lt;/h4&gt;\n&lt;select id=\"subject\"&gt;\n &lt;option value=\"0\"&gt;General&lt;/option&gt;\n &lt;option value=\"10\"&gt;Technical / IT&lt;/option&gt;\n &lt;option value=\"15\"&gt;Medical&lt;/option&gt;\n &lt;option value=\"5\"&gt;Press&lt;/option&gt;\n&lt;/select&gt;\n&lt;h4&gt;Word count&lt;/h4&gt;\n&lt;input type=\"number\" id=\"quantity\" min=\"500\" value=\"1000\"&gt;\n&lt;button id=\"calculate\"&gt;Calculate&lt;/button&gt;\n&lt;h4&gt;Total price&lt;/h4&gt;\n&lt;div id=\"total_price\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h3>Beginners note</h3>\n\n<p>You will notice the string <code>\"use strict\";</code> at the top of the JavaScript, it is a directive that forces JavaScript to run in <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/strict_mode\" rel=\"nofollow noreferrer\">strict mode</a>. </p>\n\n<p>The name may suggest this is something for experienced coders, quite the contrary as experienced JS coders seldom make the errors this will trap. </p>\n\n<p>Experienced JS coders always use strict mode because its faster and because everyone make mistakes.</p>\n\n<p>Ergo: Always run your javascript in strict mode using the directive \"use strict\";</p>\n\n<h3>This example has no semantic meaning to some</h3>\n\n<p>I have not used ARIA to add semantic meaning to the content as I do not think its applicable in this case and would make for a way too long already too long answer.</p>\n\n<h3>Slight change to result</h3>\n\n<p>I noted that the <code>quantity</code> input is unconstrained in its precision (Allows fractions). When you output values, especially monetary values, be careful to include the correct rounding and precision. A money value ideally always starts with the currency type (I used $ and the value is written with full precision Dollars.Cents eg $10.00. </p>\n\n<p>JavaScripts Number (floating point double) is only an approximation of numbers, in a few calculation a number can easily gain a rounding error and just display the value raw will end you with displayed values like <code>10.00000000000003</code> or <code>3e-17</code> both not good things to show when it involves money,</p>\n\n<h2>References</h2>\n\n<p>The site you used as a reference has a bad wrap, being incomplete and out of date, Though it has been years since I have had a good look, so if this remains true I am unsure.</p>\n\n<p>I better reference site is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript\" rel=\"nofollow noreferrer\">MDN JavaScript</a> and the main landing <a href=\"https://developer.mozilla.org/en-US/\" rel=\"nofollow noreferrer\">MDN</a> it has a mostly complete reference of Web technologies, plenty of learning resources (tutorials, examples and the like), and if you need to get to the definitive resource they do provide links to the all the standards documentation (Very dry and hard to read resource of everything) that is applicable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T13:14:00.980", "Id": "226488", "ParentId": "226482", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T09:35:43.603", "Id": "226482", "Score": "1", "Tags": [ "javascript", "beginner" ], "Title": "Javascript calculation function" }
226482
<p>I need to generate a lot of pseudo-random numbers in my software. I'm trying to create a elegant (syntax-wise) and performant class that would allow me to generate such numbers and perform other random-related stuff (like shuffling an array). I decided to "cache" a generator for each thread and expose the methods of this cached instance through static methods.</p> <p>Can you please review the following implementation? I tried to achieve the following objectives:</p> <ol> <li>Make it thread safe</li> <li>Make it convenient to use / call</li> <li>Make it performant</li> </ol> <p>I only add xmldocs to my code after I'm satisfied with the implementation, so it's not necessary to point out that the class is lacking documentation, I will do it later. But if you believe there is a important detail that should be documented, by all means, do point it out.</p> <p>About the random-labels method: it was originally called <code>Bools(int count)</code>, but considering the context in which it is used, I decided to renamed it.</p> <pre><code>namespace Minotaur.Random { using System; using System.Buffers; using System.Collections.Generic; using System.Runtime.InteropServices; using Minotaur.Collections; using Minotaur.ExtensionMethods.Float; public static class ThreadStaticRandom { // ThreadStatic to make sure that each thread gets a Random for itself, preventing the corruption // of the Random object [ThreadStatic] private static Random _instance; // This wraps the _random variable to make sure each thread gets a Random for itself private static Random Instance { get { if (_instance == null) _instance = new Random(); return _instance; } } public static bool Bool() { return Instance.NextDouble() &lt; 0.5; } public static bool Bool(float biasForTrue) { if (float.IsNaN(biasForTrue)) throw new ArgumentOutOfRangeException(nameof(biasForTrue) + " can't be NaN"); if (biasForTrue &lt; 0 || biasForTrue &gt; 1) throw new ArgumentOutOfRangeException(nameof(biasForTrue) + " must be in [0, 1] interval"); return Uniform() &lt; biasForTrue; } public static double Uniform() { return Instance.NextDouble(); } public static double Uniform(float inclusiveMin, float exclusiveMax) { if (inclusiveMin.IsNanOrInfinity()) throw new ArgumentOutOfRangeException(nameof(inclusiveMin) + " can't be NaN nor Infinity"); if (exclusiveMax.IsNanOrInfinity()) throw new ArgumentOutOfRangeException(nameof(exclusiveMax) + " can't be NaN nor Infinity"); if (inclusiveMin &gt; exclusiveMax) throw new ArgumentException(nameof(inclusiveMin) + " must be &lt;= " + nameof(exclusiveMax)); double range = exclusiveMax - inclusiveMin; range *= Uniform(); return inclusiveMin + range; } public static int Int(int exclusiveMax) { return Instance.Next(minValue: 0, maxValue: exclusiveMax); } public static int Int(int inclusiveMin, int exclusiveMax) { return Instance.Next(minValue: inclusiveMin, maxValue: exclusiveMax); } public static bool[] RandomLabels(int count) { if (count &lt; 0) throw new ArgumentOutOfRangeException(nameof(count) + " must be &gt; 0"); var labels = new bool[count]; // Todo: if shit hits the fan (it shouldn't), check this out var bytes = MemoryMarshal.AsBytes&lt;bool&gt;(labels); Instance.NextBytes(bytes); for (int i = 0; i &lt; bytes.Length; i++) bytes[i] &gt;&gt;= 7; return labels; } public static T Choice&lt;T&gt;(T first, T second) { if (Bool()) return first; else return second; } public static T Choice&lt;T&gt;(IReadOnlyList&lt;T&gt; values) { if (values == null) throw new ArgumentNullException(nameof(values)); if (values.Count == 0) throw new ArgumentException(nameof(values) + " can't be empty"); var index = Instance.Next(minValue: 0, maxValue: values.Count); return values[index]; } public static T Choice&lt;T&gt;(Array&lt;T&gt; values) { if (values == null) throw new ArgumentNullException(nameof(values)); if (values.Length == 0) throw new ArgumentException(nameof(values) + " can't be empty"); var index = Instance.Next(minValue: 0, maxValue: values.Length); return values[index]; } public static T Choice&lt;T&gt;(ReadOnlySpan&lt;T&gt; values) { if (values.Length == 0) throw new ArgumentException(nameof(values) + " can't be empty"); var index = Instance.Next(minValue: 0, maxValue: values.Length); return values[index]; } public static T Choice&lt;T&gt;(T[] values) { if (values.Length == 0) throw new ArgumentException(nameof(values) + " can't be empty"); var index = Instance.Next(minValue: 0, maxValue: values.Length); return values[index]; } public static void Shuffle&lt;T&gt;(Span&lt;T&gt; values) { if (values.Length == 0) throw new ArgumentException(nameof(values) + " can't be empty"); var rng = Instance; int n = values.Length; while (n &gt; 1) { n--; int k = rng.Next(n + 1); var temp = values[k]; values[k] = values[n]; values[n] = temp; } } public static void Shuffle&lt;T&gt;(T[] values) { if (values == null) throw new ArgumentNullException(nameof(values)); if (values.Length == 0) throw new ArgumentException(nameof(values) + " can't be empty"); var rng = Instance; int n = values.Length; while (n &gt; 1) { n--; int k = rng.Next(n + 1); var temp = values[k]; values[k] = values[n]; values[n] = temp; } } public static void CopyRandomElements&lt;T&gt;(ReadOnlySpan&lt;T&gt; from, Span&lt;T&gt; to, int count) { if (count &lt; 0) throw new ArgumentOutOfRangeException(nameof(count) + " must be &gt;= 0"); if (from.Length &lt; count) throw new ArgumentException(nameof(from) + " must have at least 'count' elements"); if (to.Length &lt; count) throw new ArgumentException(nameof(to) + "must have at least 'count' elements"); var rentedBuffer = ArrayPool&lt;int&gt;.Shared.Rent(minimumLength: from.Length); var indexes = rentedBuffer.AsSpan().Slice( start: 0, length: from.Length); for (int i = 0; i &lt; indexes.Length; i++) indexes[i] = i; Shuffle(indexes); for (int i = 0; i &lt; count; i++) to[i] = from[indexes[i]]; ArrayPool&lt;int&gt;.Shared.Return(rentedBuffer); } public static T[] SelectRandomElements&lt;T&gt;(ReadOnlySpan&lt;T&gt; from, int count) { if (count &lt; 0) throw new ArgumentOutOfRangeException(nameof(count) + " must be &gt;= 0"); var randomlySelected = new T[count]; CopyRandomElements( from: from, to: randomlySelected, count: count); return randomlySelected; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:08:34.130", "Id": "440205", "Score": "2", "body": "Fun reading on the subject of Random: https://ericlippert.com/?s=Fixing+Random&submit=Search" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:15:25.443", "Id": "440206", "Score": "1", "body": "@RickDavin holy cow... there are 40 (!) parts o_O" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:26:29.527", "Id": "440209", "Score": "1", "body": "Indeed... But reading Eric is always nice, so I'll give it a go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:54:40.647", "Id": "440215", "Score": "1", "body": "Here's another one in just 1 part by some author: https://codeblog.jonskeet.uk/2009/11/04/revisiting-randomness/." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T16:07:22.907", "Id": "440218", "Score": "3", "body": "@dfhwze 'some author'? I'm guessing you haven't spent much time on SO!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T16:07:54.360", "Id": "440219", "Score": "0", "body": "@VisualMelon Yes I should have said ''''some author'''' :p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T20:47:43.583", "Id": "440273", "Score": "1", "body": "To be fair, Jon Skeet is indeed an author. Not just of a given blog or article but of books. https://www.amazon.com/s?k=jon+skeet&i=stripbooks&ref=nb_sb_noss_2" } ]
[ { "body": "<p>As far as I'm aware, using <code>ThreadStatic</code> like this is fine, and will give you the guarantees you need.</p>\n\n<h2>Overall design</h2>\n\n<p>Your class is doing 2 things:</p>\n\n<ul>\n<li>Managing <code>Random</code> instances across threads</li>\n<li>Providing methods to query the Random instance</li>\n</ul>\n\n<p>I would much prefer to see all the fun methods usable on <em>any</em> <code>Random</code> instance, either wrapping it in another class or just provided as extension methods.</p>\n\n<p>This would leave the <code>ThreadStaticRandom</code> as a tiny little class with a very well defined role.</p>\n\n<p>I suppose the benefit of your design is that it is impossible for someone to mishandle an instance of <code>Random</code> by passing it to another thread, but at the same time it rules out any hope of having reproducible results.</p>\n\n<h2><code>RandomLabels</code></h2>\n\n<p>I do think this is a bad method name. I would never think to look at <code>RandomLabels</code> when I was looking for <code>Bools</code>. If you want to call a method called <code>RandomLabels</code> from a specific piece of code, then consider an extension method for that purpose.</p>\n\n<p>I don't like the implementation either. <code>NextBytes()</code> is having to consume a lot of entropy only for you to throw must of it away. A alternative solution which doesn't depend on what I presume is an implementation detail (too lazy to check if it is even a correct assumption) would be to sample bits from integers. This won't consume any more heap space, and may well be faster.</p>\n\n<h2>Documentation</h2>\n\n<p>I would take issue with your plan to add documentation <em>after</em> writing the methods: writing documentation forces you to be explicit about what the method does (as opposed to how it does it), and I would never be happy with an implementation when I havn't explicitly declared what it is going to do. It's also very easy to 'write documentation later', but that has a habit of not happening (not that I should wish to suggest <em>you</em> wouldn't get around to it!). Part of the joy of inline documentation is that it is easy to do it inline and as you write the methods.</p>\n\n<p>I won't suggest any details that need to be pointed out, because that would be a long list. I would argue you should always provide your documentation for review, because it means we can spot things that are missing (instead of trying to guess what you might forget), and check that it matches the implementation. For example, I don't know whether <code>CopyRandomValues</code> is correct because no-where is it specified that it should sample without replacement.</p>\n\n<h2>Misc</h2>\n\n<ul>\n<li><p>You have a lot of good argument validation, but you could do with a few more <code>null</code> checks in places (e.g. in <code>Choice</code>). Also consider using the constructor for <code>ArgumentException</code> which takes two parameters: the parameter name and the message. This makes it that little bit easier to scan when something goes wrong. <code>SelectRandomElements</code> should check that <code>from.Length &gt;= count</code>.</p></li>\n<li><p>I don't think you need overloads for <code>T[]</code> when you have <code>ReadOnlySpan&lt;T&gt;</code> or <code>Span&lt;T&gt;</code>: this would just reduce the redundancy a bit. (This can't be quite true of course, because it depends on an implicit conversion, which means it won't work if the caller is depending on some other implicit conversion, but then you can at least call <code>Shuffle&lt;T&gt;(Span&lt;T&gt;)</code> from <code>Shuffle&lt;T&gt;(T[])</code> to reduce duplication). Of course, the cost of simplification would be some unnecessary overhead when handling arrays.</p></li>\n<li><p><code>float biasForTrue</code> should probably be a <code>double</code>.</p></li>\n<li><p>I'd be temped to ditch the <code>count</code> parameters in <code>CopyRandomValues</code> methods: if the caller want a particular count, they can slice their spans accordingly. This will remove any possible confusion about whether this is a count or an offset and generally give the caller less opportunity to mess up.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:05:31.937", "Id": "226489", "ParentId": "226485", "Score": "8" } }, { "body": "<p>I have not much to add to VisualMelon's answer.</p>\n\n<p>You could use some more compact notation. For instance,</p>\n\n<blockquote>\n<pre><code>private static Random Instance {\n get {\n if (_instance == null)\n _instance = new Random();\n\n return _instance;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>..could be written as:</p>\n\n<pre><code> private static Random Instance =&gt; _instance ?? (_instance = new Random());\n</code></pre>\n\n<p>The name <code>Instance</code> suggests a shared instance across app domain. A more suitable name would be <code>Current</code> (<code>Thread.CurrentThread</code>, <code>CultureInfo.CurrentCulture</code>, etc..).</p>\n\n<pre><code> private static Random CurrentRandom =&gt; _instance ?? (_instance = new Random());\n</code></pre>\n\n<p>You are not consistent in using this convenience method:</p>\n\n<blockquote>\n<pre><code>public static double Uniform() {\n return Instance.NextDouble();\n}\n</code></pre>\n</blockquote>\n\n<p>You call it here:</p>\n\n<blockquote>\n<pre><code>public static bool Bool(float biasForTrue) {\n // .. arg checks\n\n return Uniform() &lt; biasForTrue;\n}\n</code></pre>\n</blockquote>\n\n<p>..but not here:</p>\n\n<blockquote>\n<pre><code>public static bool Bool() {\n return Instance.NextDouble() &lt; 0.5;\n}\n</code></pre>\n</blockquote>\n\n<p>You could also use the shorthand notation here:</p>\n\n<pre><code> public static bool Bool() =&gt; Uniform() &lt; 0.5;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:25:27.447", "Id": "440208", "Score": "2", "body": "Thanks for the feedback! I really didn't notice the inconsistencies in my calls.\nAbout compacting the code... Maybe it is just me, but I feel weird \"returning the result of an assignment\". I think I prefer, in this case, the more prolix approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T00:05:30.553", "Id": "440466", "Score": "0", "body": "`private static Random Instance => _instance ?? (_instance = new Random());` - should be done with the `Lazy<T>` class rather than this race condition-prone methodology." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T04:49:23.397", "Id": "440469", "Score": "0", "body": "@JesseC.Slicer I don't think there is a race going on, since the instance is declared ThreadStatic. But it needs to get verified." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:57:50.820", "Id": "226496", "ParentId": "226485", "Score": "4" } }, { "body": "<p>Your shuffle implementation suffers from a deceptive flaw. It will currently only allow up to a maximum of <code>2^32</code> permutations on the initial shuffle. To put that into perspective, a standard deck of cards has <code>52!</code> permutations, which is vastly beyond orders of magnitudes more.</p>\n\n<p>If you look at the method in isolation, you will understand why.</p>\n\n<blockquote>\n<pre><code> var rng = Instance;\n int n = values.Length;\n while (n &gt; 1) {\n n--;\n int k = rng.Next(n + 1);\n var temp = values[k];\n values[k] = values[n];\n values[n] = temp;\n }\n</code></pre>\n</blockquote>\n\n<p>The <code>Random</code> instance will always be seeded with some <code>Int32</code> value. Given a specified array to be shuffled along with any seed and the algorithm, the sequence generated is <em>completely deterministic</em>.</p>\n\n<p>What does all of that actually imply? Lets say you have a blackjack program with only 1 thread. Lets assume as a user, I don't know the seed, but I do know the algorithm and the first shuffled deck sequence. Because there are only <code>2^32</code> permutations, I can easily pre-calculate all of them based upon every possible seed. Once I find the sequence that matches the shuffled deck, I now also know the seed used. Once I know the seed used, I can now calculate every subsequent shuffled deck.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T08:42:39.467", "Id": "440481", "Score": "1", "body": "Good point! The seed in your example could be found in just a couple of hours. Whether the OP should use a cryptographically secure PRNG instead depends on the intended use-cases, but this is definitely something that should at least be documented." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T20:16:50.943", "Id": "226590", "ParentId": "226485", "Score": "2" } }, { "body": "<p>One small thing I noticed is that all your Choice methods that take in a list of some sort are basically the same structure. </p>\n\n<pre><code>public static T Choice&lt;T&gt;(IReadOnlyList&lt;T&gt; values) {\n if (values == null)\n throw new ArgumentNullException(nameof(values));\n if (values.Count == 0)\n throw new ArgumentException(nameof(values) + \" can't be empty\");\n\n var index = Instance.Next(minValue: 0, maxValue: values.Count);\n return values[index];\n}\n\npublic static T Choice&lt;T&gt;(Array&lt;T&gt; values) {\n if (values == null)\n throw new ArgumentNullException(nameof(values));\n if (values.Length == 0)\n throw new ArgumentException(nameof(values) + \" can't be empty\");\n\n var index = Instance.Next(minValue: 0, maxValue: values.Length);\n return values[index];\n}\n\npublic static T Choice&lt;T&gt;(ReadOnlySpan&lt;T&gt; values) {\n if (values.Length == 0)\n throw new ArgumentException(nameof(values) + \" can't be empty\");\n\n var index = Instance.Next(minValue: 0, maxValue: values.Length);\n return values[index];\n}\n\npublic static T Choice&lt;T&gt;(T[] values) {\n if (values.Length == 0)\n throw new ArgumentException(nameof(values) + \" can't be empty\");\n\n var index = Instance.Next(minValue: 0, maxValue: values.Length);\n return values[index];\n}\n</code></pre>\n\n<p>Can any of these be combined? There might be a common interface many of these different collections implement, such as IEnumerable, or ICollection. That might not handle all the input types you expect, but it could reduce the number of Choice methods you have.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T20:50:14.480", "Id": "226594", "ParentId": "226485", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T12:31:18.990", "Id": "226485", "Score": "6", "Tags": [ "c#", "performance", "multithreading", "random", "thread-safety" ], "Title": "Thread-safe, Convenient and Performant Random Number Generator" }
226485
<p>I am a beginner in C. My teacher gave me a homework problem in which a user would provide an array with its size.</p> <p>What we have to do is:-</p> <blockquote> <p>1) Take out all the distinct elements from that array.</p> <p>2) Compare all the subarrays which are possible in the main array with the "distinct array".</p> <p>3) Tell the number of times we were able to successfully "discover" all those subarrays which contained ALL the distinct elements.</p> </blockquote> <p>Example:- We are given an array :- [1,2,2,3,3] The distinct elements array would be :- [1,2,3] All the subarray of the original array will be :- </p> <pre><code>1) [1,2] 2) [1,2,2] 3) [1,2,2,3] 4) [1,2,2,3,3] 5) [2,2] 6) [2,2,3] 7) [2,2,3,3] 8) [2,3] 9) [2,3,3] 10) [3,3] </code></pre> <p>The answer of this specific test case shall be 2. Since only (3) and (4) subarrays contain all the distinct elements i.e. 1,2 and 3.</p> <p>Second Example:-</p> <p>Given array :- [86,5,34,64,56,60,81,77,36,41]</p> <p>The answer of the second example is 1; since all the elements of the original array are distinct and hence only one solution shall contain all the possible distinct elements which is the original array itself.</p> <p>Here is my code which I have wrote for the above problem:-</p> <pre><code># include &lt;stdio.h&gt; # include &lt;stdlib.h&gt; # include &lt;stdbool.h&gt; bool check(int *, int *, int, int); int main() { int number; // Variable name "number" which will specify the size of dynamically allocated array. printf("Enter the size of your array\n"); scanf("%d",&amp;number); int *array; array = (int*)calloc(number, sizeof(int)); // Dynamically allocated memory. int *temp_array; temp_array = (int*)calloc(number, sizeof(int)); // Temporary variable of original array. int i,j=0; // Counter variables for loop. printf("Enter the elements of arrays\n"); for(i = 0; i &lt; number; i++) { scanf("%d",(array + i)); //Main original array being filled. } for(i = 0; i &lt; number; i++) { *(temp_array + i) = *(array + i); //Copying into temp. } for(i = 0; i &lt; number; i++) { for( j = i + 1 ; j &lt; number; j++) { if( *(temp_array + i ) == *(temp_array + j)) { *(temp_array + j) = 0; // My way of removing those numbers which are the repeated. (Assigning them value of zero). } } } i=0;j=0; int sub_number = 0; while(i &lt; number) { if(*(temp_array + i) != 0) { sub_number++; // Variable name "sub_number" which will specify the size of dynamically allocated array "sub_array". } i++; } int *sub_array ; sub_array = (int*)calloc(sub_number,sizeof(int)); j=0; for(i = 0;i &lt; number ;i++) { if( *(temp_array + i ) != 0) { *(sub_array + j) = * (temp_array + i ); //Transferring all the distinct values from temp_array to sub_array. j++; } } free(temp_array); //Freed "temp_array". No longer needed. temp_array = NULL; for(i = 0;i &lt; sub_number; i++) { printf("%d ",*(sub_array + i)); // Desired array which only contains distinct and unique variables. } printf("\n"); int ans = 0; //Variable which shall calculate the answer. int k=0; //New variable counter j=0; for(i=0; i &lt; number; i++) //This loop will traverse variable "i" on array "array". { k = i; while(k &lt; number) //This loop will traverse variable "k" on array "array" { int *new_array; new_array = (int*) calloc ((k-i+1),sizeof(int)); for(j = i; j &lt;= k; j++) //This loop will assign the subset values of array "array" to array "new_array". { *(new_array + (j - i)) = *(array + j); } if(check(new_array, sub_array, (k-i+1), sub_number) == true) //This will check if ALL the values in "sub_array" are present in "new_array" or not. { ans++; } free(new_array); new_array = NULL; k++; } } printf("%d",ans); return 0; } bool check(int * new_array, int *sub_array, int new_number, int sub_number) //Function to check if ALL the values in "sub_array" are present in "new_array" or not. { int i = 0; int j = 0; for(i = 0; i &lt; new_number; i++) //new_number is nothing but (k - i + 1) { if(*(new_array + i) == *(sub_array + j)) { j++; if(j == sub_number) { return true; } i = -1; } } return false; } </code></pre> <p>How to optimise this code? Is there any better way to implement this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T13:56:45.133", "Id": "440183", "Score": "0", "body": "What guarantees are there about the order of the array and its subarrays? Are they guaranteed to be sorted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:05:27.390", "Id": "440186", "Score": "0", "body": "This can be done in `O(N)` see: https://leetcode.com/problems/subarrays-with-k-different-integers/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:08:35.660", "Id": "440189", "Score": "0", "body": "Do you have sample input and expected output? That might help me understand your description better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:46:12.897", "Id": "440200", "Score": "0", "body": "@Reinderien no need to sort out array, we just have to make all possible sub-arrays of original array and then compare with an array which stores all the \"distinct elements\". If all distinct elements are there then we can increment our answer by `1`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:48:35.860", "Id": "440201", "Score": "0", "body": "@TobySpeight Sample input :- `[1,2,2,3,3]`. Sample output :- `2`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:37:22.607", "Id": "440211", "Score": "0", "body": "I'm not asking whether we need to sort the array; I'm asking whether we can assume that it's already sorted (as your examples are)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:40:00.717", "Id": "440212", "Score": "0", "body": "@Reinderien They are not necessarily sorted." } ]
[ { "body": "<p>Prefer to declare <code>main()</code> as a prototype:</p>\n\n<pre><code>int main(void)\n</code></pre>\n\n<hr>\n\n<p>Always, always check the return value of <code>scanf()</code> and family:</p>\n\n<pre><code>if (scanf(\"%d\", &amp;number) != 1) {\n fprintf(stderr, \"Failed to parse a number\\n\");\n return EXIT_FAILURE;\n}\n</code></pre>\n\n<p>Without such a test, the program will blindly proceed with whatever uninitialised value <code>number</code> has.</p>\n\n<p>We should also ensure that a positive number was entered - if <code>number</code> is less than <code>0</code>, then bad things are going to happen. Consider using an unsigned type for <code>number</code>, so that we're not converting between signed and unsigned (in <code>calloc()</code> calls).</p>\n\n<hr>\n\n<p>Don't cast the result of <code>malloc()</code> family of functions. They return <code>void*</code>, which is assignable to a variable of any pointer type. I recommend using the variable itself as the argument to <code>sizeof</code> rather than repeating the type name - in many cases, it makes it easier for readers to see the correspondence.</p>\n\n<p>And always, always check allocations don't return a null pointer.</p>\n\n<pre><code>int *array = calloc(number, sizeof *array);\nif (!array) {\n fprintf(stderr, \"Memory allocation failure\\n\");\n return EXIT_FAILURE;\n}\n</code></pre>\n\n<hr>\n\n<p><code>*(array + i)</code> is more conveniently and conventionally written as <code>array[i]</code> (or, perversely, as <code>i[array]</code> - but don't do that!).</p>\n\n<hr>\n\n<p>I don't have time right now to follow the algorithm, but I'm sure it could be simpler. Fixing the issues above will certainly improve your C programs, anyway.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:17:56.670", "Id": "226492", "ParentId": "226487", "Score": "5" } }, { "body": "<p><strong>Lack of Error Checking</strong><br>\nThere are two types of error checking that would improve the code. The first is checking user input, for instance if the value for the size of the array is negative the program will crash when it tries to allocate the memory for the array. The second is that the value returned from <code>calloc(size_t count, size_t size)</code> may be NULL if the call to <code>calloc()</code> fails for some reason. The function <code>calloc()</code> can fail if there is not enough memory to allocate the array.</p>\n\n<p>It is generally a good practice to always check the return value of <code>calloc()</code>, while computers today have a lot of memory there are cases such as in embedded programming where there may not be enough memory.</p>\n\n<pre><code> int *array;\n array = (int*)calloc(number, sizeof(int));\n if (array == NULL)\n {\n // report error and handle clean up\n }\n</code></pre>\n\n<p><strong>Avoid Pointer Arithmetic When Possible</strong><br>\nThe code could just as easily use <code>temp_array[i]</code> as <code>*(temp_array + i)</code>. Using an index is makes it easier to write, read and debug the code. </p>\n\n<p>Pointers can be used to move through an array quickly in a linear fashion, but then it would be better to increment the pointer rather than adding an offset to the pointer.</p>\n\n<p><strong>DRY Code</strong><br>\nThere is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. One place where this code could be encapsulated is allocating memory for arrays. A function could take a number and return an allocated array of integers if the allocation doesn't fail.</p>\n\n<p><strong>Complexity</strong><br>\nThe function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n\n<p>There is also a programming principle called the Single Responsibility Principe that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n\n<blockquote>\n <p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>There are at least 3 possible functions in <code>main()</code>.<br>\n - Allocate array memory<br>\n - Get the user input<br>\n - Copy distinct integers<br>\n - Calculate and print the answer </p>\n\n<p><strong>Algorithm</strong><br>\nRather than removing duplicates from the input array it might be better to go through the input array and copy a value to the <code>sub_array</code> only once. The check for zero is invalid since valid integers in the array can include zero and negative numbers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:15:56.830", "Id": "440207", "Score": "1", "body": "Not all arrays are pointers. In fact there's a big difference between them: sizeof(arr) vs sizeof(ptr)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:51:02.073", "Id": "440214", "Score": "0", "body": "@CacahueteFrito I didn't say all pointers are arrays, they aren't, could you give an example of an array that isn't a pointer? sizeof(ptr) should always yield word size." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T16:00:37.387", "Id": "440216", "Score": "1", "body": "Example: `int buf[BUFSIZ];`. Differences: https://stackoverflow.com/q/1641957/6872717. Arrays decay in most cases to pointers, but they *are* not pointers, and sometimes that difference is visible, for example when `sizeof` is applied to them (it's one of the few cases where they don't decay to a pointer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T16:06:58.647", "Id": "440217", "Score": "0", "body": "@CacahueteFrito removed comment about arrays being pointers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T16:08:14.053", "Id": "440220", "Score": "1", "body": "Many people don't have this difference clear enough, and that is a common source of [bugs](https://lkml.org/lkml/2015/9/3/428). Note that I disagree with the solution that Linus proposes in that link, I like array arguments as documentation, but it's good to have the differences very present. I use a different approach to avoid those bugs, which is to never use `sizeof(arr)`, but have a macro called `ARRAY_BYTES(arr)` that does the same, but with some compile-time safety checks added." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:08:44.837", "Id": "226498", "ParentId": "226487", "Score": "5" } }, { "body": "<p>there are several memory leaks in the posted code.</p>\n\n<p>This is because only some of the memory pointers (returned by calls to <code>calloc()</code> are being passed to <code>free()</code></p>\n\n<p>Suggest running <code>valgrind</code> (a free utility) as it will tell/show you all the memory leaks</p>\n\n<p>When compiling, always enable the warnings, then fix those warnings. (for <code>gcc</code>, at a minimum use: <code>-Wall -Wextra -Wconversion -pedantic -std=gnu11</code> ) Note: other compilers use different options to produce the same results.</p>\n\n<p>Note that the function: <code>calloc()</code> expects it parameters to be of type <code>size_t</code>, not <code>int</code> nor <code>unsigned int</code> nor <code>long int</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T02:01:10.333", "Id": "226537", "ParentId": "226487", "Score": "0" } } ]
{ "AcceptedAnswerId": "226498", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T13:10:29.840", "Id": "226487", "Score": "6", "Tags": [ "beginner", "c", "homework" ], "Title": "Taking out number of subarrays from an array which contains all the distinct elements of that array" }
226487
<p>This is my implementation of the famous Number Guessing Game. It is not object oriented, but the goal was to create a simple to read, procedural program. Have I accomplished this goal?</p> <pre><code>import java.util.Random; import java.util.Scanner; class Main { private static int lowerRange = 1; private static int upperRange = 99; private static int tries = 6; private static Scanner input = new Scanner(System.in); private static Random random = new Random(); public static void main(String[] args) { showDescription(); boolean run = true; while (run) { play(); System.out.print("Play again? (Y / N): "); run = input.nextLine().equalsIgnoreCase("Y") ? true : false; } } private static void showDescription() { System.out.println("You have to guess a number between " + lowerRange + " and " + upperRange + "."); System.out.println("You have " + tries + " tries."); } private static void play() { int randomNumber = generateRandomNumber(lowerRange, upperRange); int triesSoFar = 0; boolean won = false; while (triesSoFar &lt; tries &amp;&amp; won == false) { System.out.print("Your try: "); int guess = Integer.parseInt(input.nextLine()); if (guess &gt; randomNumber) { System.out.println("The secret number is smaller."); } else if (guess &lt; randomNumber) { System.out.println("The secret number is higher."); } else { won = true; break; } triesSoFar++; } if (won) { System.out.println("You found the secret number!"); } else { System.out.println("You lose. The secret number was " + randomNumber + "."); } } private static int generateRandomNumber(int lowerRange, int upperRange) { return random.nextInt(upperRange - lowerRange) + lowerRange; } } </code></pre>
[]
[ { "body": "<p>I assume you have already ran it and can confirm it works. Seems to be fine.\nOnly small thing is that you have to choose a number between 1 and 99, but although 99 cannot be the answer, 1 can be.</p>\n\n<p><a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Random.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/8/docs/api/java/util/Random.html</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:33:55.303", "Id": "226493", "ParentId": "226491", "Score": "2" } }, { "body": "<p>You have <code>showDescription</code> directly printing out the message. Avoid printing in arbitrary functions whenever possible. It's much better to have things return Strings, then print at the call site as needed. I'd change that function to:</p>\n\n<pre><code>private static String produceDescription() {\n return \"You have to guess a number between \" + lowerRange + \" and \" + upperRange + \".\\n\"\n + \"You have \" + tries + \" tries.\");\n}\n\n. . .\n\nSystem.out.println(produceDescription());\n</code></pre>\n\n<p>Why? Two highly-related reasons:</p>\n\n<ul>\n<li><p>Whenever possible, functions should <em>return</em> the data that they produce. Can you guarantee that for a function like this you will <em>always</em> want to directly print that data? Let the caller decide how they want to use the data that the function produces. Forcing the data to be printed makes the function less useful in the long term. As an example...</p></li>\n<li><p>If you ever decide to adapt this program to use a full GUI, you're directly printing and will need to modify every function that is calling <code>println</code>. The less functions you have that are using data in a specific way, the easier it will be to alter your program later.</p></li>\n</ul>\n\n<hr>\n\n<p>I would not make everything <code>static</code> here. Again, what if in the future you wanted to run two games at the same time (like if you created a server that allows people to connect to it and play)? I'd get rid of <code>static</code> everywhere, and make everything plain instance methods/properties, then just instantiate a instance of the game in <code>main</code>.</p>\n\n<hr>\n\n<p><code>Main</code> is a poor name for this class. Ideally, it should be a description of what the object accomplishes. What if you ever imported this class so it can be used elsewhere? A class called <code>Main</code> doesn't make it immediately obvious what it is used for. I'd change the name to something like <code>NumberGuessingGame</code>.</p>\n\n<hr>\n\n<pre><code>run = input.nextLine().equalsIgnoreCase(\"Y\") ? true : false;\n</code></pre>\n\n<p>is redundant. Ternary expressions are cool, but they're often overused. Think about it, what does <code>equalsIgnoreCase</code> return? A <code>bool</code> (<code>true</code> or <code>false</code>). You're then using that bool as a condition to the ternary... to get the same thing that <code>equalsIgnoreCase</code> returned originally.</p>\n\n<p>Just get rid of the ternary:</p>\n\n<pre><code>run = input.nextLine().equalsIgnoreCase(\"Y\");\n</code></pre>\n\n<p>And on the topic of conditions, a little later you have:</p>\n\n<pre><code>while (triesSoFar &lt; tries &amp;&amp; won == false) {\n</code></pre>\n\n<p><code>won == false</code> certainly isn't <em>wrong</em>, but comparing against a boolean value directly is almost always unnecessary. Just write:</p>\n\n<pre><code>while (triesSoFar &lt; tries &amp;&amp; !won) {\n</code></pre>\n\n<p>Remember, <code>!</code> is read as \"not\". \"While tries to far is less than tries, and they haven't (not) won\".</p>\n\n<hr>\n\n<p><code>tries</code> is a bad name. It isn't representing the number of tries taken (that's <code>triesSoFar</code>), it's representing the <em>max</em> number of tries allowed. Change it to something like <code>maxAllowedTries</code>.</p>\n\n<p>Naming is <em>very</em> important. It is one of the key things that allows someone to be able to read your code and quickly know what's going on. Make sure your functions and variable names accurately describe what they do, or you'll make other people's lives more difficult when they need to read your code. You'll also make your own life more difficult if you ever come back to this program, because you <em>will</em> eventually forget parts of this program after some time.</p>\n\n<hr>\n\n<pre><code>System.out.print(\"Your try: \");\n</code></pre>\n\n<p>Isn't actually guaranteed to print right away. <code>print</code> and <code>println</code> use a \"buffer\" to hold text while waiting to print. That buffer is only \"flushed\" (printed out) when the text exceeds a certain length, or a newline (<code>\\n</code>) is reached. You have short text here, and because you're using <code>print</code>, no newline is being added to the buffer. You may find that if you made this text a little shorter, it wouldn't print until some other text had be printed as well, which will make your program confusing.</p>\n\n<p>If you use <code>print</code> instead of <code>println</code>, it can be a good idea to add a call to <code>System.out.flush()</code> after it to make sure everything is printed when you want it to be.</p>\n\n<hr>\n\n<p>Just to show a potentially appropriate use of a ternary, you have:</p>\n\n<pre><code>if (won) {\n System.out.println(\"You found the secret number!\");\n} else {\n System.out.println(\"You lose. The secret number was \" + randomNumber + \".\");\n}\n</code></pre>\n\n<p>Which isn't bad, but it could be shorted a bit:</p>\n\n<pre><code>String message = won ? \"You found the secret number!\"\n : (\"You lose. The secret number was \" + randomNumber + \".\");\n\nSystem.out.println(message);\n</code></pre>\n\n<p>I'm not <em>necessarily</em> advocating for this way, but I thought I'd show it. It allows you to get rid of the multiple calls to <code>println</code>.</p>\n\n<hr>\n\n<pre><code> int guess = Integer.parseInt(input.nextLine());\n if (guess &gt; randomNumber) {\n System.out.println(\"The secret number is smaller.\");\n } else if (guess &lt; randomNumber) {\n System.out.println(\"The secret number is higher.\");\n } else {\n won = true;\n break;\n }\n</code></pre>\n\n<p>is a <em>dense</em> chunk of code. I prefer to add more spacing around things. I like blank lines above <code>if</code>s and <code>else</code>s so it's easier to see at a glance the distinct blocks. I'd make it:</p>\n\n<pre><code> int guess = Integer.parseInt(input.nextLine());\n\n if (guess &gt; randomNumber) {\n System.out.println(\"The secret number is smaller.\");\n\n } else if (guess &lt; randomNumber) {\n System.out.println(\"The secret number is higher.\");\n\n } else {\n won = true;\n break;\n }\n</code></pre>\n\n<p>That generally makes it easier to pick things out by eye when scanning over a document.</p>\n\n<hr>\n\n<hr>\n\n<p>There's some more stuff, but unfortunately, I have to go. Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T16:47:24.293", "Id": "440227", "Score": "0", "body": "I disagree with the flush()-topic and with the format-recommandation at the end, but the rest is gold. Thank you for your lovely code review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T07:56:19.700", "Id": "440316", "Score": "0", "body": "The flush behaviour of System.out.print(...) is undocumented, so as far as we know, you need to flush to guarantee it to always work in every possible scenario. There is a fair bit of discussion about it on Stack Overflow." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T16:25:38.800", "Id": "226501", "ParentId": "226491", "Score": "3" } }, { "body": "<p>The static variables declared in the beginning of the class should be constants and named according to naming conventions.</p>\n\n<pre><code>private static final int LOWER_RANGE = 1;\nprivate static final int UPPER_RANGE = 99;\nprivate static final int MAX_TRIES = 6;\n</code></pre>\n\n<p>Things that are not meant to change should be final. It's debatable if these should be named like constants like above, as they are static and final, but in this context of pure procedural programming, the static keyord doesn't make much difference, so going lower case can be justified.</p>\n\n<pre><code>private static final Scanner input = new Scanner(System.in);\nprivate static final Random random = new Random();\n</code></pre>\n\n<p>A number guessing game should handle invalid input too, so the code should catch NumberFormatException. However, now that the input reading became more complex, I would refactor it into a separate method. How errors and user's desire to stop playing is reported is again debatable, but since the context is procedural programming, I'm sticking to C-style magic return values.</p>\n\n<pre><code>/**\n * Read input from user.\n *\n * @return The user's guess or -1 if the user wants to stop playing.\n */ \nprivate static int readGuess() { \n ...\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T07:47:52.693", "Id": "226550", "ParentId": "226491", "Score": "1" } } ]
{ "AcceptedAnswerId": "226501", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T14:11:09.420", "Id": "226491", "Score": "4", "Tags": [ "java", "beginner", "game", "number-guessing-game" ], "Title": "Number Guessing Game in Java" }
226491
<p>I've written a helper for combining objects (deep merge).</p> <p>It works, and is flexible to add options (like <code>uniq</code> and <code>replace</code>).</p> <p>Replace should replaces the any matching properties on the object (but spread in any existing properties).</p> <p>The code below works, but I believe it could be optimized particularly as I could NOT find a way to remove empty keys without the use of <code>JSON.parse(JSON.stringify</code> - it feels wrong to have to crawl back over the entire array to do so.</p> <p>Using Lodash is not an option.</p> <h2>Examples</h2> <p>DATA = {foo:{i:{z:[1]},x:[1]}}</p> <ul> <li><code>getDeepMerge(DATA, {add:{foo:{q:[1]}}}</code> // {foo:{i:{},x:[1], q:[1]}}</li> <li><code>getDeepMerge(DATA, {add:{foo:{}}, replace:true}</code> // {foo:{}}</li> <li><code>getDeepMerge(DATA, {add:{foo:{i:{}}} }, replace:true, removeEmpty:true}</code> // {add:{foo:{i:{}}, x[1]} }</li> </ul> <h2>Code</h2> <pre><code>const removeKey = (key, {[key]: _, ...rest}) =&gt; rest; const getNewObj = toAdd =&gt; Array.isArray(toAdd) ? getObj(toAdd) : toAdd const DE_DUPE = (e, i, arr) =&gt; arr.indexOf(e) === i const removeEmptyObj = (o) =&gt; { let ignores = [null, undefined, ""], isNonEmpty = d =&gt; !ignores.includes(d) &amp;&amp; (typeof(d) !== "object" || Object.keys(d).length) return JSON.parse(JSON.stringify(o), function(k, v) { if (isNonEmpty(v)) return v; }); } const getDeepMerge = (ogObj, opts={})=&gt; { const { add, uniq=true, replace=false, removeEmpty=false } = opts const isObject = obj =&gt; obj &amp;&amp; typeof obj === 'object'; return [ogObj, add].reduce((prev, obj) =&gt; { let _add = {...prev} Object.keys(obj).forEach(key =&gt; { const pVal = _add[key]; const oVal = obj[key]; if (Array.isArray(pVal) &amp;&amp; Array.isArray(oVal)) { _add[key] = pVal.concat(...oVal).filter(uniq ? DE_DUPE : null) if(replace){ _add[key] = oVal } _add = removeEmpty ? removeKey(key, _add) : _add } else if (isObject(pVal) &amp;&amp; isObject(oVal)) { _add[key] = getDeepMerge(pVal, {...opts, add:oVal}) if(replace){ _add[key] = oVal } } else { _add[key] = oVal } }); return removeEmptyObj(_add) }, {}); } </code></pre> <p>Live working demo: <a href="https://jsbin.com/yuduvukiqe/1/edit?js,console" rel="nofollow noreferrer">https://jsbin.com/yuduvukiqe/1/edit?js,console</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-19T09:33:58.470", "Id": "485915", "Score": "3", "body": "I have tried your code, but it does not output the expected result. Could you please check this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-22T15:24:20.443", "Id": "493941", "Score": "1", "body": "For those in the Close vote queue: Jan's statement is correct - see the output [here](https://jsbin.com/wisozizovi/edit?js,console)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-20T15:22:25.903", "Id": "226499", "Score": "4", "Tags": [ "javascript", "recursion", "json" ], "Title": "JS deep merging of objects- removing empty keys" }
226499