body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have some questions about a code I found on stackoverflow. The code does what I want to do. Redirects to HTTPS and WWW when doesn't exist in URL. But, I want now to understand what I'm doing.</p>
<p>So, here is the code I use:</p>
<pre><code># Redirect non HTTPS to HTTPS #
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
# Force www #
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L,E=HTTPS:1]
</code></pre>
<ol>
<li>The code above works as expected. Why isn't the code in the next format, as it does the same thing ? Is any difference ?</li>
</ol>
<pre><code>RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
</code></pre>
<ol start="2">
<li>The first line of code looks a little bit ambiguous. So I try to modify with:</li>
</ol>
<pre><code>RewriteCond %{HTTPS} != on # Put a space before on
</code></pre>
<p>Or:</p>
<pre><code>RewriteCond %{HTTPS} != 'on' # Put on in single quotes
</code></pre>
<p>Or:</p>
<pre><code>RewriteCond %{HTTPS} != "on" # Put on in double quotes
</code></pre>
<p>And it doesn't work. Can you please explain why ?</p>
<ol start="3">
<li>I found some users which are using:</li>
</ol>
<pre><code>RewriteCond %{HTTPS} off
</code></pre>
<p>and not:</p>
<pre><code>RewriteCond %{HTTPS} !=on
</code></pre>
<p>I understand that one line checks if the https is off and another one if https is not on. We can say they do the same thing. There are other differences here ? Can HTTPS not be neither <code>on</code> or <code>off</code> ? If the answer is yes, that means the line <code>RewriteCond %{HTTPS} !=on</code> is better than <code>RewriteCond %{HTTPS} off</code>. Isn't it ?</p>
<p>4 When forcing www I have <code>E=HTTPS:1</code> flag, which means I set the variable HTTPS with value 1. I don't understand the reason... When and who checks for this variable ?</p>
<p>Here, on question 4 I try to rename HTTPS to HTTPSaaa and then, with php, to get all server variable (from $_SERVER). I don't find HTTPSaaa. So this means that the flag is used only by htaccess ? So, I ask again. What's the reason for this flag/variable to exist ?</p>
<p>PS: If someone want's to answer, please specify the question number. I am already a little bit confused...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T15:39:03.303",
"Id": "502026",
"Score": "0",
"body": "We require that the poster know why the code is written the way it is. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T17:22:17.123",
"Id": "502030",
"Score": "0",
"body": "If this question is off-topic for CodeReview then feel free to ask future questions of this nature (or even move this question) to the [Webmasters stack](https://webmasters.stackexchange.com/), where it is certainly on-topic."
}
] |
[
{
"body": "<blockquote>\n<ol>\n<li><p>The code above works as expected. Why isn't the code in the next format, as it does the same thing? Is any difference ?</p>\n<pre><code>RewriteCond %{HTTPS} !=on [OR]\nRewriteCond %{HTTP_HOST} !^www\\.\nRewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]\n</code></pre>\n</li>\n</ol>\n</blockquote>\n<p>This code is different to your "working" code (at the top of your question). In this code, the <code>www</code> subdomain is <em>always</em> prefixed to the requested hostname. So, if you were to request <code>http://www.example.com/foo</code> (HTTP + www) then it will redirect to <code>https://www.www.example.com/foo</code> - which is presumably not the intention.</p>\n<p>This can be "fixed" with an additional <em>condition</em> in order to capture the hostname less the "optional" <code>www</code> subdomain, however, this is still not "the same" as the "working" directives you posted. For example:</p>\n<pre><code>RewriteCond %{HTTPS} !=on [OR]\nRewriteCond %{HTTP_HOST} !^www\\.\nRewriteCond %{HTTP_HOST} ^(?:www\\.)?(.+?)\\.?$ [NC]\nRewriteRule ^(.*)$ https://www.%1/$1 [R=301,L]\n</code></pre>\n<p>The only purpose of the 3rd <em>condition</em> is to capture the hostname, less the <code>www.</code> prefix (if any). This condition is <em>always</em> successful. The hostname (less the <code>www.</code> prefix) is stored in the <code>%1</code> backreference.</p>\n<p>Just to emphasise... this is not <em>exactly</em> the same as the "working" redirects you posted initially. This performs the HTTPS + www redirect in 1 go, instead of two (potentially) in your "working" directives. eg. When you request HTTP and non-www then your "working" redirects will trigger 2 redirects, first to HTTPS on the same host<sup><b>*1</b></sup> and then to HTTPS + www.</p>\n<p><sup><b>*1</b></sup> This is a necessary requirement if you have implemented <a href=\"https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security\" rel=\"nofollow noreferrer\">HTTP Strict Transport Security (HSTS)</a> - where you must redirect to HTTPS on the same host <em>before</em> canonicalising the hostname. So, one redirect is not always "better" than two.</p>\n<blockquote>\n<ol start=\"2\">\n<li><p>The first line of code looks a little bit ambiguous. So I try to modify with:</p>\n<pre><code>RewriteCond %{HTTPS} != on # Put a space before on\n</code></pre>\n</li>\n</ol>\n</blockquote>\n<p>It may <em>look</em> ambiguous to you, but I assure you it's not.</p>\n<p>You cannot simply inject spaces here, since <em>spaces</em> are argument delimiters in Apache config files. So, by putting a <em>space</em> after the <code>!=</code> you are now passing 3 arguments to the <code>RewriteCond</code> directive: <code>%{HTTPS}</code>, <code>!=</code> and <code>on</code>. <code>on</code> is likely to trigger an "invalid flags" error, since this will be interpreted as the 3rd "flags" parameter (eg. normally something like <code>[NC]</code>).</p>\n<p>The <code>=</code> and <code>!</code> are prefix-operators and are in fact part of the argument (<em>CondPattern</em>). They change the way the <em>CondPattern</em> (2nd argument) is interpreted. <code>!=</code> is not a single operator, it does not strictly mean not-equals, as you are perhaps expecting, although the net result is the same. (More on this below).</p>\n<p>The only time you <em>need</em> to use double-quotes (not single-quotes) around an argument in Apache config files is if the argument contains <em>spaces</em> (since, as mentioned above, <em>spaces</em> are argument delimiters). Although you can always surround the argument in double-quotes if you wish. And you can sometimes backslash escape the <em>space</em> instead (if the argument is a regex).</p>\n<p>But note, the double-quotes surround the <em>entire argument</em> (which includes the prefix operators). For example:</p>\n<pre><code>RewriteCond %{HTTPS} "!=on"\n</code></pre>\n<p><em>Aside:</em> Apache does not support line-end comments, so the <code># Put a space before on</code> at the end of the line is not valid. Due to the way Apache directives are processed, this may appear to be OK at times (ie. no error), but it is strictly invalid. (You may have only used this in the code sample in your question, however, it is a common source of error, so worth mentioning.)</p>\n<blockquote>\n<ol start=\"3\">\n<li>I found some users which are using:</li>\n</ol>\n</blockquote>\n<blockquote>\n<pre><code>RewriteCond %{HTTPS} off\n</code></pre>\n<p>and not:</p>\n<pre><code>RewriteCond %{HTTPS} !=on\n</code></pre>\n<p>I understand that one line checks if the https is off and another one if https is not on. We can say they do the same thing. There are other differences here ?</p>\n</blockquote>\n<p>I've actually <a href=\"https://webmasters.stackexchange.com/a/118396/1243\">answered the same question on the Webmasters stack</a> previously, so I'll just link to that for more detail:</p>\n<ul>\n<li><a href=\"https://webmasters.stackexchange.com/questions/118391/in-htaccess-files-is-there-any-difference-at-all-between-on-and-off\">https://webmasters.stackexchange.com/questions/118391/in-htaccess-files-is-there-any-difference-at-all-between-on-and-off</a></li>\n</ul>\n<p>But yes, the net result is indeed the same and it's primarily personal preference which method you choose. Although the two methods are technically different.</p>\n<ul>\n<li><code>off</code> is a regex comparison: Does <code>off</code> occur anywhere in the value of the <code>HTTPS</code> server variable?</li>\n<li><code>!=on</code> is <em>not</em> a regex comparison. The <code>=</code> prefix changes it to a lexicographical string comparison. ie. Is the value of the HTTPS server var exactly equal to "on"? The <code>!</code> prefix then negates the expression. So the condition is successful when it does not match.</li>\n</ul>\n<blockquote>\n<p>Can <code>HTTPS</code> not be neither on or off ?</p>\n</blockquote>\n<p>The <code>HTTPS</code> server variable can only be "on" or "off" if your server is correctly configured.</p>\n<blockquote>\n<p>If the answer is yes, that means the line <code>RewriteCond %{HTTPS} !=on</code> is better than <code>RewriteCond %{HTTPS} off</code>. Isn't it ?</p>\n</blockquote>\n<p>Not necessarily. If <code>HTTPS</code> is not "on" or "off" then it's more likely to not be set at all (on all requests), so <code>!=on</code> would always be successful and result in a redirect loop. Whereas <code>off</code> will simply fail. Although this is hypothetical, your server would have to be "broken" for the <code>HTTPS</code> <em>server</em> variable not to be set at all and to not be "on" or "off".</p>\n<blockquote>\n<ol start=\"4\">\n<li>When forcing www I have <code>E=HTTPS:1</code> flag, which means I set the variable HTTPS with value 1.</li>\n</ol>\n</blockquote>\n<p>First, a bit of clarification... there are 2 variables here:</p>\n<ol>\n<li>The <code>HTTPS</code> <em>server</em> variable as set by Apache and referenced in <code>%{HTTPS}</code>. This is effectively readonly.</li>\n<li>The <code>HTTPS</code> <em>environment</em> variable that you are setting here. This would be readable using the syntax <code>%{ENV:HTTPS}</code>.</li>\n</ol>\n<p>Whilst it is relatively common to see this, it is arguably confusing to have two different variables of the same name. It would be <em>better</em> to change your environment variable to something like <code>HSTS</code> instead (see below), to avoid any confusion.</p>\n<blockquote>\n<p>I don't understand the reason... When and who checks for this variable ?</p>\n</blockquote>\n<p>Well, in the directives you posted it's not required. So, maybe this is not required here? But...</p>\n<p>The reason for setting an env var on the HTTPS redirect like this is a common pattern when implementing HSTS<sup><b>*2</b></sup>. When implementing HSTS you need to set the <code>Strict-Transport-Security</code> HTTP response header on the HTTPS to HTTPS redirect itself. This is why I suggested using a variable called <code>HSTS</code> instead. If you are not setting this header with a conditional <code>Header</code> directive elsewhere in your config file (based on this env var) then you are not implementing HSTS (properly) and this env var is most probably superfluous.</p>\n<p><sup><b>*2</b></sup> Although I wouldn't necessarily do it this way myself. I would set the env var in a separate rule, since you still need to set the STS header on other HTTPS responses, not just the redirect. See <a href=\"https://webmasters.stackexchange.com/a/131970/1243\">my answer</a> to the following question on the Webmasters stack for more information on this, with example code:</p>\n<ul>\n<li><a href=\"https://webmasters.stackexchange.com/questions/115125/hsts-implementation-when-using-www-tld\">https://webmasters.stackexchange.com/questions/115125/hsts-implementation-when-using-www-tld</a></li>\n</ul>\n<blockquote>\n<p>Here, on question 4 I try to rename HTTPS to HTTPSaaa and then, with php, to get all server variable (from $_SERVER). I don't find HTTPSaaa. So this means that the flag is used only by htaccess ? So, I ask again. What's the reason for this flag/variable to exist ?</p>\n</blockquote>\n<p>Yes, it's only used by Apache/<code>.htaccess</code>. It is set only on the redirect response back to the client. Your PHP script is not processed in this time, so cannot read it.</p>\n<p>The reason would be to help with implementing HSTS, as described above.</p>\n<hr />\n<p>If you are interested in HSTS then see this related CodeReview question (and <a href=\"https://codereview.stackexchange.com/a/251218/6744\">my answer</a>) regarding the implementation of HSTS in <code>.htaccess</code>:</p>\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/questions/250805/hsts-recommendations-in-htaccess\">HSTS Recommendations in .htaccess</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T22:39:36.953",
"Id": "502046",
"Score": "1",
"body": "Thank you, MrWhite! A wonderful answer and so clear!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T10:26:17.577",
"Id": "502083",
"Score": "1",
"body": "[Please do not answer off-topic questions.](https://codereview.stackexchange.com/help/how-to-answer)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T11:05:09.517",
"Id": "502086",
"Score": "0",
"body": "@greybeard Sorry, but I didn't realise it was off-topic at the time I answered."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T15:04:46.607",
"Id": "254559",
"ParentId": "254552",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254559",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T12:58:59.217",
"Id": "254552",
"Score": "0",
"Tags": [
".htaccess",
"https"
],
"Title": "Understanding htaccess redirect to HTTPS and WWW"
}
|
254552
|
<p>On my app I'm checking the equality between an objects array property and a nested object property - based on the results I return a new objects array.</p>
<p>The <code>items</code> objects array:</p>
<pre><code>[{name: 'test', value: 1, category: 'a'},{name: 'test2', value: 2, category: 'b'},{name: 'test3', value: 3, category: 'c'}]
</code></pre>
<p>The <code>itemList</code> object:</p>
<pre><code>{testnum1: {name: 'test123', category: 'a'}, testnum2: {name: 'test234', category: 'b'}
</code></pre>
<p>I need to check the equality between the <code>category</code> properties and return the following objects array:</p>
<pre><code>[{name: 'test', itemCategory: 'testnum1'},{name: 'test2', itemCategory: 'testnum2'}]
</code></pre>
<p>This is what I did, any idea on how to make it more readable?</p>
<pre><code>const getCategorizedItems = items => {
const itemListCategories = Object.keys(itemList)
const categorizedItems= items.map(item=> {
const itemCategory = itemListCategories.find(category =>
item.category === itemList[category].category
)
if (itemCategory ) return {name: item.name, category: itemCategory }
})
.filter(f => f)
return categorizedItems
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T10:09:48.847",
"Id": "502081",
"Score": "2",
"body": "Welcome to CodeReview@SE. Please add to your question how the code presented is going to be used: What is it good for? (Re)Visit [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)"
}
] |
[
{
"body": "<p>Short review;</p>\n<ul>\n<li>Unless you are writing inline functions, you should stick to using <code>function</code></li>\n<li>Using semicolons is preferred, it takes skill and knowledge to avoid the pitfalls of not using semicolons</li>\n<li>You assign in 1 statement the value of <code>categorizedItems</code> and <code>return</code> it in the next, you might as well <code>return</code> immediately</li>\n<li>In essence you do a <code>find</code> within a <code>map</code>, not too fast, I would create a lookup structure before the <code>map</code></li>\n<li><code>itemList</code> seems like a terrible name, I would call it <code>categories</code></li>\n</ul>\n<p>I would counter-propose the following;</p>\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 items = [{name: 'test', value: 1, category: 'a'}, {name: 'test2', value: 2, category: 'b'}, {name: 'test3', value: 3, category: 'c'}];\nconst categories = {testnum1: {name: 'test123', category: 'a'}, testnum2: {name: 'test234', category: 'b'}};\n \nfunction getCategorizedItems(items, categories){\n //Desired output; [{name: 'test', itemCategory: 'testnum1'},{name: 'test2', itemCategory: 'testnum2'}]\n const categoriesMap = Object.fromEntries(Object.entries(categories).map((entry) => [entry[1].category, entry[0]]));\n return items.map(item => ({name: item.name, itemCategory:categoriesMap[item.category]})).filter(item => item.itemCategory);\n}\n\nconsole.log(getCategorizedItems(items, categories));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T15:31:35.043",
"Id": "254560",
"ParentId": "254553",
"Score": "4"
}
},
{
"body": "<p>I would start by extracting the relevant data from <code>itemList</code> and create a lookup object that maps the <code>category</code> to the relevant key/itemCategory.</p>\n<pre><code>const itemCategories = new Map(\n Object.entries(itemList)\n .map(([itemCategory, {category}]) => [category, itemCategory])\n);\n</code></pre>\n<p>With the above structure you can <code>filter</code> the <code>items</code> and only keep the items that have a <code>category</code> property that is present within the lookup object. After filtering the array you can <code>map</code> the data into the desired result.</p>\n<pre><code>items\n .filter(item => itemCategories.has(item.category))\n .map(item => ({\n name: item.name,\n itemCategory: itemCategories.get(name.category)\n }));\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const items = [{name: 'test', value: 1, category: 'a'}, {name: 'test2', value: 2, category: 'b'}, {name: 'test3', value: 3, category: 'c'}];\nconst itemList = {testnum1: {name: 'test123', category: 'a'}, testnum2: {name: 'test234', category: 'b'}};\n\nconst itemCategories = new Map(\n Object.entries(itemList)\n .map(([itemCategory, {category}]) => [category, itemCategory])\n);\n\nfunction getCategorizedItems(items) {\n return items\n .filter(item => itemCategories.has(item.category))\n .map(item => ({\n name: item.name,\n itemCategory: itemCategories.get(item.category)\n }));\n}\n\nconsole.log(getCategorizedItems(items));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T19:10:20.867",
"Id": "254565",
"ParentId": "254553",
"Score": "2"
}
},
{
"body": "<p>There is some very bad naming in the code. Names are too long and have overlapping abstractions. What is a category, there are two types <code>a</code>, <code>b</code>, or <code>c</code> and <code>testnum1</code> and <code>itemNum2</code></p>\n<p>Due to poor naming the function has lost so much semantic accuracy it takes a second look to see what it is doing.</p>\n<h2>What are you doing?</h2>\n<p><code>getCategorizedItems</code> getting categorized items??</p>\n<ul>\n<li><p>From the input example all items are already categorized. So the function is not really getting categorized items</p>\n</li>\n<li><p>The output has new categories <code>"a"</code> becomes <code>"test123"</code> so the items are being recategorized (or because there is a one to one match the cats are being transformed)</p>\n</li>\n<li><p>Each item is restructured, From <code>{name: 'test', value: 1, category: 'a'}</code> to <code>{name: 'test', category: 'testnum1'}</code></p>\n</li>\n<li><p>Items are filtered by existence of transformed category names.</p>\n</li>\n</ul>\n<h2>Rename</h2>\n<p>Naming the function <code>transformCategoriesRestructureAndFilter</code> is impractical so <code>recategorize</code> could be more apt within the context of the code</p>\n<p>As you are using <code>category</code> as an identifier, you should make it clear <code>categoryId</code> or <code>catId</code>, or even just <code>id</code>. Thus</p>\n<pre><code>// ignoring irrelevant data\nitemList = {testnum1: {catId: 'a'}, testnum2: {catId: 'b'}}; \nitems = [{name: '1', catId: 'a'},{name: '2', catId: 'b'},{name: '3', catId: 'c'}];\n</code></pre>\n<h3>Use appropriate data structures</h3>\n<p>The object <code>itemList</code> is a transformation and should be a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference, Map\">Map</a> for quick lookup. Either defined as such</p>\n<pre><code>const catIdTransform = new Map((["a", "testnum1"], ["b", "testnum2"]]);\n</code></pre>\n<p>Or constructed from <code>itemList</code></p>\n<pre><code>const catIdTransform = new Map(Object.entries(itemList).map(([name, {catId}]) => [catId, name]));\n</code></pre>\n<h2>Rewrite</h2>\n<p>Thus you can rewrite using the new naming.</p>\n<p>First transform the <code>catId</code> and then filter items without new ids.</p>\n<pre><code>function recategorize(items, idMap) {\n return items.map(item => ({...item, catId: idMap.get(item.catId)}))\n .filter(({catId}) => catId);\n}\n</code></pre>\n<h3>Working example</h3>\n<p>Using renamed data structures.</p>\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 items = [{name: '1', catId: 'a'},{name: '2', catId: 'b'},{name: '3', catId: 'c'}];\nconst catIdTransform = new Map([[\"a\", \"num1\"], [\"b\", \"num2\"]]);\n\nfunction recategorize(items, idMap) {\n return items.map(item => ({...item, catId: idMap.get(item.catId)}))\n .filter(({catId}) => catId);\n}\n\nconsole.log(recategorize(items, catIdTransform));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>or if you are forced to maintain the naming and existing data</p>\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 items = [{name: '1', category: 'a'}, {name: '2', category: 'b'}, {name: '3', category: 'c'}];\nconst itemList = {testnum1: {category: 'a'}, testnum2: {category: 'b'}}; \nconst categoryTransform = new Map(Object.entries(itemList).map(([name, {category}]) => [category, name]));\n\nfunction categorizedItems(items, idMap) { // at least drop the get\n return items.map(item => ({...item, category: idMap.get(item.category)}))\n .filter(({category}) => category);\n}\n\nconsole.log(categorizedItems(items, categoryTransform));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T05:25:09.750",
"Id": "254583",
"ParentId": "254553",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254560",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T13:15:31.373",
"Id": "254553",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Check equality of an objects array property and a nested object property"
}
|
254553
|
<p>I have an Android quiz app that I am building to learn kotlin / android app development. Here is an object I have which acts as one of many question builders.</p>
<p>Is there a better way of writing this?</p>
<pre><code> package com.maxcell.sumitup
import java.security.SecureRandom
import kotlin.math.roundToInt
object MultiplicationFactory {
//What this code does by step
// step1 - I set 4 variables using a random number generator to different values. Sometimes the first variable is bigger, sometimes the second variable etc
// step 2 - based on the first constructor value (ML) the main level is passed to variable templevel
// This step provides sets a variable called vInc and with the constructor value (SL) is passed to function SLM()
// The function SLM takes three variables (SL, Num, vInc) and then adds vInc as a flat increase, the new value is then further increased
// by the value of SL but this is expressed as a percentage, the value is then returned as an updated integer
// step 3, the Num variables are then passed to this step to create a sum as a string (the question) and as an expression (the answer)
// step 4 the object function returns a dataclass containing 5 values for use in the activity:
// SingleQuestion(ML,vType,vQuestion,vAnswer,vTime) - Currently the values used from the return is the question and the answer, i then create
// three other answers, shuffle all of them and pass them to buttons: See screenshot for example of a question being used within the activity
// this code is used in different places in the app where a question is required under the specific minigame
var Num1 = 0 //Number for use in sums
var Num2 = 0 //Number for use in sums
var Num3 = 0 //Number for use in sums
var Num4 = 0 //Number for use in sums
var GrabQuestion = 0 //base level numbers
var Operations = 0 // how many calculations someone has to do to reach the answer
var vType = "" //e.g. multiplication, this is redundant soon to be redundant once all question types migrated
var vQuestion = "" //The question as the user will see it
var vAnswer = 0 //answer to the sum
var vTime = 0 //Time to offer for the question
var vInc = 0 //sub level multiplier variable
var tempLevel = 0 //main level
var BSL = 0 // Bonus round selector
fun newQ(ML:Int, SL:Int,BR:Boolean,gameType:String):SingleQuestion {
vType = "Multiplication"
//map old game levels to new broader levelling logic - ignore this snippet in codereview
if (gameType=="FreeStyle"){
when (ML){
1->{tempLevel = rand(1,3)}
2->{tempLevel = rand(4,5)}
3->{tempLevel = rand(6,8)}
4->{tempLevel = rand(9,10)}
}} else {tempLevel = ML}
GrabQuestion = rand(1,23)
//Step 1
//to create a greater feel of randomness in the questions multiple possibilities created. These are base level figures
when(GrabQuestion){
1->{Num1 = rand(1,5);Num2 = rand(1,5);Num3 = rand(2,6);Num4 = rand(4,8)}
2->{Num1 = rand(2,6);Num2 = rand(1,5);Num3 = rand(2,6);Num4 = rand(4,8)}
3->{Num1 = rand(3,7);Num2 = rand(1,5);Num3 = rand(2,6);Num4 = rand(4,8)}
4->{Num1 = rand(4,8);Num2 = rand(1,5);Num3 = rand(2,6);Num4 = rand(4,8)}
5->{Num1 = rand(5,9);Num2 = rand(1,5);Num3 = rand(2,6);Num4 = rand(4,8)}
6->{Num1 = rand(6,10);Num2 = rand(7,11);Num3 = rand(2,6);Num4 = rand(4,8)}
7->{Num1 = rand(1,5);Num2 = rand(6,10);Num3 = rand(2,6);Num4 = rand(4,8)}
8->{Num1 = rand(2,6);Num2 = rand(5,9);Num3 = rand(2,6);Num4 = rand(4,8)}
9->{Num1 = rand(3,7);Num2 = rand(4,8);Num3 = rand(2,6);Num4 = rand(4,8)}
10->{Num1 = rand(4,8);Num2 = rand(3,7);Num3 = rand(2,6);Num4 = rand(4,8)}
11->{Num1 = rand(5,9);Num2 = rand(2,6);Num3 = rand(2,6);Num4 = rand(4,8)}
12->{Num1 = rand(6,10);Num2 = rand(1,5);Num3 = rand(2,6);Num4 = rand(4,8)}
13->{Num1 = rand(1,5);Num2 = rand(1,5);Num3 = rand(2,6);Num4 = rand(4,8)}
14->{Num1 = rand(2,6);Num2 = rand(2,6);Num3 = rand(2,6);Num4 = rand(4,8)}
15->{Num1 = rand(3,7);Num2 = rand(3,7);Num3 = rand(2,6);Num4 = rand(4,8)}
16->{Num1 = rand(4,8);Num2 = rand(4,8);Num3 = rand(2,6);Num4 = rand(4,8)}
17->{Num1 = rand(5,9);Num2 = rand(5,9);Num3 = rand(2,6);Num4 = rand(4,8)}
18->{Num1 = rand(6,10);Num2 = rand(6,10);Num3 = rand(2,6);Num4 = rand(4,8)}
19->{Num1 = rand(1,5);Num2 = rand(1,5);Num3 = rand(2,6);Num4 = rand(4,8)}
20->{Num1 = rand(1,5);Num2 = rand(2,6);Num3 = rand(2,6);Num4 = rand(4,8)}
21->{Num1 = rand(1,5);Num2 = rand(3,7);Num3 = rand(2,6);Num4 = rand(4,8)}
22->{Num1 = rand(1,5);Num2 = rand(4,8);Num3 = rand(2,6);Num4 = rand(4,8)}
23->{Num1 = rand(1,5);Num2 = rand(5,9);Num3 = rand(2,6);Num4 = rand(4,8)}
}
//when not a bonus round
//step2
if (BR==false){
//based on level increase base numbers (flat increase), based on sublevel increase numbers (%)
when (tempLevel){
1->{vInc = 0;Operations = 1;vTime = 10;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc)}
2->{vInc = 1;Operations = 1;vTime = 10;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc)}
3->{vInc = 2;Operations = 1;vTime = 10;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc)}
4->{vInc = 3;Operations = 1;vTime = 10;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc)}
5->{vInc = 4;Operations = 1;vTime = 10;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc)}
6->{vInc = 0;Operations = 2;vTime = 15;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc);Num3 = SLM(SL,Num3,vInc)}
7->{vInc = 1;Operations = 2;vTime = 15;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc);Num3 = SLM(SL,Num3,vInc)}
8->{vInc = 2;Operations = 2;vTime = 15;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc);Num3 = SLM(SL,Num3,vInc)}
9->{vInc = 3;Operations = 2;vTime = 15;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc);Num3 = SLM(SL,Num3,vInc)}
10->{vInc = 4;Operations = 2;vTime = 15;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc);Num3 = SLM(SL,Num3,vInc)}
}
//grab appropriate question format for number of calculations required
// step 3
when (Operations){
1->{vQuestion ="$Num1 \u00D7 $Num2";vAnswer = Num1 * Num2}
2->{vQuestion ="($Num1 \u00D7 $Num2) \u00D7 $Num3";vAnswer = (Num1 * Num2) *Num3}
else->{vQuestion ="$Num1 \u00D7 $Num2";vAnswer = Num1 * Num2}
}
} else {
//bonus games include different operators
//step 2
when (tempLevel){
in 1..3->{vInc = 0;BSL = rand(1,4);vTime = 20;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc);Num3 = SLM(SL,Num3,vInc);Num4 = SLM(SL,Num4,vInc)}
in 4..5->{vInc = 2;BSL = rand(1,4);vTime = 20;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc);Num3 = SLM(SL,Num3,vInc);Num4 = SLM(SL,Num4,vInc)}
in 6..8->{vInc = 4;BSL = rand(1,4);vTime = 20;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc);Num3 = SLM(SL,Num3,vInc);Num4 = SLM(SL,Num4,vInc)}
in 9..10->{vInc = 6;BSL = rand(1,4);vTime = 20;Num1 = SLM(SL,Num1,vInc);Num2 = SLM(SL,Num2,vInc);Num3 = SLM(SL,Num3,vInc);Num4 = SLM(SL,Num4,vInc)}
}
//grab appropriate question format for number of calculations required
//step 3
when (BSL){
1->{vQuestion ="($Num1 × $Num2) + ($Num3 x $Num4)";vAnswer = (Num1 * Num2) + (Num3 * Num4)}
2->{vQuestion ="$Num1 + ($Num2 × $Num3) + $Num4";vAnswer = Num1 + (Num2 * Num3) + Num4}
3->{vQuestion ="(($Num1 × $Num2) + $Num3) - $Num4";vAnswer = ((Num1 * Num2) + Num3) - Num4}
4->{vQuestion ="$Num1 + ($Num2 × $Num3) - $Num4";vAnswer = Num1 + (Num2 * Num3) -Num4}
}
}
//return question to the minigame
// step 4
return SingleQuestion(ML,vType,vQuestion,vAnswer,vTime)
}
}
// Function to provide a random number. Set the lowest number and highest number.
private fun rand(start: Int, end: Int): Int {
require(start <= end) { "Illegal Argument" }
val random = SecureRandom()
random.setSeed(random.generateSeed(20))
return random.nextInt(end - start + 1) + start
}
//This function is aimed at providing an optimisation capability.
// sb levels are 1-25 e.g sub level 1 increases each number by 1.01% up to 1.25% (1% increase to 25% increase)
// you can lower the division factor (e.g. /100 to /50) to create bigger gaps between sub levels
private fun SLM(subLevel:Int, num:Int, increment:Int):Int{
var multiplier = ((subLevel / 100)+1).toDouble()
var newNum = ((num + increment) * multiplier).roundToInt()
return newNum
}
</code></pre>
<p><img src="https://i.stack.imgur.com/cOIOxl.png" alt="screen shot" /></p>
<p>The screenshot shows a division question and my code is from a multiplication question builder but it's just to show how the data is used once returned</p>
<p>See <a href="https://codereview.stackexchange.com/questions/255289/generating-multiplication-questions-and-answers-for-a-quiz-style-app">Generating multiplication questions and answers for a quiz style app</a> for follow up</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T13:59:21.043",
"Id": "502015",
"Score": "1",
"body": "Please provide some more details, not in code but in pure English, about what your code is doing. Can you provide some examples? Screenshots? Anything to make the question clearer. See https://codereview.meta.stackexchange.com/a/6429/31562"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T14:27:25.340",
"Id": "502016",
"Score": "0",
"body": "I'll add some more info shortly to show the steps the code goes through. Screenshots not possible as this is an object class that returns a question which is then dealt with in a separate activity"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T14:44:21.790",
"Id": "502018",
"Score": "0",
"body": "Even screenshots from your application where the question is shown would be helpful. Any examples of what the output is from this code is helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T15:18:51.070",
"Id": "502023",
"Score": "0",
"body": "I have provided a broader explanation at the top and a screenshot as an example of one quiz in motion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T18:27:03.707",
"Id": "502035",
"Score": "1",
"body": "@UnknownError Sorry for being unclear, my recommendation was about adding the \"What this code does by step\" part outside of the code block (unless you actually want to have it as comments inside the code, in which case parts of a review could potentially address these comments as well)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T18:32:42.027",
"Id": "502036",
"Score": "0",
"body": "As you wanted a clearer explanation I thought I'd add it to my object as a note and then copied it over. For the purpose of this I'll jump on the laptop shortly and pull it out of code brackets and into main body so it can be read independently of the code block"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:46:36.523",
"Id": "502898",
"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](http://meta.codereview.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T16:07:40.650",
"Id": "502903",
"Score": "0",
"body": "How do you link two questions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T16:22:35.347",
"Id": "502904",
"Score": "0",
"body": "Drop a hyperlink to the old question in the new one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T16:35:00.843",
"Id": "502906",
"Score": "0",
"body": "And if I do that can I add a link to the new one at the bottom of this one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T19:29:03.293",
"Id": "502915",
"Score": "1",
"body": "@UnknownError Yes, absolutely"
}
] |
[
{
"body": "<h3>Readability</h3>\n<p>The most important part about any code is readability.</p>\n<p>BSL, ML, SL, BR, vInc, etc. might mean something to you, but it's not clear what it means by just looking at the names.</p>\n<p>Example:</p>\n<p><code>var BSL = 0 // Bonus round selector</code></p>\n<p>This would be much clearer as</p>\n<p><code>var bonusRoundSelector = 0</code></p>\n<p>You have done the same thing for a lot of your variables. In some cases it's even contradictory.</p>\n<p><code>var tempLevel = 0 //main level</code></p>\n<p>Is it temporary or main? Those are two very different things.</p>\n<p>Variables should be named so that they don't require a comment next to them about what their purpose is.</p>\n<hr />\n<h3>Declaring variables</h3>\n<p>All your variables are declared outside of the function scope, that is unnecessary, they can be moved to inside the <code>fun newQ</code> instead.</p>\n<p>Prefer using <code>val</code> instead of <code>var</code> whenever possible in Kotlin. You might get an error message from it but the solution to errors is to <strong>understand them</strong> and not workaround them just because you know how to workaround them.</p>\n<p>There's multiple steps to be involved but here's some things that I notice:</p>\n<ul>\n<li><code>Num1</code> should be called <code>num1</code> but you might want to try and come up with a different name for it as the four Num-variables does not seem very similar to me.</li>\n<li>If we would make <code>Num1</code> a <code>val</code> we would be told that it cannot be reassigned. That is because you give it a default value of 0. This already is a problem, what if <code>GrabQuestion</code> is not in the range of 1..23 ? You might think that it always is because of you calling <code>rand(1, 23)</code>, but what if there would one day be a bug in the rand function? Solutions: Use an <code>else</code> statement in <code>when</code> to throw an exception and don't initialize <code>Num1</code> to anything, declare it as <code>val num1: Int</code>.</li>\n<li>Num1 is mutated again in step2, all these steps could be extracted as different methods and their data stored in one or several <code>data class</code> structures. For example, <code>val numbers = initializeNumbers(grabQuestion)</code> to initialize the num1, num2, num3, num4 values.</li>\n</ul>\n<hr />\n<h3>Copied code</h3>\n<p>This is just an example, but <code>BSL</code> is always set to <code>rand(1,4)</code> so take it out of the duplication in the <code>when</code> and only do it once.</p>\n<p>The same goes for vTime, Num1, and many other values.</p>\n<p>Additionally, you have several magic numbers copy-pasted in your code, things like <code>vTime = 20</code> could maybe be <code>vTime = TIME_LONG</code> where <code>TIME_LONG</code> is declared as <code>const val TIME_LONG = 20</code></p>\n<hr />\n<h3>SecureRandom</h3>\n<p>First of all, it's not necessary to set the seed on SecureRandom, it can do that by itself.</p>\n<p>Secondly, I don't think it's necessary to use SecureRandom here at all. It's a Math Quiz, not a password generation service. Use <code>Random.Default</code> instead like this:</p>\n<pre><code>val random = Random.Default\nreturn random.nextInt(start, end + 1)\n</code></pre>\n<hr />\n<h3>Overall</h3>\n<p>The current code is difficult to read and difficult to maintain, using better variable naming and less code duplication and structuring the code into multiple separated methods for each step, this will improve drastically.</p>\n<p>I started refactoring the code but realized that it was a bit of work and that you wouldn't learn much by copy-pasting my code, but I promise you that your main method can be reduced to something like this:</p>\n<pre><code>val vType = "Multiplication"\nval level = determineLevel(gameType, ML)\nval grabQuestion: Int = rand(1, 23) //base level numbers\nvar numbers = initializeNumbers(grabQuestion)\n\nval operations = determineOperations(level)\nnumbers = processNumbersStep2(bonusRound, level)\n\nval questionAndAnswer = createQuestion(bonusRound, level, operations)\nreturn createQuestion(questionAndAnswer)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T21:09:41.240",
"Id": "502042",
"Score": "0",
"body": "Thank you for your feedback. This is really useful. Some of it doesn't yet make total sense but like you point out the purpose is to learn. I'm going to digest some of this, have a crack at making some changes and I'll report back. Thank you for taking the time to review and provide me some good food for thought"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T20:02:08.343",
"Id": "502268",
"Score": "0",
"body": "I have a lot to go through still but a quick initial question. With the naming of num1,2,3,4. Each represents a number in a sum e.g num1 x num2. I allow up to 4 as some questions require 4 variables. They can all be a different number but they are all numbers used in a sum. Based on that how would you better describe them? Or does that help clarify how they not that different from eachother?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T21:02:50.907",
"Id": "502271",
"Score": "0",
"body": "@UnknownError My main concern about them is that if they are indeed 4 similar variables, they would best be represented by an array, but they seem to be initialized and set somewhat differently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T00:55:48.823",
"Id": "502829",
"Score": "0",
"body": "I still have some areas to look at but my first run through has been added as an addition to my OP, am I on the right track or have I misunderstood your feedback?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T09:22:08.263",
"Id": "502860",
"Score": "0",
"body": "@UnknownError That looks like a good start, yes, but please post a new follow-up question instead of editing an existing one"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:59:24.820",
"Id": "502900",
"Score": "0",
"body": "So we should not show progress made following feedback? It was an addition rather than re write to doesn't lose its original intent. I also thought that one question can be open ended over here which suggests there is the potential for ongoing dialogue. Would some of that history not be beneficial for others to see rather than potentially having to find 2,3,4 versions of a question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T19:31:11.533",
"Id": "502916",
"Score": "1",
"body": "@UnknownError Having multiple code samples, some more improved, some less, causes a lot of confusion when multiple answers appear, as it is unclear which answer addresses which code. (We have some experience of this happening on this site) So the recommended way is to post multiple questions and add links between them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T21:01:56.630",
"Id": "502921",
"Score": "0",
"body": "That makes a lot of sense. Thank you for explaining that to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T12:45:29.473",
"Id": "503660",
"Score": "0",
"body": "@UnknownError Will you be posting any follow-up?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T14:52:11.467",
"Id": "503677",
"Score": "0",
"body": "Yes, I will post a follow up tonight under a new question and provide the links :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T15:38:42.463",
"Id": "503682",
"Score": "0",
"body": "Link added to OP"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T19:16:12.263",
"Id": "254566",
"ParentId": "254554",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254566",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T13:17:18.313",
"Id": "254554",
"Score": "1",
"Tags": [
"android",
"classes",
"kotlin"
],
"Title": "Generating mathematical questions and answers"
}
|
254554
|
<p><em>This is an updated question with new code, taking into account your comments from last time: <a href="https://codereview.stackexchange.com/questions/254268/car-computer-in-python-gps-tracking">Car computer in python / GPS tracking</a></em></p>
<p>I have an old car that I use for long distance driving and have coded an onboard computer based on a Raspberry Pi 3 and a few other modules. I use a FONA 808 from Adafruit as the cellular modem (via serial), the Sparkfun NEO-M9N as a GPS sensor (i2c), an OLED display (i2c) and a small temperature sensor via 1-wire. Here is a picture of the computer in action, just so you have a better picture of it:</p>
<p><a href="https://i.stack.imgur.com/x30Tc.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/x30Tc.jpg" alt="car computer" /></a></p>
<p>Notable improvements compared to version 1 in the old questions are (in a nutshell):</p>
<ul>
<li>config.ini file</li>
<li>communication with remote server either per DB direct insert or per POST to a PHP script</li>
<li>cleaned up use of globals, imports</li>
<li>using the DRY principle as much as possible, creating new helper functions</li>
<li>shortening of code where possible</li>
<li>testing function for GPS module</li>
</ul>
<p>Without further ado, here the code, split up in a few files:</p>
<p><strong>car_computer.py</strong></p>
<pre><code>import os
from threading import Thread
import glob
import serial
import board
import subprocess
import smbus
import time
from time import sleep
import datetime
import configparser
import re
import urllib
from urllib import request
import random
from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import sh1106
from PIL import ImageFont, Image, ImageDraw
import pymysql
import csv
import json
import hashlib
import pynmea2
from haversine import haversine, Unit
config = configparser.ConfigParser()
config.read('/home/pi/Desktop/car_computer.ini')
################## start display ##################
device = sh1106(i2c(port=1, address=config['display']['i2c_port']), rotate=0)
device.clear()
pending_redraw = False
output = Image.new("1", (128,64))
add_to_image = ImageDraw.Draw(output)
def setup_font(font_filename, size):
return ImageFont.truetype(os.path.join(config['general']['folder'],config['general']['folder_fonts'],font_filename), size)
fa_solid = setup_font('fa-solid-900.ttf', 12)
fa_solid_largest = setup_font('fa-solid-900.ttf', 40)
text_largest = setup_font('digital-7.ttf', 58)
text_medium = setup_font('digital-7.ttf', 24)
text_small = setup_font('digital-7.ttf', 18)
icons = { #to look up the icons on FontAwesome.com, remove quote marks and \u from the search query
"save": "\uf56f","cloud": "\uf0c2","check": "\uf058","upload": "\uf382","no_conn": "\uf127","location": "\uf124","question": "\uf128","altitude": "\uf077","distance": "\uf1b9","temperature": "\uf2c9" }
def wipe(zone):
add_to_image.rectangle(tuple(int(v) for v in re.findall("[0-9]+", config['display'][zone])), fill="black", outline ="black")
def icon(zone,name):
add_to_image.text(tuple(int(v) for v in re.findall("[0-9]+", config['display'][zone])), icons[name], font=fa_solid, fill="white")
def text(zone,text,fontsize=text_medium):
add_to_image.text(tuple(int(v) for v in re.findall("[0-9]+", config['display'][zone])), text, font=fontsize, fill="white")
################## upload data from GPS folder via FONA to MySQL ##################
def fix_nulls(s):
return (line.replace('\0', '') for line in s)
def upload_data():
global pending_redraw
while True:
sleep(5)
current_dir = os.path.join(config['general']['folder'],config['general']['folder_data'])
archive_dir = os.path.join(config['general']['folder'],config['general']['folder_data_archive'])
path, dirs, files = next(os.walk(current_dir))
file_count = len(files)
if file_count < 2:
print("Not enough GPS.csv files found so it's probably in use now or doesn't exist")
return
list_of_files = glob.glob(current_dir+"/*.csv")
oldest_file = min(list_of_files, key=os.path.getctime)
oldest_file_name = os.path.basename(oldest_file)
try:
openPPPD()
if config['db']['mode'] == "db":
print("mode = db")
db = pymysql.connect(config['db']['db_host'],config['db']['db_user'],config['db']['db_pw'],config['db']['db_name'])
cursor = db.cursor()
csv_data = csv.reader(fix_nulls(open(oldest_file)))
next(csv_data)
for row in csv_data:
if row:
statement = 'INSERT INTO '+config['db']['db_table']+' (gps_time, gps_lat, gps_long, gps_speed) VALUES (%s, %s, %s, %s)'
cursor.execute(statement,row)
print("Committing to db")
db.commit()
cursor.close()
if config['db']['mode'] == "server":
print("mode = server")
csv_data = csv.reader(fix_nulls(open(oldest_file)))
next(csv_data)
row_nb = 1
row_data = {}
rows_encoded_nb = 1
rows_encoded = {}
for row in csv_data:
if row:
row_data[row_nb] = {'gps_time': int(row[0]), 'gps_lat' : round(float(row[1]), 5), 'gps_long' : round(float(row[2]), 5), 'gps_speed' : round(float(row[3]), 1)}
if row_nb % int(config['db']['server_batchsize']) == 0:
rows_encoded[rows_encoded_nb] = row_data
rows_encoded_nb +=1
row_data = {}
row_nb +=1
rows_encoded[rows_encoded_nb] = row_data
row_data = {}
for i in rows_encoded :
checksum = hashlib.md5(str(rows_encoded[i]).encode())
checksum = checksum.hexdigest()
req = request.Request(config['db']['server_addr'], method="POST")
req.add_header('Content-Type', 'application/json')
data = {
"hash": checksum,
"ID": config['db']['server_ID'],
"pw": config['db']['server_pw'],
"data": rows_encoded[i]
}
data = json.dumps(data)
data = data.encode()
r = request.urlopen(req, data=data)
print(r.read())
#sleep(1)
closePPPD()
print("Successfully committed to db")
wipe('GPRS_ZONE')
icon('GPRS_START',"check")
pending_redraw = True
os.rename(current_dir+"/"+oldest_file_name, archive_dir+"/archive_"+oldest_file_name)
sleep(60)
wipe('GPRS_ZONE')
except Exception as e:
print("Database error:", e)
wipe('GPRS_ZONE')
icon('GPRS_START',"no_conn")
pending_redraw = True
closePPPD()
sleep(60)
wipe('GPRS_ZONE')
pending_redraw = True
return
sleep(300)
################## config and start GPS ##################
BUS = None
reading_nr = 1
reading_nr_upload = 1
reading_nr_upload_nbrowsinlog = 0
total_km = 0
prev_lat = 0
prev_long = 0
def connectBus():
global BUS
BUS = smbus.SMBus(1)
def debug_gps():
sleep(1)
time = datetime.datetime.now()
gga1 = pynmea2.GGA('GN', 'GGA', (time.strftime("%H%M%S"), '1929.045', 'S', '02410.516', 'E', '1', '04', '2.6', '69.00', 'M', '-33.9', 'M', '', '0000'))
gga2 = pynmea2.GGA('GN', 'GGA', (time.strftime("%H%M%S"), '1929.075', 'S', '02410.506', 'E', '1', '04', '2.6', '73.00', 'M', '-33.9', 'M', '', '0000'))
rmc1 = pynmea2.RMC('GN', 'RMC', (time.strftime("%H%M%S"), 'A', '1929.055', 'S', '02411.516', 'E', '28', '076.2', time.strftime("%d%m%y"), 'A'))
rmc2 = pynmea2.RMC('GN', 'RMC', (time.strftime("%H%M%S"), 'A', '1929.045', 'S', '02411.506', 'E', '29', '076.2', time.strftime("%d%m%y"), 'A'))
nmea = [gga1,rmc1,gga2,rmc2]
return str(random.choice(nmea))
def parseResponse(gpsLine):
global pending_redraw
gpsChars = ''.join(chr(c) for c in gpsLine)
##### uncomment only for testing when the GPS chip has no reception #####
gpsChars = debug_gps()
#print(gpsChars)
if "GGA" in gpsChars:
if ",1," not in gpsChars:
print("GGA?")
wipe('STATUS_ICON_ZONE')
wipe('STATUS_ZONE')
icon('STATUS_ICON_START', "location")
icon('STATUS_START', "question")
pending_redraw = True
sleep(1)
return False
try:
nmea = pynmea2.parse(gpsChars, check=True)
if "0.0" in str(nmea.latitude) or "0.0" in str(nmea.longitude):
return False
#show that we have a location and delete whatever was there
wipe('STATUS_ICON_ZONE')
icon('STATUS_ICON_START', "location")
wipe('STATUS_ZONE')
## update altitude
icon('ALTI_ICON_START', "altitude")
wipe('ALTI_ZONE')
text('ALTI_START', str('%.0f'%(nmea.altitude)))
## update total distance
global reading_nr
global total_km
global prev_lat
global prev_long
dist = 0
if reading_nr != 1:
dist = haversine(((float(prev_lat)), (float(prev_long))), ((float(nmea.latitude)), (float(nmea.longitude))))
total_km = total_km+dist
icon('DIST_ICON_START', "distance")
wipe('DIST_ZONE')
text('DIST_START', "%0.1f" % total_km)
prev_lat = nmea.latitude
prev_long = nmea.longitude
pending_redraw = True
reading_nr +=1
except Exception as e:
print("GGA parse error:", e)
wipe('STATUS_ZONE')
pending_redraw = True
pass
if "RMC" in gpsChars:
if ",A," not in gpsChars: # 1 for GGA, A for RMC
print("RMC?")
wipe('STATUS_ICON_ZONE')
wipe('STATUS_ZONE')
icon('STATUS_ICON_START', "location")
icon('STATUS_START', "question")
pending_redraw = True
sleep(1)
return False
try:
nmea = pynmea2.parse(gpsChars, check=True)
if "0.0" in str(nmea.latitude) or "0.0" in str(nmea.longitude):
return False
#show that we have a location and delete whatever was there
wipe('STATUS_ICON_ZONE')
icon('STATUS_ICON_START', "location")
wipe('STATUS_ZONE')
## update speed
wipe('SPEED_ZONE')
text('SPEED_START', str('%.0f'%(nmea.spd_over_grnd*1.852)), fontsize=text_largest)
## log every log_frequency nth GPS coordinate in CSV file
global reading_nr_upload
global reading_nr_upload_nbrowsinlog
if reading_nr_upload % int(config['gps']['log_frequency']) == 0:
t = datetime.datetime.combine(nmea.datestamp, nmea.timestamp).strftime("%s")
d = datetime.datetime.combine(nmea.datestamp, nmea.timestamp).strftime("%Y%m%d%H")
filename = os.path.join(config['general']['folder'],config['general']['folder_data'],'gps_' + d + '.csv')
with open(filename, 'a', newline='') as csvfile:
gps_writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
gps_writer.writerow([t, nmea.latitude, nmea.longitude, nmea.spd_over_grnd*1.852])
reading_nr_upload_nbrowsinlog +=1
#print("Added to log. Total in Log from this session is", reading_nr_upload_nbrowsinlog)
wipe('STATUS_ZONE')
icon('STATUS_START',"save")
reading_nr_upload +=1
pending_redraw = True
except Exception as e:
print("RMC parse error:", e)
wipe('STATUS_ZONE')
pending_redraw = True
pass
def readGPS():
c = None
response = []
try:
while True: # Newline, or bad char.
global BUS
c = BUS.read_byte(int(config['gps']['i2c_port'], 16))
if c == 255:
return False
elif c == 10:
break
else:
response.append(c)
parseResponse(response)
except IOError:
time.sleep(0.5)
connectBus()
connectBus()
def updateGPS():
while True:
readGPS()
################## config external thermometer ##################
def update_temp_ext(temp_signature='t=', update_interval=config['temp_ext']['update_interval']):
global pending_redraw
icon('TEMP_ICON_START', "temperature")
base_dir = config['temp_ext']['w1_folder']
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
while True:
f = open(device_file, 'r')
lines = f.readlines()
f.close()
equals_pos = lines[1].find(temp_signature)
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = round(float(temp_string) / 1000.0)
wipe('TEMP_ZONE')
text('TEMP_START', str(temp_c))
pending_redraw = True
time.sleep(int(update_interval))
################## update display ##################
def update_display():
sleep(0.5)
while True:
global pending_redraw
if pending_redraw:
device.display(output)
pending_redraw = False
time.sleep(0.2)
################## start cellular connection ##################
def openPPPD():
subprocess.call("sudo pon fona", shell=True)
print("FONA on")
wipe('GPRS_ZONE')
icon('GPRS_START', "cloud")
global pending_redraw
pending_redraw = True
sleep(20)
try:
urllib.request.urlopen(config['db']['ping'])
print("Connection is on")
wipe('GPRS_ZONE')
icon('GPRS_START', "upload")
pending_redraw = True
return True
except:
print("Connection error")
wipe('GPRS_ZONE')
icon('GPRS_START', "no_conn")
pending_redraw = True
return False
# Stop PPPD
def closePPPD():
print("turning off PPPD")
subprocess.call("sudo poff fona", shell=True)
print("turned off")
return True
################## threading and program execution ##################
if __name__ == '__main__':
temp_ext_thread = Thread(target = update_temp_ext)
display_thread = Thread(target=update_display)
gps_thread = Thread(target = updateGPS)
data_thread = Thread(target = upload_data)
display_thread.start()
gps_thread.start()
data_thread.start()
temp_ext_thread.start()
display_thread.join()
</code></pre>
<p><strong>car_computer.ini</strong></p>
<pre><code>[general]
folder = /home/pi/Desktop
folder_fonts = fonts
folder_data = data/gps
folder_data_archive = data/gps/archive
[db]
mode = server
ping = https://XXX
db_host = XXX
db_user = XXX
db_pw = XXX
db_name = XXX
db_table = gps_data
server_addr = https://www.XXX.com/gps_logger.php
server_batchsize = 50
server_ID = XXX
server_pw = XXX
[display]
i2c_port = 0x3c
### coordinates always: padding-left, padding-top. the first pair of zone is mostly = start (except to offset small icons)
# temp_ext
TEMP_ZONE = [(14,44), (36,64)]
TEMP_START = (14,44)
TEMP_ICON_ZONE = [(0,48), (15,64)]
TEMP_ICON_START = (3,48)
# alti
ALTI_ZONE = [(14,22), (69,40)]
ALTI_START = (14,22)
ALTI_ICON_ZONE = [(0,24), (15,40)]
ALTI_ICON_START = (0,26)
# distance
DIST_ZONE = [(14,0), (69,21)]
DIST_START = (14,0)
DIST_ICON_ZONE = [(0,4), (15,21)]
DIST_ICON_START = (0,4)
# speed
SPEED_ZONE = [(66,0), (128,45)]
SPEED_START = (66,0)
# GPRS status
GPRS_ZONE = [(114,46), (128,64)]
GPRS_START = (114,50)
# GPS status, incl. GPS startup icon
STATUS_ICON_ZONE = [(70,50), (88,64)]
STATUS_ICON_START = (70,50)
STATUS_ZONE = [(86,46), (113,64)]
STATUS_START_TEXT = (86,46)
STATUS_START = (86,50)
[gps]
i2c_port = 0x42
log_frequency = 5
[temp_ext]
update_interval = 30
w1_folder = /sys/bus/w1/devices/
</code></pre>
<p><strong>gps_logger.php</strong></p>
<pre><code><?php
$mysqli = new mysqli($hostname_db, $username_db, $password_db,$database_db);
$json = file_get_contents('php://input');
if($data = json_decode($json)) {
$sql = "SELECT * FROM gps_computers WHERE gc_ID = ? AND gc_pw = ?";
$statement = $mysqli->prepare($sql);
$statement->bind_param('is', $data->ID, $data->pw);
if(!$statement->execute()) { die("Query error: ".$statement->error); }
$auth = $statement->get_result();
$totalRows_auth = $auth->num_rows;
if($totalRows_auth == 1) {
echo "";
} else {
echo "no auth match found";
die;
}
$i = 0;
foreach ($data->data as $key => $record) {
$sql = "SELECT * FROM gps_data WHERE gps_time = ? AND gps_computerID = ?";
$statement = $mysqli->prepare($sql);
$statement->bind_param('ii', $record->gps_time, $data->ID);
if(!$statement->execute()) { die("Query error: ".$statement->error); }
$doublecheck = $statement->get_result();
$totalRows_doublecheck = $doublecheck->num_rows;
if($totalRows_doublecheck != 1) {
$i++;
$sql = "INSERT INTO `gps_data` (`gps_time`, `gps_lat`, `gps_long`, `gps_speed`, `gps_computerID`) VALUES (?, ?, ?, ?, ?);";
$statement = $mysqli->prepare($sql);
$statement->bind_param('isssi', $record->gps_time, $record->gps_lat, $record->gps_long, $record->gps_speed, $data->ID);
if(!$statement->execute()) { die("Query error: ".$statement->error); }
}
}
echo $i." records inserted";
} else {
echo "error reading json";
}
?>
</code></pre>
<p>I have to say I'm quite proud of how it's turned out! Happy to edit the question if you want more info to better help :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T14:54:10.107",
"Id": "502020",
"Score": "0",
"body": "How is the PHP hosted - in an instance of Apache (or something else)? Why not just use more Python, for uniformity?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T14:56:50.440",
"Id": "502022",
"Score": "0",
"body": "It's on a shared host running on Apache. I guess I could do more python, didnt really think of it as I've started programming using php and it always was my go-to. Other than consistency, would you see any advantages in using python?"
}
] |
[
{
"body": "<p>First, I need to say that this is a really cool project; quite fun.</p>\n<p>You ask:</p>\n<blockquote>\n<p>Other than consistency, would you see any advantages in using python?</p>\n</blockquote>\n<p>Bad code can be written in any language, but <a href=\"http://www.phpsadness.com/\" rel=\"nofollow noreferrer\">it's really easy to write bad code in PHP</a>. At the risk of starting a language-religion flame war, there is not a single application I could in good conscience recommend to a new PHP build for which other languages aren't a better fit. Fun fact: according to Wikipedia,</p>\n<blockquote>\n<p>72% of PHP websites use discontinued versions of PHP.</p>\n</blockquote>\n<p>As such, many of the greyed-out entries in PHP Sadness still have significant impact. So less "use Python instead" and more "use something that isn't PHP". <em>Anyway</em>, on to less controversial topics:</p>\n<h2>Global code</h2>\n<p>Move lines like</p>\n<pre><code>device = sh1106(i2c(port=1, address=config['display']['i2c_port']), rotate=0)\ndevice.clear()\npending_redraw = False\noutput = Image.new("1", (128,64))\nadd_to_image = ImageDraw.Draw(output)\n\nfa_solid = setup_font('fa-solid-900.ttf', 12)\nfa_solid_largest = setup_font('fa-solid-900.ttf', 40)\ntext_largest = setup_font('digital-7.ttf', 58)\ntext_medium = setup_font('digital-7.ttf', 24)\ntext_small = setup_font('digital-7.ttf', 18)\nicons = { #to look up the icons on FontAwesome.com, remove quote marks and \\u from the search query \n "save": "\\uf56f","cloud": "\\uf0c2","check": "\\uf058","upload": "\\uf382","no_conn": "\\uf127","location": "\\uf124","question": "\\uf128","altitude": "\\uf077","distance": "\\uf1b9","temperature": "\\uf2c9" }\n</code></pre>\n<p>out of global scope. Among a long list of other reasons, this harms testability and pollutes your namespace. Also, since this is an embedded environment, I'd be worried about memory usage being impacted by long-lived references that needn't be.</p>\n<p>Consider making classes, and/or moving code into free functions, and/or moving those classes and functions into more narrow-purpose Python module files.</p>\n<h2>Style</h2>\n<p>Get a linter. My favourite is PyCharm. It will help you learn the PEP8 standard, including (significantly) untangling your function definitions by separating them with two empty new lines.</p>\n<h2>Pathlib</h2>\n<p>These:</p>\n<pre><code> current_dir = os.path.join(config['general']['folder'],config['general']['folder_data'])\n archive_dir = os.path.join(config['general']['folder'],config['general']['folder_data_archive'])\n</code></pre>\n<p>will be simplified by the use of <code>pathlib</code>. Store a <code>Path</code> for your <code>config['general']['folder']</code> so that you don't need to re-traverse that configuration object. Drop your <code>os.path</code> calls.</p>\n<h2>Application location</h2>\n<pre><code>/home/pi/\n</code></pre>\n<p>is a bad home for an application. You should take this opportunity to learn how standard Unix applications store their data. Configuration in <code>/etc</code>, application script in <code>/usr/bin</code>, data files in <code>/usr/share</code>, etc.</p>\n<p><code>pi</code> is a login user, and your device has internet connectivity. I'm unclear on how your application is started and whether you intend on running it as a service, but whatever the case, you would benefit from making a jail that has this application run as a heavily permissions-restricted, dedicated-purpose user.</p>\n<h2>Method complexity</h2>\n<p>Break up <code>upload_data</code> into multiple subroutines, given its length and complexity.</p>\n<h2>Connection management</h2>\n<p>Surround your unprotected <code>connect</code>/<code>close</code>:</p>\n<pre><code> db = pymysql.connect(config['db']['db_host'],config['db']['db_user'],config['db']['db_pw'],config['db']['db_name'])\n cursor = db.cursor()\n cursor.close()\n</code></pre>\n<p>in a <code>try</code>/<code>finally</code>. I would stop short of <a href=\"https://stackoverflow.com/questions/31214658/can-i-use-pymysql-connect-with-with-statement\">using a with statement</a> since that library has surprising behaviour on <code>__exit__</code>.</p>\n<h2>Data vs. config</h2>\n<p>These are good examples of config entries:</p>\n<pre><code>mode = server\nping = https://XXX\ndb_host = XXX\ndb_user = XXX\ndb_pw = XXX\ndb_name = XXX\n</code></pre>\n<p>These are not:</p>\n<pre><code>TEMP_ZONE = [(14,44), (36,64)]\nTEMP_START = (14,44)\nTEMP_ICON_ZONE = [(0,48), (15,64)]\nTEMP_ICON_START = (3,48)\n</code></pre>\n<p>So far as I can tell, those are UI coordinates. They aren't meaningful for a user to configure and should instead live in the application, perhaps in a dedicated UI constants file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T00:24:33.260",
"Id": "254674",
"ParentId": "254555",
"Score": "4"
}
},
{
"body": "<p>There is a potential race condition in <code>update_display()</code></p>\n<pre><code>def update_display():\n sleep(0.5)\n while True:\n global pending_redraw\n if pending_redraw: <-- test flag\n device.display(output) possible race condition in between\n pending_redraw = False <-- clear flag\n time.sleep(0.2)\n</code></pre>\n<p>If one of the other threads sets <code>pending_redraw</code> to <code>True</code> after this thread checks <code>if pending_redraw:</code> but before it sets <code>pending_redraw = False</code> (e.g., during the call to <code>device.display(output)</code>), the <code>True</code> will be lost.</p>\n<h3>configparser</h3>\n<p><code>configparser.ConfigParser</code> supports value interpolation. This let's you write the directory configurations like so:</p>\n<pre><code>[general]\nfolder = /home/pi/Desktop\nfolder_fonts = %(folder)/fonts\nfolder_data = %(folder)/data/gps\nfolder_data_archive = %(folder)/data/gps/archive\n</code></pre>\n<p>And then access the directories without needing <code>os.path.join()</code>:</p>\n<pre><code>dir = config['general']['folder_data']\narchive_dir = config['general']['folder_data_archive']\n</code></pre>\n<p><code>ConfigParser</code> include methods such as <code>getint()</code>, <code>getfloat()</code> and <code>getboolean</code>:</p>\n<pre><code>c = BUS.read_byte(config['gps'].getint('i2c_port'), 16))\n</code></pre>\n<p>And you can define your own such methods:</p>\n<pre><code>def getcoord(string):\n return tuple(int(v) for v in re.findall("[0-9]+", string))\n\ndef getpath(string):\n return pathlib.Path(string)\n\nconfig = configparser.ConfigParser(\n converters={'coord':getcoord, 'path':getpath, 'zone':getcoord}\n )\n</code></pre>\n<p>then other code can be simpler:</p>\n<pre><code>def wipe(zone):\n add_to_image.rectangle(config['display'].getzone(zone),\n fill="black", outline ="black")\n</code></pre>\n<p>or</p>\n<pre><code>def setup_font(font_filename, size):\n return ImageFont.truetype(\n config['general'].getpath('folder_fonts') / font_filename,\n size)\n</code></pre>\n<h3><code>upload_data()</code></h3>\n<p><code>config</code> is loaded once at the beginning of the application. Yet <code>upload_data</code> reloads <code>current_dir</code> and <code>archive_dir</code> inside a <code>while True:</code> loop. Move them before the loop.</p>\n<p>The code uses <code>os.walk()</code> to get a list of files and then uses <code>glob.glob()</code> to get the list again a few lines later. Get the list just once. Also, the file names include a date component, so you can just grab the <code>max()</code> filename</p>\n<pre><code>file_paths = list(current_dir.glob("*.csv")) #<-- assuming use `getpath()` \nif len(file_paths) < 2:\n print("Not enough GPS.csv files found so it's probably in use now or doesn't exist")\n\nelse:\n oldest_file = max(file_paths)\n oldest_file_name = oldest_file.name\n</code></pre>\n<p><code>OpenPPPD()</code> could be a context manager used in a <code>with</code> statement so that the cellphone connection gets closed automatically. Look at <code>@contextlib.contextmanager</code></p>\n<p>Catching bare exceptions using <code>except Exception as e:</code> is generally a bad idea. Specify the exception or a tuple of exceptions that you expect could occur. Note that <code>os.rename()</code> might have raised an exception, in which case <code>ClosePPPD()</code> would have already been called when the exception handler runs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T20:55:03.143",
"Id": "503524",
"Score": "0",
"body": "Thanks for the input, that’s really helpful! I had heard of the rave condition thing but I’m not sure of how to address it. Is it something I just have to live with?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T22:40:50.160",
"Id": "503526",
"Score": "1",
"body": "@DamienBourdonneau, in this case the race condition probably doesn't matter. One of the other threads might set `pending_redraw = True` just before `update_display` clears it. So a redraw may get missed. But something will change (GPS, temp, ?) and that thread will cause a display update soon anyway. I just point it out, because using threads can have some gotchas."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T21:49:21.763",
"Id": "255028",
"ParentId": "254555",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T13:32:36.530",
"Id": "254555",
"Score": "8",
"Tags": [
"python",
"raspberry-pi"
],
"Title": "Car computer in Python / GPS tracking VERSION 2"
}
|
254555
|
<p>I have an array of objects, <code>reviews</code> which I get from an API endpoint. This object looks like this:</p>
<pre class="lang-javascript prettyprint-override"><code>[
{ name: "Facebook", count: 50 },
{ name: "Google", count: 43 },
{ name: "TripAdvisor", count: 67 },
{ name: "Other", count: 130 }
]
</code></pre>
<p>I have a <a href="https://www.chartjs.org/" rel="noreferrer">chart.js</a> Pie chart that I'm feeding this data to. I'm using the <code>name</code> for the <code>labels</code> and the <code>count</code> for the size of each slice of the pie chart. Now, due to how chart.js works, I have to supply some hexadecimal colors to use as background colors, and the order in which the background color is being defined matters if I want the labels to match the colors properly. For example, if the order of the labels is <code>[A, B, C]</code>, an array of colors like <code>[red, green, blue]</code> means that A = red, B = green and C = blue. The problem is that the <code>reviews</code> array comes in a random order every single time from the API (I don't have control over the API and the data it gives me), so I can't just have a simple, predetermined array.</p>
<p>As far as I see, I have two options, I either sort the <code>reviews</code> array in some way, or I iterate over the data I get from the API and return an array based on some simple switch statements. I opted for the 2nd option, as it seems simpler for my usecase.</p>
<p>My current solution looks like this</p>
<pre class="lang-javascript prettyprint-override"><code>const chartBackgroundColor = collection => {
let colorArray = [];
const itemArray = collection.map(data => data.name);
itemArray.forEach(item => {
switch (item) {
case "TripAdvisor":
colorArray.push("#00B98B");
break;
case "Google":
colorArray.push("#FFBD00");
break;
case "Facebook":
colorArray.push("#4B6DAA");
break;
default:
colorArray.push("#D9D9D9");
break;
}
}
)
return colorArray;
}
</code></pre>
<p>The method works fine, but I was just curious whether there was some more elegant way of handling this issue, and whether a switch case is appropriate in this situation rather than a if/ifel/else tree.</p>
|
[] |
[
{
"body": "<p>I would</p>\n<ul>\n<li>Encapsulate the names and colors in a data structure</li>\n<li>Use <code>.map</code> instead of <code>.forEach</code></li>\n</ul>\n<p>So something like this;</p>\n<pre><code>function chartBackgroundColor(collection){\n const nameColorMap = {\n "TripAdvisor": "#00B98B",\n "Google": "#FFBD00",\n "Facebook": "#4B6DAA",\n };\n return collection.map(data => nameColorMap[data.name] || "#D9D9D9");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T14:48:15.443",
"Id": "502019",
"Score": "0",
"body": "Really nice one! Thanks for the help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T07:27:47.693",
"Id": "502062",
"Score": "0",
"body": "Just as a small potential improvement, would it not be worthwhile declaring `nameColorMap` outside of the function? Means it could be used elsewhere (if exported) and won't be redeclared each time the function is run. I also believe the `=` sign should be removed on the return. Not sure if that's valid JS."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T07:32:15.913",
"Id": "502063",
"Score": "1",
"body": "@DaneBrouwer if the map were to be used outside of this function -> Totally yes. Otherwise -> No. I imagine the speed gain would be minimal but the memory increase would be permanent."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T14:36:37.747",
"Id": "254558",
"ParentId": "254557",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "254558",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T14:17:30.480",
"Id": "254557",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Javascript function to return an array that needs to be in a specific order, depending on the order of a different array"
}
|
254557
|
<p>I have a requirement that is summarized below.</p>
<pre><code>void update()
{
| | | |
| | | |
| | | |
\| \| \| \|
=============
meat <--- Only one thread must execute here, the rest should skip it.
=============
| | | | <--- Other threads wait here until the "first" thread is done w/ "meat"
| | | |
| | | |
|/ |/ |/ |/
}
</code></pre>
<p>From an outsider perspective, "meat" should be executed just once (by the first thread that encounters it)</p>
<p><a href="https://stackoverflow.com/questions/38312930/using-condition-variable-to-trigger-threads-one-at-a-time?noredirect=1&lq=1">This</a> post is similar but differs in that it also requires other threads to execute the meat code block one at a time.</p>
<pre class="lang-cpp prettyprint-override"><code>// testExecutive.cpp
#include <atomic>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
struct Target {
int nhits = 0;
inline void hit() { ++nhits; }
};
struct Executive {
Executive() = delete;
Executive(int _Id, Target &_Tgt) : m_Id(_Id), m_Ready(false), m_Tgt(_Tgt) {}
void update() {
{ // only one thread can execute this
std::scoped_lock<std::mutex> lk(m_Mtx);
// std::cout << "++Acquired lk " << m_Id << " | tid: " <<
// std::this_thread::get_id() << "++\n";
if (!m_Ready.load()) {
// std::cout << "==Updating" << m_Id << " | tid: " <<
// std::this_thread::get_id() << "==\n";
m_Ready.store(true);
m_Tgt.hit();
m_Cv.notify_all();
}
// std::cout << "++Releasing lk " << m_Id << " | tid: " <<
// std::this_thread::get_id() << "++\n";
}
// the rest should wait here
std::mutex wait_mtx;
std::unique_lock<std::mutex> lk(wait_mtx);
m_Cv.wait(lk, [&]() -> bool { return m_Ready.load(); });
}
inline void reset() { m_Ready.store(false); }
private:
int m_Id;
Target &m_Tgt;
std::condition_variable m_Cv;
std::mutex m_Mtx;
std::atomic_bool m_Ready;
};
int main(int argc, char *argv[]) {
int n(2);
if (argc >= 2) {
n = atoi(argv[1]);
}
Target tgt;
Executive e(1, tgt);
auto updFn = [&e]() { e.update(); };
// update same executive from 3 threads. Repeat n times.
int i(n);
while (i > 0) {
e.reset();
{
std::thread t1(updFn), t2(updFn), t3(updFn);
t1.join();
t2.join();
t3.join();
}
--i;
}
std::cout << (n == tgt.nhits ? "[OK]" : "[ERR]") << " Updates: " << n << " | "
<< "Hits: " << tgt.nhits << "\n";
return 0;
}
</code></pre>
<p>I setup a simple method to verify that exactly one out of three threads executes the desired code. The method <code>hit()</code> is called in <code>Executive::Update</code>. Compile and test like so.</p>
<pre><code>jaswant@HAL9000:~$ g++ testExecutive.cpp -lpthread --std=c++17
jaswant@HAL9000:~$ ./a.out 2
[OK] Updates: 2 | Hits: 2
jaswant@HAL9000:~$ ./a.out 100
[OK] Updates: 100 | Hits: 100
jaswant@HAL9000:~$ ./a.out 2
[OK] Updates: 2 | Hits: 2
jaswant@HAL9000:~$ ./a.out 4
[OK] Updates: 4 | Hits: 4
jaswant@HAL9000:~$ ./a.out 8
[OK] Updates: 8 | Hits: 8
jaswant@HAL9000:~$ ./a.out 16
[OK] Updates: 16 | Hits: 16
jaswant@HAL9000:~$ ./a.out 256
[OK] Updates: 256 | Hits: 256
jaswant@HAL9000:~$ ./a.out 1024
[OK] Updates: 1024 | Hits: 1024
jaswant@HAL9000:~$ ./a.out 8192
[OK] Updates: 8192 | Hits: 8192
jaswant@HAL9000:~$ ./a.out 100000
[OK] Updates: 100000 | Hits: 100000
</code></pre>
<p>So, it works. Can anyone please point out bad usage of mutex/condition variables/locks and perhaps a way to do this w/o an atomic variable in the predicate?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T18:47:14.120",
"Id": "502037",
"Score": "3",
"body": "Your problem is exactly `std::once_flag`; see https://quuxplusone.github.io/blog/2020/10/23/once-flag/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T17:07:04.427",
"Id": "502121",
"Score": "0",
"body": "Just to be clear, can the first thread execute the \"meat\" before the others have reached it, or do all threads really have to wait to arrive there before the \"meat\" can be executed? And if the latter, does it really matter which thread executes it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T17:10:46.480",
"Id": "502123",
"Score": "0",
"body": "@G.Sliepen. It is the former. Also, it doesn't matter which thread executes it. All that matters is for an instance of the executive; unless reset, \"meat\" should execute only once. The requirement is similar to [`#pragma omp single`](https://www.openmp.org/spec-html/5.0/openmpsu38.html) w/o the `nowait` clause."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T17:12:26.680",
"Id": "502124",
"Score": "1",
"body": "Ok, then it might very well be that `std::once_flag` is indeed all you need."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T06:45:20.387",
"Id": "502180",
"Score": "1",
"body": "Welcome to Code Review. I have rolled back your latest edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T12:42:06.543",
"Id": "502206",
"Score": "0",
"body": "Simpler: `#pragma omp master` :-p"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T04:38:15.163",
"Id": "502388",
"Score": "0",
"body": "@TobySpeight, not really the `master` With your suggestion, `update()` would never execute since the master thread never touches `update()`. Hence I was looking for a `#pragma omp single` analogue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T07:47:53.797",
"Id": "502396",
"Score": "0",
"body": "Oops, I meant `single` but brainfarted! Thanks for correction."
}
] |
[
{
"body": "<h1>Use <code>std::once_flag</code></h1>\n<p>The <a href=\"https://en.cppreference.com/w/cpp/thread/once_flag\" rel=\"nofollow noreferrer\"><code>std::once_flag</code></a> class basically does what you want. However, there is no way nice way to reset it, except by using a trick like <a href=\"https://en.cppreference.com/w/cpp/language/new#Placement_new\" rel=\"nofollow noreferrer\">placement <code>new</code></a>, or by allocating a flag dynamically, and using a <code>std::unique_ptr</code> to point to it for example. As indi mentioned, it's not really "once" anymore then, but it does work for your specific case. Here is a drop-in replacement for your <code>struct Executive</code>:</p>\n<pre><code>struct Executive {\n Executive(int _Id, Target &_Tgt) : m_Id(_Id), m_Tgt(_Tgt) {}\n void update() {\n std::call_once(flag, [this]{ m_Tgt.hit(); });\n }\n void reset() {\n flag.~once_flag();\n new (&flag) std::once_flag;\n }\n\nprivate:\n int m_Id;\n Target &m_Tgt;\n std::once_flag flag;\n};\n</code></pre>\n<h1>No need to write <code>inline</code></h1>\n<p>If you include the full definition of a member function in a <code>class</code> or <code>struct</code> definition, you don't need to explicitly use the <a href=\"https://en.cppreference.com/w/cpp/language/inline\" rel=\"nofollow noreferrer\"><code>inline</code> specifier</a>, as it will implicitly be an inline function.</p>\n<h1>Write idiomatic code</h1>\n<p>There are a few things in your code that are not incorrect in any way, but are a rather unusual way to write things. For example, when declaring an <code>int</code> and initializing it, I would expect <code>int n = 2</code> or <code>int n{2}</code>, but not <code>int n(2)</code>.</p>\n<p>Also, when repeating something a number of times, use a <code>for</code>-loop, like so:</p>\n<pre><code>for (int i = 0; i < n; ++i) {\n e.reset();\n ...\n}\n</code></pre>\n<p>This completely describes how often the loop is run in a single line, which makes it easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T02:56:50.890",
"Id": "502166",
"Score": "1",
"body": "Eeeeh… . If you’re going to do this, you should at least call the destructor before re-constructing in place. Even then, this strikes me as at least immoral, if not outright wrong. It will (probably!) “work” for the program given, because each thread is started *after* the reset, and then quits without `reset()` ever being called again. But if you start threads *then* call `reset()`… . I see no promises that “reconstructing” a `once_flag` will be properly propagated across threads without *at least* some manual synchronization like fences (which kinda defeats the purpose)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T02:57:28.883",
"Id": "502167",
"Score": "1",
"body": "And by the way, this applies even if you try to do something like dynamically allocate the `once_flag`, then `delete` and re-`new` it in `update()`. It’s not the placement `new` that’s fishy here, it’s constructing (or re-constructing) the `once_flag` *after* the threads that will be waiting on it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T06:04:47.567",
"Id": "502177",
"Score": "0",
"body": "@indi, \"But if you start threads then call reset()\", this is guaranteed to never occur in my use case. `reset` is called only when all threads are done with `update`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T22:01:10.367",
"Id": "254624",
"ParentId": "254561",
"Score": "3"
}
},
{
"body": "<h1>Don’t overthink the plumbing</h1>\n<p>With no disrespect to Mr. O’Dwyer, I think he missed something key going on here. <code>std::call_once</code> <em>is</em> the best tool for the job… if you’re <em>really</em> only calling some code <em>once</em>.</p>\n<p>But your code includes a <code>reset()</code> function. That immediately invalidates the whole idea of <code>std::call_once</code> (and, by extension, <code>std::once_flag</code>). <code>call_once</code> means “call <em>once</em>”. Not “call once-<em>at-a-time</em>”… which is really what you’re looking for.</p>\n<p>With respect to the fairy tale metaphor, <code>call_once</code> is <code>call_once</code>… not <code>call_once_upon_a_time</code>. <em>If</em> your situation matches O’Dwyer’s metaphor, where a single knight gets to the princess, and then it’s all over, they get married, there’s a happily-ever-after… that’s <code>call_once</code>. But if your situation allows for the marriage to end in divorce after a while, and then the princess goes <em>back up on the glass hill</em> to give another group of knights a shot… that’s <em>not</em> <code>call_once</code>. That’s something else.</p>\n<p>So what <em>is</em> the right pattern here?</p>\n<p>Well, your situation is actually the classic double-checked problem. You don’t <em>need</em> <em>double</em>-checked locking; that’s just an optimization. You just need locking. Simple, basic locking. No tricks. Nothing complicated.</p>\n<p>I know all the cool kids are using condition variables these days, but you don’t need that here either. Alls you need is a mutex and a flag. Heck, you can even get away with the pre-C++20 <code>atomic_flag</code>:</p>\n<pre><code>struct Executive {\n Executive(int id, Target& tgt) :\n m_Id{id},\n m_Tgt{tgt}\n {\n // need this before C++20\n m_done.clear(); // or .clear(std::memory_order_release)\n }\n\n void update() {\n {\n auto lock = std::scoped_lock(m_Mtx);\n \n if (not m_Done.test_and_set()) // or .test_and_set(std::memory_order_acq_rel)\n {\n m_Tgt.hit();\n }\n }\n\n void reset()\n {\n m_Done.clear(); // or .clear(std::memory_order_release)\n }\n\nprivate:\n int m_Id;\n Target& m_Tgt;\n std::mutex m_Mtx;\n std::atomic_flag m_Done;\n};\n</code></pre>\n<p>Yup. That’s literally it. Just a lock and a flag.</p>\n<p>To understand how it works: If you have a bunch of threads that want to run the “meat” function, every one of them is going to stop cold at the lock… <em>except one</em>. That one thread will set the flag to <code>true</code>, and then run the target function. When it’s done, it will release the lock… and then every other thread will start running… they will all see the flag is already set, so they will skip running the target function. Thus, the target function only gets run once.</p>\n<p>Simple.</p>\n<p>Resetting is also simple. Just clear the flag.</p>\n<p>If you want to use the classic double-checked locking trick, that’s fine too… you just can’t use the pre-C++20 <code>atomic_flag</code> anymore; you’d have to use <code>atomic<bool></code>. (But from C++20 you <em>could</em> still use <code>atomic_flag</code>!)</p>\n<p>Okay… everything’s not <em>that</em> simple….</p>\n<h2>Tolerating failure.</h2>\n<p>One thing that <code>once_flag</code> does that’s really handy is take care of the case where the target function can fail. But that’s trivial to add:</p>\n<pre><code>void update() {\n{\n auto lock = std::scoped_lock(m_Mtx);\n \n if (not m_Done.test_and_set())\n {\n try\n {\n m_Tgt.hit();\n }\n catch (...)\n {\n m_Done.clear();\n\n // What to do now? Depends what you want.\n //\n // You could re-throw the exception, but you'd need to catch it\n // somehow or it'll just end up calling std::terminate().\n //\n // If you want to allow retries, you could simply wrap the whole\n // thing in a loop. (But be smart about it. You only want to redo\n // the loop if you ended up in this catch block - that is, if\n // you tried and failed. If you tried and succeeded, or if some\n // other thread succeeded and set m_Done, you don't want to loop.)\n }\n }\n}\n</code></pre>\n<p>Again, simple. Don’t overthink the plumbing!</p>\n<h2>The big picture; or, okay, maybe overthink the plumbing a little</h2>\n<p>Alright, so your <code>Executive</code> class basically manages a critical section so that it only gets executed once, and it allows resets. Now, if you’re <em>very</em> careful to ensure that you only call <code>reset()</code> <em>when no thread is executing <code>update()</code></em>, then you’ll have no problems.</p>\n<p>But if you’re not careful… well consider this situation:</p>\n<ol>\n<li>You create two threads, <code>t1</code> and <code>t2</code> to run <code>foo()</code> once.</li>\n<li><code>t1</code> acquires the lock, then goes to sleep.</li>\n<li><code>t2</code> tries to acquire the lock, but <code>t1</code> owns it, so it blocks, and goes to sleep.</li>\n<li><code>t1</code> wakes up, and then runs through to the end of <code>update()</code>—calling <code>foo()</code> once—then releases the lock.</li>\n<li>Your main thread sees <code>foo()</code> has been called, and so figures the job is done. It calls <code>reset()</code> (I don’t know why for, maybe in anticipation of needing <code>foo()</code> called again in the future?).</li>\n<li><code>t2</code> then wakes up, acquires the lock, and then sees the flag is clear… so it sets the flag and calls <code>foo()</code>.</li>\n</ol>\n<p>Thus, <code>foo()</code> ended up being called twice.</p>\n<p>This is not an impossible problem to solve… it just can’t be solved from within <code>update()</code>, or even <code>Executive</code>, because it requires knowing how many threads are trying to call <code>update()</code>. If you know how many threads are involved, there are <em>several</em> ways you can make sure that they all finish <code>update()</code> (so you know when it’s safe to call <code>reset()</code>). You can use an <code>atomic<int></code> as a counter, or a barrier… you have options.</p>\n<p>Or maybe you won’t actually need anything at all, because (as with your current <code>main()</code>) the problem never arises. I’m not actually suggesting you go ahead and implement something to guard against this—quite the opposite in fact—I’m just warning you to be aware.</p>\n<p>In fact, I would suggest giving careful thought as to whether you need <code>reset()</code> capability at all. As you can see from this section, it is <em>not</em> a trivial addition; it adds <em>significant</em> cognitive complexity. And you don’t <em>really</em> need it, at least not in the code you have written. You just need to rethink things. Instead of:</p>\n<pre><code>Target tgt;\nExecutive e(1, tgt);\nauto updFn = [&e]() { e.update(); };\n\nint i(n);\nwhile (i > 0) {\n e.reset();\n {\n std::thread t1(updFn), t2(updFn), t3(updFn);\n t1.join();\n t2.join();\n t3.join();\n }\n --i;\n}\n</code></pre>\n<p>just do:</p>\n<pre><code>Target tgt;\n\nint i(n);\nwhile (i > 0) {\n Executive e(1, tgt);\n auto updFn = [&e]() { e.update(); };\n\n {\n std::thread t1(updFn), t2(updFn), t3(updFn);\n t1.join();\n t2.join();\n t3.join();\n }\n\n --i;\n}\n</code></pre>\n<p>If you don’t <em>really</em> need <code>reset()</code>… I’d suggest dropping it. No sense inviting nasty race condition bugs unnecessarily.</p>\n<p>And <em>if</em> you drop <code>reset()</code>, <em>and</em> you really only need the target function called <em>once</em>—<em>ever</em>, in the entire program (not just once-at-a-time)—<em>and</em> you ensure that the executive is set up <em>before</em> the threads… then yeah, Quuxplusone and G. Sliepen are right, you might be able to get away with using <code>std::once_flag</code>.</p>\n<h1>Code review</h1>\n<pre><code>struct Target {\n int nhits = 0;\n inline void hit() { ++nhits; }\n};\n</code></pre>\n<p>G. Sliepen already mentioned that the <code>inline</code> is pointless here (and everywhere, pretty much; don’t use <code>inline</code> just because you <em>think</em> it will make you code faster (you’ll usually be wrong); don’t use <code>inline</code> unless you know you need to).</p>\n<p>But the real problem here is that you are using this class as shared, mutable data across multiple threads… and you have not a single whiff of synchronization anywhere. I presume you’re running you code on an x86, probably x86-64. Well, on that hardware you’re safe because <code>int</code>s will be naturally atomic (mooooooost of the time), and everything sequentially consistent (ish!). But if you switched to less beginner-friendly hardware, you may find some surprises.</p>\n<p><code>++nhits</code> is not a trivial operation. It has to <em>load</em> <code>nhits</code> into a register (we’ll presume, for simplicity), increment the value, then <em>store</em> the result back into <code>nhits</code>. If all this is atomic, no problems. <em>Buuuuut</em>… if thread 1 loads <code>nhits</code>, then stalls… then thread 2 loads <code>nhits</code>, then stalls… then thread 1 increments and stores the result… then thread 2 increments and stores the results… you might be expecting the final result of two threads incrementing <code>nhits</code> to be 2… but it will be 1!</p>\n<p>And <em>that</em> is just the tip of the iceberg. The other issue here is “tearing”. This occurs when the processor can’t load/store the entire value of <code>nhits</code> in a single step, so it has to do multiple loads/stores. For example, imagine you have a 16-bit processor and <code>nhits</code> is a 16-bit <code>int</code>… which happens to be misaligned in memory—it’s at address <code>0x1001</code> rather than <code>0x1000</code> or <code>0x1002</code>. So the processor has to do <em>two</em> loads to read <code>nhits</code>: first it loads the 16 bits starting at <code>0x1000</code>, and shifts that right by 8 bits… then it loads the 16 bits starting at <code>0x1002</code> and ANDs that with <code>0x00FF</code>… then it ORs the two results together to get the actual value of <code>nhits</code>. <em>THEN</em> it does the increment, and then goes through the whole dance in reverse to write the value back to memory address <code>0x1001</code>. At <em>ANY STEP IN ALL OF THAT</em>, the thread may be swapped out, and another thread starts running. If <code>nhits</code> gets loaded/stored halfway in one thread while another thread is loading/storing it, you could end up with a situation where <em>part</em> of <code>nhits</code> was written by one thread and another part of it was written by another. In other words, you could end up with gibberish.</p>\n<p>The bottom line is this: Target is shared, mutable data. Shared, mutable data <em>MUST</em> be synchronized somehow. You can’t just go commando.</p>\n<p>You don’t need to synchronize it <em>within</em> the class. You could use external synchronization. But you <em>must</em> use <em>some</em> synchronization. Because right now, you have a race condition; you have UB.</p>\n<pre><code>Executive() = delete;\n</code></pre>\n<p>You don’t need this; don’t write code that serves no purpose, it just becomes a maintenance burden.</p>\n<pre><code>Executive(int _Id, Target &_Tgt) : m_Id(_Id), m_Ready(false), m_Tgt(_Tgt) {}\n</code></pre>\n<p>Identifiers that begin with an underscore followed by an uppercase letter are illegal. Besides, you don’t need to tag function arguments. The point of tagging variables with things like an underscore, or <code>m_</code>, is because they’re “global-ish”; that is, they are used in scopes that they aren’t declared in. The tag signals to you “I know you can’t see where this variable is defined; don’t panic, it’s a data member of this class (if it has <code>m_</code>, for example)”. But with function arguments, you <em>can</em> see where they’re defined, and they don’t extend beyond the function scope. So tagging them is pointless.</p>\n<p>Just do:</p>\n<pre><code>Executive(int id, Target& tgt) : m_Id(id), m_Ready(false), m_Tgt(tgt) {}\n</code></pre>\n<p>Also, you have mixed up the order of variables; the order here in the initializer list is not the same as declared in the class. That’s unwise. You should have got a warning. You do have warnings turned on, don’t you?</p>\n<p>Now in <code>update()</code>:</p>\n<pre><code>std::scoped_lock<std::mutex> lk(m_Mtx);\n</code></pre>\n<p>Since you’re using C++17, prefer to use template argument deduction for things like this:</p>\n<pre><code>std::scoped_lock lk(m_Mtx);\n</code></pre>\n<p>That decreases the maintenance burden because you’re not repeating the type.</p>\n<pre><code>// the rest should wait here\nstd::mutex wait_mtx;\nstd::unique_lock<std::mutex> lk(wait_mtx);\nm_Cv.wait(lk, [&]() -> bool { return m_Ready.load(); });\n</code></pre>\n<p>This doesn’t do what I think you think it does. It creates a <em>local</em> mutex—so it will be a different mutex in each thread—so all three threads own their own <code>wait_mtx</code>. The reason this… <em>appears</em>… to work is because you then have all three mutexes wait on the same condition variable and condition. I’ll be honest, I’m not even sure it’s legal for a condition variable to work with three different mutexes. But at any rate, they’re all waiting on an atomic variable, so… I guess it shakes out somehow.</p>\n<p>And finally, in <code>main()</code>:</p>\n<pre><code>int i(n);\nwhile (i > 0) {\n e.reset();\n {\n std::thread t1(updFn), t2(updFn), t3(updFn);\n t1.join();\n t2.join();\n t3.join();\n }\n --i;\n}\n</code></pre>\n<p>This is… messy… for a lot of reasons. G. Sliepen already mentioned some. I’ll go further.</p>\n<p>If you’re going to make <code>x</code> number of threads, it makes more sense to put them all in a container:</p>\n<pre><code>for (auto i = 0; i < num_repeats; ++i)\n{\n auto threads = std::vector<std::thread>(3); // or std::array<std::thread, 3>{}\n std::generate(threads.begin(), threads.end(), [] { return std::thread{func}; });\n\n std::for_each(threads.begin(), threads.end(), [](auto&& t) { t.join(); });\n}\n</code></pre>\n<p>Even better, as of C++20 you should prefer to use <code>std::jthread</code>, which auto-joins:</p>\n<pre><code>for (auto i = 0; i < num_repeats; ++i)\n{\n auto threads = std::vector<std::jthread>(3);\n std::ranges::generate(threads, [] { return std::thread{func}; });\n\n // all threads run then auto-join\n}\n</code></pre>\n<p>This is not just a matter of style. Doing it this way allows you to trivially adjust the number of threads:</p>\n<pre><code>for (auto i = 0; i < num_repeats; ++i)\n{\n auto threads = std::vector<std::jthread>(num_threads);\n std::ranges::generate(threads, [] { return std::thread{func}; });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T05:53:32.797",
"Id": "502174",
"Score": "0",
"body": "\"And if you drop reset(), and you really only need the target function called once—ever, in the entire program (not just once-at-a-time)—and you ensure that the executive is set up before the threads… then yeah, Quuxplusone and G. Sliepen are right, you might be able to get away with using std::once_flag\". Partly right. `update` should run only once per frame. So I think I should use `call_once`. But thanks for your insights! `struct Target` was only placed as an example-usage and I did not look to get it reviewed. I'll make a new edit to OP with these suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T20:59:51.070",
"Id": "502370",
"Score": "0",
"body": "“Once-per-frame” ≠ “once”. And unless you’re creating threads every frame (!!!), or doing manual synchronization between `reset()` and `update()`, then I see no guarantee that `once_flag` will work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T04:33:16.030",
"Id": "502387",
"Score": "0",
"body": "I create threads well before the event loop even begins in the application(not recreated each frame!!). I understand the example I put in my question can be miscronstrued to think otherwise. At the end of every frame, an explicit synchronization occurs if any of the threads called `update()`. Then `once_flag` is clearly exactly what I need."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T20:12:28.967",
"Id": "502465",
"Score": "0",
"body": "Okay, whatever. You do you. (For other readers, no, what he’s doing isn’t guaranteed to work, because he’s updating the `once_flag` after each `update()`, but there’s no synchronization—like a fence—to propagate that update between threads. The next time the threads get around to checking the `once_flag`, they may still see the old value—which says “already done”, and the target function will just never get called. Moral of the story: `call_once` means call ***ONCE***. One time. Ever. In the whole program. *Not* “once per frame/second/whatever”.)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T05:09:26.567",
"Id": "254635",
"ParentId": "254561",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254624",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T15:37:36.570",
"Id": "254561",
"Score": "3",
"Tags": [
"c++",
"multithreading",
"c++17"
],
"Title": "Allow one thread to execute section while others wait and resume"
}
|
254561
|
<p>There are two main classes: <code>Game</code> and <code>MCTSPlayer</code>. The first one is just an abstract class with a couple of methods and some hints on how to implement actual games. The second implements the simplest form of MCTS algorithm (it does not use any expert knowledge), storing a graph of all known games as a <code>dict[Game, NodeInfo]</code>. That graph is sometimes trimmed to save some memory by deleting games that are unreachable from the current one. For that, a class that inherits from the Game can implement <code>__lt_</code>_, so that if <code>a</code> and <code>b</code> are instances of the same game <code>a<b</code> would mean that <code>a</code> is unreachable from <code>b</code>.</p>
<p>game.py:</p>
<pre><code>from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import Optional
class GameState(Enum):
WhitesMove = 1
BlacksMove = 2
WhiteWon = 3
BlackWon = 4
Draw = 5
class MoveType(Enum):
Put = 1
Jump = 2
Slide = 3
Take = 4
@dataclass
class Move:
type: MoveType
pos: Optional[tuple[int, int]]
pfrom: Optional[tuple[int, int]]
pto: Optional[tuple[int, int]]
@staticmethod
def Put(pos: tuple[int, int]):
return Move(MoveType.Put, pos, None, None)
@staticmethod
def Jump(pfrom, pto):
return Move(MoveType.Jump, None, pfrom, pto)
@staticmethod
def Slide(pfrom, pto):
return Move(MoveType.Slide, None, pfrom, pto)
@staticmethod
def Take(pos: tuple[int, int]):
return Move(MoveType.Take, pos, None, None)
class Game(ABC):
state: GameState
@abstractmethod
def with_move(self, m: Move) -> 'Game':
pass
@abstractmethod
def possible(self) -> list[Move]:
pass
@abstractmethod
def finished(self) -> bool:
pass
@abstractmethod
def __lt__(self, other):
pass
</code></pre>
<p>mctsplayer.py:</p>
<pre><code>from game import Game, GameState, Move
from typing import Optional, Union
from dataclasses import dataclass
from math import sqrt, log
from random import choice
from time import time
@dataclass
class NodeInfo:
whiteWon: int
blackWon: int
visitCount: int
class MCTSPlayer:
def __init__(self, game, c=0.7, warm_up=1):
self.game: Game = game
self.tree: dict[Game, NodeInfo] = dict()
self.tree[self.game] = NodeInfo(0, 0, 1)
self.cur = self.game
self.C = c
start = time()
while time() - start < warm_up:
self.build()
def move_to(self, game: Game):
if game not in self.tree.keys():
self.tree[game] = NodeInfo(0, 0, 1)
keys = list(self.tree.keys())
for key in keys:
if key < game:
del self.tree[key]
self.cur = game
def best_move(self, time_limit):
start = time()
ps = 0
while time() - start < time_limit:
self.build()
ps += 1
return self.best()
def build(self):
cur: Game = self.cur
path: list[Game] = []
self.expand(cur)
while cur in self.tree.keys():
path.append(cur)
cur = self.select(cur)
cur = path[-1]
self.expand(cur)
res = self.simulate(cur)
while path:
cur = path.pop()
self.backpropagate(cur, res)
def value(self, game: Game) -> int:
ret = self.tree[game].whiteWon - self.tree[game].blackWon
if self.cur.state == GameState.BlacksMove:
ret *= -1
return ret
def select(self, game: Game) -> Optional[Game]:
vs: list[Game] = list(self.tree.keys())
next_games: list[list[Union[Game, int]]] = \
[[game.with_move(m), 0] for m in game.possible() if game.with_move(m) in vs]
if not next_games:
return None
for i in range(len(next_games)):
next_games[i][1] = self.value(game)
next_games[i][1] += self.C * sqrt(log(self.tree[game].visitCount) /
self.tree[next_games[i][0]].visitCount)
next_games.sort(key=lambda p: p[1], reverse=True)
return next_games[0][0]
def expand(self, game):
next_games: list[Game] = [game.with_move(m) for m in game.possible()]
if not next_games:
return
for ng in next_games:
if ng not in self.tree.keys():
self.tree[ng] = NodeInfo(0, 0, 1)
@staticmethod
def simulate(game: Game) -> GameState:
while not game.finished():
next_moves = game.possible()
game = game.with_move(choice(next_moves))
return game.state
def backpropagate(self, game: Game, state: GameState):
self.tree[game].visitCount += 1
if state == GameState.BlackWon:
self.tree[game].blackWon += 1
if state == GameState.WhiteWon:
self.tree[game].whiteWon += 1
def best(self) -> Move:
vs = self.tree.keys()
moves2values: list[tuple[Move, int]] = \
[(m, self.value(self.cur.with_move(m))) for m in self.cur.possible() if
self.cur.with_move(m) in vs]
moves2values.sort(key=lambda p: p[1], reverse=True)
return moves2values[0][0]
</code></pre>
<p>To test it, I wrote an Othello (Reversi) game with pygame visualization (I did not put a lot of effort into it and post it rather for demonstration than for an actual review):</p>
<pre><code>from game import Game, GameState, Move, MoveType
from mctsplayer import MCTSPlayer
from copy import copy, deepcopy
from random import shuffle
from enum import Enum
import pygame
def draw_board(game, display, last, plr):
display.fill((0, 100, 0))
for i in range(9):
pygame.draw.line(display, (0, 0, 0), (i*50, 0), (i*50, 400), 1)
pygame.draw.line(display, (0, 0, 0), (0, i*50), (400, i*50), 1)
for x in range(8):
for y in range(8):
pos = (x, y)
m = Move.Put(pos)
if pos in game.board.keys():
fill = (0, 0, 0)
if game.board[pos] == OthelloPieces.White:
fill = (200, 200, 200)
pygame.draw.circle(display, fill, ((x+0.5)*50, (y+0.5)*50), 20)
if plr:
if m in game.possible():
pygame.draw.circle(display, (255, 125, 0), ((x + 0.5) * 50, (y + 0.5) * 50), 5)
if Move.Put((x, y)) == last:
pygame.draw.circle(display, (255, 0, 0), ((x + 0.5) * 50, (y + 0.5) * 50), 5)
def play_othello():
g = Othello()
p = MCTSPlayer(g)
pygame.init()
display = pygame.display.set_mode((400, 400))
finished = False
last_move = (-1, -1)
colors = [GameState.WhitesMove, GameState.BlacksMove]
shuffle(colors)
print(colors)
cmp, plr = colors
while not finished:
draw_board(g, display, last_move, g.state == plr)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
if g.state == cmp:
bm = p.best_move(2)
last_move = bm
g = g.with_move(bm)
p.move_to(g)
if event.type == pygame.MOUSEBUTTONDOWN:
if g.state == plr:
x, y = event.pos
x = int(x/50)
y = int(y/50)
if Move.Put((x, y)) in g.possible():
g = g.with_move(Move.Put((x, y)))
p.move_to(g)
pygame.quit()
class OthelloPieces(Enum):
White = 1
Black = 2
Empty = 3
def flip(self):
if self == OthelloPieces.White:
return OthelloPieces.Black
if self == OthelloPieces.Black:
return OthelloPieces.White
return OthelloPieces.Empty
class Othello(Game):
def __init__(self, base: 'Othello' = None):
self.board = dict()
self.state = GameState.BlacksMove
if base is not None:
self.board = base.board.copy()
self.state = copy(base.state)
self.possible_memo = deepcopy(base.possible_memo)
else:
self.board[(3, 3)] = OthelloPieces.White
self.board[(4, 4)] = OthelloPieces.White
self.board[(4, 3)] = OthelloPieces.Black
self.board[(3, 4)] = OthelloPieces.Black
self.possible_memo = None
self.possible_memo = self.possible()
self.memo_hash = None
def with_move(self, m: Move) -> 'Othello':
ret = Othello(self)
assert m.type == MoveType.Put
assert m in ret.possible(), 'Invalid move: ' + str(m) + ' in game \n' + str(ret)
x_0, y_0 = m.pos
piece = OthelloPieces.White if ret.state == GameState.WhitesMove else OthelloPieces.Black
opposite = piece.flip()
to_flip = []
ds = [(1, 0),
(-1, 0),
(0, 1),
(0, -1),
(1, 1),
(1, -1),
(-1, 1),
(-1, -1)]
for dx, dy in ds:
to_add = []
add = False
for i in range(1, 8):
x = x_0 + dx * i
y = y_0 + dy * i
if not 0 <= x < 8 or not 0 <= y < 8:
break
if (x, y) not in ret.board.keys():
break
if ret.board[(x, y)] == opposite:
to_add.append((x, y))
if ret.board[(x, y)] == piece:
add = True
break
if add:
to_flip.extend(to_add)
for p in to_flip:
ret.board[p] = piece
ret.board[(x_0, y_0)] = piece
ret.change_state()
ret.possible_memo = None
ret.possible_memo = ret.possible()
if not ret.possible():
ret.change_state()
ret.changed = True
if not ret.possible():
ret.change_state(True)
return ret
def change_state(self, force_end=False):
if {(x, y) for x in range(8) for y in range(8)} != self.board.keys() and not force_end:
if self.state == GameState.WhitesMove:
self.state = GameState.BlacksMove
elif self.state == GameState.BlacksMove:
self.state = GameState.WhitesMove
return
w = list(self.board.values()).count(OthelloPieces.White)
b = list(self.board.values()).count(OthelloPieces.Black)
if w > b:
self.state = GameState.WhiteWon
if w < b:
self.state = GameState.BlackWon
if w == b:
self.state = GameState.Draw
def possible(self) -> list[Move]:
if self.possible_memo:
return self.possible_memo
ret: list[Move] = []
ds = [(1, 0),
(-1, 0),
(0, 1),
(0, -1),
(1, 1),
(1, -1),
(-1, 1),
(-1, -1)]
piece = OthelloPieces.White if self.state == GameState.WhitesMove else OthelloPieces.Black
opposite = piece.flip()
for x_0 in range(8):
for y_0 in range(8):
good = False
if (x_0, y_0) in self.board.keys():
continue
for dx, dy in ds:
started = False
if good:
break
for i in range(1, 8):
x = x_0 + dx * i
y = y_0 + dy * i
if not 0 <= x < 8 or not 0 <= y < 8:
good = False
break
if (x, y) not in self.board.keys():
break
if self.board[(x, y)] == piece and started:
good = True
break
elif self.board[(x, y)] == opposite:
started = True
else:
break
if good:
ret.append(Move.Put((x_0, y_0)))
self.possible_memo = ret
return ret
def finished(self):
return self.state in [GameState.BlackWon, GameState.WhiteWon, GameState.Draw]
def __repr__(self):
ret = [['-' for _ in range(8)] for _ in range(8)]
for x in range(8):
for y in range(8):
key = (x, y)
symbol = '-'
if key in self.board.keys():
if self.board[key] == OthelloPieces.White:
symbol = 'O'
if self.board[key] == OthelloPieces.Black:
symbol = 'X'
if key in self.possible():
symbol = '.'
ret[key[1]][key[0]] = symbol
return ''.join([''.join(l) + '\n' for i, l in enumerate(ret)])
def __str__(self):
ret = repr(self)[:-1].split('\n')
ret = ''.join([str(i) + l + '\n' for i, l in enumerate(ret)])
ret = ' 01234567\n' + ret
return ret
def __eq__(self, other):
if type(other) == str:
return repr(self).replace('\n', '') == other.replace('\n', '').replace(' ', '')
if type(other) == Othello:
return self.board == other.board and self.state == other.state
def __hash__(self):
if self.memo_hash:
return self.memo_hash
self.memo_hash = hash((frozenset(self.board.items()), self.state))
return self.memo_hash
def __lt__(self, other):
assert type(other) == Othello
return len(self.board) < len(other.board)
</code></pre>
<p>What are some ways to make this code better? It seems reasonably readable, but I feel like it could be improved. I also feel that the actual "framework" part design can be improved.</p>
<p>Also, what are some ways to make <code>MCTSPlayer</code> stronger? Right now it plays well only when it has a lot of time to think and it is not too strong. I know that expert knowledge does improve playing strength, but I don<code>t want to use it to keep </code>MCTSPlayer<span class="math-container">`</span> game-independent.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T16:45:41.197",
"Id": "254562",
"Score": "2",
"Tags": [
"python",
"game",
"pygame",
"ai"
],
"Title": "A little board game framework with MCTS AI"
}
|
254562
|
<p>I need to update a nested array of settings. There are several difficulties that I managed to solve, but I'm pretty sure the code can be written much simpler. I just don't know how, which is why I'm asking for a simpler solution.</p>
<p>Problem:</p>
<ul>
<li>I have a nested array of settings in the database.</li>
<li>I have a form with fields that need to update the database.</li>
<li>The form contains checkboxes. When the form is sent, the empty checkbox fields don't get transmitted as keys in the form <code>$input</code> array. They are just missing.</li>
<li>I have settings in the database that don't get updated with the form and need to be preserved.</li>
</ul>
<p>It is not possible to just use array_merge(). It doesn't work recursively. And, it will not update a checkbox setting from true to false, because the form <code>$input</code> array doesn't contain the key.</p>
<p>Also we must preserve all settings that are not being updated with the form.</p>
<p>What I've done:</p>
<ol>
<li>Create an array with all keys that are not part of the form.</li>
<li>Merge that array recursively with the form <code>$input</code>. (This ensures that existing non-form keys get preserved with the next merge function. But, we are still missing the key for the empty checkboxes.)</li>
<li>Created a function that iterates recursively through the input array and the database array. If keys on boths sides exist, the form input key overwrites the database key. If the form input key is missing, the database key is set to false.</li>
</ol>
<p>Here is my working code. It contains a few helpers. It tests if the final processed array is equal to the desired output or not. So this should make it easier to jump in and test quickly.</p>
<pre><code>$input_from_db = [
'first' => [
'one' => '123123132', // form textfield textfield with text, change
'two' => '', // form, empty textfield, don't change
'three' => 0, // form, checkbox, false, change to true
'four' => 1, // form, checkbox, true, change to false
'five' => 1, // form, checkbox, true, keep
'six' => 0, // form, checkbox, false, keep
'seven' => 'testdata' // not in form, must be preserved
],
'second' => [ // test some deep nested arrays too
'one' => 0, // change to true
'two' => 1, // change to false with empty key
'three' => [
'a' => 'uno',
'b' => 'due'
]
],
'third' => '2', // not in form, must be preserved
'fourth' => '3' // not in form, must be preserved
];
$input_from_form = [
'first' => [
'one' => 'abababab',
'two' => '',
'three' => 1,
// four is missing from the form input because it was sent empty
'five' => 1,
// six is missing from the form input because it was sent empty
// seven is missing because it is no part of the form
],
'second' => [ //test some nested array too
'one' => 1,
// form field, must come back with zero
'three' => [
// a is not in form, preserve
'b' => 'due_new',
// c is an empty form checkbox
]
],
'third' => '2',
// four not in form, must be preserved
];
$must_be_result = [
'first' => [
'one' => 'abababab', // changed in the form to 'abababab'
'two' => '',
'three' => 1,
'four' => 0, // because it IS in the form, but was unchecked, it must be present again, with value zero
'five' => 1,
'six' => 0,
'seven' => 'testdata' // not in form, must be preserved
],
'second' => [
'one' => 1,
'two' => 0,
'three' => [
'a' => 'uno',
'b' => 'due_new',
'c' => 0,
]
],
'third' => '2',
'fourth' => '3'
];
// list of keys that the form will never return because they are not part of the form fields
function non_form_keys($array_existing): array
{
return [
'first' => [
'seven' => $array_existing['first']['seven'],
],
'second' => [
'three' => [
'a' => 'uno'
]
],
'third' => $array_existing['third'],
'fourth' => $array_existing['fourth'],
];
}
function update_options($array_existing, $array_input)
{
$output_array = [];
foreach ($array_existing as $key => $value)
{
if(array_key_exists($key, $array_input)){
if(is_array($value)){
$output_array[$key] = update_options($value, $array_input[$key]);
} else {
$output_array[$key] = $array_input[$key];
}
} else {
if(is_array($value)){
$output_array[$key] = set_to_zero($value);
} else {
$output_array[$key] = 0;
}
}
}
return $output_array;
}
function set_to_zero($array){
foreach ($array as $key => $value) {
if(is_array($value)) {
$array[$key] = set_to_zero($value);
} else {
$array[$key] = 0;
}
}
return $array;
}
// this is just a test that helps comparing my computed array with
// with an array that contains the result I want to see
function arrayRecursiveDiff($aArray1, $aArray2)
{
$aReturn = array();
foreach ($aArray1 as $mKey => $mValue) {
if (array_key_exists($mKey, $aArray2)) {
if (is_array($mValue)) {
$aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
if (count($aRecursiveDiff)) {
$aReturn[$mKey] = $aRecursiveDiff;
}
} else {
if ($mValue != $aArray2[$mKey]) {
$aReturn[$mKey] = $mValue;
}
}
} else {
$aReturn[$mKey] = $mValue;
}
}
return $aReturn;
}
// small helper to either print success or the
// diff array
function check_result($array_diff)
{
if(empty($array_diff)){
echo 'success' . PHP_EOL;
} else {
echo 'array diff' . PHP_EOL;
print_r($array_diff);
}
}
$input_from_form_updated = array_replace_recursive(non_form_keys($input_from_db), $input_from_form);
$result = update_options($input_from_db, $input_from_form_updated);
$array_diff = arrayRecursiveDiff($result, $must_be_result);
check_result($array_diff);
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p><code>set_to_zero()</code> is a "re-invention of the wheel". Just use the native <code>array_walk_recursive()</code> function to modify leafnodes.</p>\n<pre><code>array_walk_recursive(\n $array,\n function(&$leafnode) {\n $leafnode = 0;\n }\n);\n</code></pre>\n<p>Or from PHP7.4:</p>\n<pre><code>array_walk_recursive($array, fn(&$leafnode) => $leafnode = 0);\n</code></pre>\n</li>\n<li><p>To use the above in <code>update_options()</code>, I recommend using reference variables instead of declaring a new array to be returned.</p>\n</li>\n<li><p>You should employ consistent method naming styles. I prefer camel-case over snake_case.</p>\n</li>\n<li><p><code>empty($array_diff)</code> can be safely trduced to <code>!$array_diff</code> because the variable is assured to be declared.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T04:37:37.027",
"Id": "502172",
"Score": "0",
"body": "Is there a way to compare two nested arrays with `array_walk_recursive()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T08:10:40.657",
"Id": "502186",
"Score": "0",
"body": "No, because it does not keep track of where it is while iterating leafnodes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T03:28:28.790",
"Id": "254580",
"ParentId": "254563",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T17:27:50.667",
"Id": "254563",
"Score": "1",
"Tags": [
"php"
],
"Title": "Merge nested arrays coming from a database and a form"
}
|
254563
|
<p>I created a rest controller with Spring Boot, I am trying to learn what I should write on my tests, right now I only check status codes and keys existence. I am planning to build an API to showcase at interviews.</p>
<p><em>I would like you to tell me what do you think of my tests class and what I should add</em>. I will use your advises to write the rest of the API tests.</p>
<p>Rest Controller</p>
<pre><code> @RestController
@RequestMapping("/countries")
public class CountryController {
private final CountryRepository countryRepository;
private final CountryModelAssembler countryModelAssembler;
public CountryController(CountryRepository countryRepository, CountryModelAssembler countryModelAssembler) {
this.countryRepository = countryRepository;
this.countryModelAssembler = countryModelAssembler;
}
@GetMapping("/")
public CollectionModel<EntityModel<Country>> getCountries() {
List<EntityModel<Country>> countries = this.countryRepository.findAll()
.stream()
.map(this.countryModelAssembler::toModel)
.collect(Collectors.toList());
return CollectionModel.of(countries, linkTo(methodOn(CountryController.class).getCountries()).withSelfRel());
}
@GetMapping("/{id}")
public EntityModel<Country> getCountry(@PathVariable Long id) {
return this.countryRepository.findById(id).map(this.countryModelAssembler::toModel)
.orElseThrow(() -> new CountryNotFoundException(id));
}
@PostMapping("/")
public ResponseEntity<?> saveCountry(@RequestBody Country country) {
EntityModel<Country> entityModel = this.countryModelAssembler.toModel(this.countryRepository.save(country));
return ResponseEntity.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri())
.body(entityModel);
}
@PutMapping("/{id}")
public ResponseEntity<?> editCountry(@RequestBody Country country, @PathVariable Long id) {
Country updatedCountry = this.countryRepository.findById(id).map(mappedCountry -> {
mappedCountry.setName(country.getName());
return this.countryRepository.save(mappedCountry);
}).orElseGet(() -> {
country.setId(id);
return this.countryRepository.save(country);
});
EntityModel<Country> entityModel = this.countryModelAssembler.toModel(updatedCountry);
return ResponseEntity.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri())
.body(entityModel);
}
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteCountry(@PathVariable Long id) {
this.countryRepository.deleteById(id);
return ResponseEntity.noContent().build();
}
}
</code></pre>
<p>Tests</p>
<pre><code>@SpringBootTest
public class CountryControllerTest {
@BeforeEach
public void init() {
RestAssured.baseURI = "http://127.0.0.1:8085/countries";
}
@Test
public void getCountries() {
Response getResponse = RestAssured
.when()
.get("/")
.then()
.extract()
.response();
getResponse.prettyPrint();
getResponse
.then()
.assertThat()
.statusCode(HttpStatus.OK.value());
}
@Test
public void saveCountry() throws JSONException {
JSONObject country = new JSONObject();
country.put("name", "Honduras");
Response postResponse = RestAssured
.given()
.contentType(ContentType.JSON)
.body(country.toString())
.when()
.post("/")
.then()
.extract()
.response();
postResponse.prettyPrint();
postResponse
.then()
.assertThat()
.statusCode(HttpStatus.CREATED.value())
.body("$", Matchers.hasKey("id"))
.body("$", Matchers.hasKey("name"));
}
@Test
public void getCountry() throws JSONException {
JSONObject country = new JSONObject();
country.put("name", "Panama");
Response postResponse = RestAssured
.given()
.contentType(ContentType.JSON)
.body(country.toString())
.when()
.post("/")
.then()
.extract()
.response();
postResponse.prettyPrint();
System.out.println("****************");
postResponse
.then()
.assertThat()
.statusCode(HttpStatus.CREATED.value())
.body("$", Matchers.hasKey("id"))
.body("$", Matchers.hasKey("name"));
String jsonResponse = postResponse
.getBody()
.asString();
String selfPath = new JSONObject(jsonResponse)
.getJSONObject("_links")
.getJSONObject("self")
.get("href")
.toString();
Response getResponse = RestAssured
.when()
.get(selfPath)
.then()
.extract()
.response();
getResponse.prettyPrint();
getResponse
.then()
.statusCode(HttpStatus.OK.value())
.body("$", Matchers.hasKey("id"))
.body("$", Matchers.hasKey("name"));
}
@Test
public void editCountry() throws JSONException {
JSONObject country = new JSONObject();
country.put("name", "Costa Rica");
Response postResponse = RestAssured
.given()
.contentType(ContentType.JSON)
.body(country.toString())
.when()
.post("/")
.then()
.extract()
.response();
postResponse.prettyPrint();
System.out.println("****************");
postResponse
.then()
.assertThat()
.statusCode(HttpStatus.CREATED.value())
.body("$", Matchers.hasKey("id"))
.body("$", Matchers.hasKey("name"));
String jsonPostResponse = postResponse
.getBody()
.asString();
String selfReference = new JSONObject(jsonPostResponse)
.getJSONObject("_links")
.getJSONObject("self")
.get("href")
.toString();
String newName = "Guatemala";
country.put("name", newName);
Response putResponse = RestAssured
.given()
.contentType(ContentType.JSON)
.body(country.toString())
.when()
.put(selfReference)
.then()
.extract()
.response();
putResponse.prettyPrint();
putResponse
.then()
.assertThat()
.statusCode(HttpStatus.CREATED.value())
.body("$", Matchers.hasKey("id"))
.body("$", Matchers.hasKey("name"))
.body("name", Matchers.equalTo(newName));
}
@Test
public void deleteCountry() throws JSONException {
JSONObject country = new JSONObject();
country.put("name", "Costa Rica");
Response postResponse = RestAssured
.given()
.contentType(ContentType.JSON)
.body(country.toString())
.when()
.post("/")
.then()
.extract()
.response();
postResponse
.then()
.assertThat()
.statusCode(HttpStatus.CREATED.value())
.body("$", Matchers.hasKey("id"))
.body("$", Matchers.hasKey("name"));
postResponse.prettyPrint();
String jsonPostResponse = postResponse
.getBody()
.asString();
String selfReference = new JSONObject(jsonPostResponse)
.getJSONObject("_links")
.getJSONObject("self")
.get("href")
.toString();
Response deleteResponse = RestAssured
.when()
.delete(selfReference)
.then()
.extract()
.response();
deleteResponse
.then()
.assertThat()
.statusCode(HttpStatus.NO_CONTENT.value());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T13:30:04.877",
"Id": "502100",
"Score": "0",
"body": "Hi Daniel, when you call `RestAssured.when().get(\"/\").then().extract().response();` in your tests, your Country controller is being called?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T17:33:03.053",
"Id": "502127",
"Score": "0",
"body": "@AndresGardiol Yes it is being called, why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T17:56:26.450",
"Id": "502132",
"Score": "0",
"body": "Just to know, It's the first time I see the `RestAssured` class. To answer your question. I would recommend you to test as many cases as possible on each of your controller endpoints. You should test not only the \"happy path\", but also the cases where an error is expected. A great methodology for this is TDD (Test driven develpment)"
}
] |
[
{
"body": "<p>What happens if you get a country or id which isn't recognised? Does your code throw the correct errors in such circumstances?</p>\n<p>My (current, I still feel fairly new to writing good tests) approach is to look at all the inputs for a given method and ask myself: what could possibly get passed in, and how should the program handle it?</p>\n<p>E.g. I want to delete countries with IDs 0, 5, -3, 7.392, -0.33333. You might feel as though your project has been written so that invalid or nonsense values can't actually be sent to the method in the first place. Maybe you are right. However, maybe someone will find a way to hack it, or a future programmer will change something which then does accidentally allow the unwanted values to get through. Assume <i>any</i> value of <code>long</code> could get through. Write a different test for each and every variation you can think of. Confirm that the correct action is taken, whether it's returning something, invoking another method, changing a class parameter, or throwing an error.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T04:35:57.623",
"Id": "254683",
"ParentId": "254575",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T22:57:06.263",
"Id": "254575",
"Score": "1",
"Tags": [
"java",
"unit-testing",
"spring"
],
"Title": "What to test on a rest API?"
}
|
254575
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251983/231235">A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>, <a href="https://codereview.stackexchange.com/q/252404/231235">A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/254384/231235">A Function Applier for Applying Various Algorithms on Nested Container Things in C++</a>. I am trying to use unwrap level template parameter as the termination condition of the recursion process in <code>recursive_count</code> template function.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>recursive_count</code> function is as below.</p>
<pre><code>// recursive_count implementation (the version with unwrap_level)
template<std::size_t unwrap_level, class T, typename ValueType>
constexpr auto recursive_count(const T& input, const ValueType& target)
{
if constexpr (unwrap_level > 0)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [&target](auto&& element) {
return recursive_count<unwrap_level - 1>(element, target);
});
}
else
{
if (input == target)
{
return 1;
}
else
{
return 0;
}
}
}
</code></pre>
<p><strong>Test cases</strong></p>
<p>The <code>std::vector<int></code>, <code>std::vector<std::vector<int>></code>, <code>std::vector<std::string></code>, <code>std::vector<std::vector<std::string>></code>, <code>std::deque<int></code>, <code>std::deque<std::deque<int>></code>, <code>std::list<int></code> and <code>std::list<std::list<int>></code> type input test case has been listed as below.</p>
<pre><code>std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
std::cout << recursive_count<1>(test_vector, 5) << std::endl;
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
std::cout << recursive_count<2>(test_vector2, 5) << std::endl;
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
std::cout << recursive_count<1>(test_string_vector, "0") << std::endl;
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
std::cout << recursive_count<2>(test_string_vector2, "0") << std::endl;
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
std::cout << recursive_count<1>(test_deque, 1) << std::endl;
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
std::cout << recursive_count<2>(test_deque2, 1) << std::endl;
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
std::cout << recursive_count<1>(test_list, 1) << std::endl;
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
std::cout << recursive_count<2>(test_list2, 1) << std::endl;
std::cout << recursive_count<11>(
n_dim_container_generator<10, std::list>(test_list, 3),
1
) << std::endl;
</code></pre>
<p></p>
<b>Full Testing Code</b>
<p>
<p>The full testing code:</p>
<pre><code>#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <exception>
#include <execution>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
template<typename T>
concept is_inserterable = requires(T x)
{
std::inserter(x, std::ranges::end(x));
};
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<typename T>
concept is_multi_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::multi_array(x);
};
#endif
// recursive_copy_if function
template <std::ranges::input_range Range, std::invocable<std::ranges::range_value_t<Range>> UnaryPredicate>
constexpr auto recursive_copy_if(const Range& input, const UnaryPredicate& unary_predicate)
{
Range output{};
std::ranges::copy_if(std::ranges::cbegin(input), std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
unary_predicate);
return output;
}
template <
std::ranges::input_range Range,
class UnaryPredicate>
constexpr auto recursive_copy_if(const Range& input, const UnaryPredicate& unary_predicate)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&unary_predicate](auto&& element) { return recursive_copy_if(element, unary_predicate); }
);
return output;
}
// recursive_count implementation
template<std::ranges::input_range Range, typename T>
constexpr auto recursive_count(const Range& input, const T& target)
{
return std::count(std::ranges::cbegin(input), std::ranges::cend(input), target);
}
// transform_reduce version
template<std::ranges::input_range Range, typename T>
requires std::ranges::input_range<std::ranges::range_value_t<Range>>
constexpr auto recursive_count(const Range& input, const T& target)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [target](auto&& element) {
return recursive_count(element, target);
});
}
// recursive_count implementation (the version with unwrap_level)
template<std::size_t unwrap_level, class T, typename ValueType>
constexpr auto recursive_count(const T& input, const ValueType& target)
{
if constexpr (unwrap_level > 0)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [&target](auto&& element) {
return recursive_count<unwrap_level - 1>(element, target);
});
}
else
{
if (input == target)
{
return 1;
}
else
{
return 0;
}
}
}
// recursive_count implementation (with execution policy)
template<class ExPo, std::ranges::input_range Range, typename T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_count(ExPo execution_policy, const Range& input, const T& target)
{
return std::count(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), target);
}
template<class ExPo, std::ranges::input_range Range, typename T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_count(ExPo execution_policy, const Range& input, const T& target)
{
return std::transform_reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [execution_policy, target](auto&& element) {
return recursive_count(execution_policy, element, target);
});
}
// recursive_count_if implementation
template<class T, std::invocable<T> Pred>
constexpr std::size_t recursive_count_if(const T& input, const Pred& predicate)
{
return predicate(input) ? 1 : 0;
}
template<std::ranges::input_range Range, class Pred>
requires (!std::invocable<Pred, Range>)
constexpr auto recursive_count_if(const Range& input, const Pred& predicate)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if(element, predicate);
});
}
// recursive_count_if implementation (with execution policy)
template<class ExPo, class T, std::invocable<T> Pred>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr std::size_t recursive_count_if(ExPo execution_policy, const T& input, const Pred& predicate)
{
return predicate(input) ? 1 : 0;
}
template<class ExPo, std::ranges::input_range Range, class Pred>
requires ((std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (!std::invocable<Pred, Range>))
constexpr auto recursive_count_if(ExPo execution_policy, const Range& input, const Pred& predicate)
{
return std::transform_reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if(element, predicate);
});
}
// recursive_count_if implementation (the version with unwrap_level)
template<std::size_t unwrap_level, std::ranges::range T, class Pred>
auto recursive_count_if(const T& input, const Pred& predicate)
{
if constexpr (unwrap_level > 1)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if<unwrap_level - 1>(element, predicate);
});
}
else
{
return std::count_if(std::ranges::cbegin(input), std::ranges::cend(input), predicate);
}
}
// recursive_function_applier implementation
template<std::size_t unwrap_level, class F, std::ranges::range Range, class... Args>
constexpr auto recursive_function_applier(const F& function, const Range& input, Args... args)
{
if constexpr (unwrap_level >= 1)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&function, &args...](auto&& element) { return recursive_function_applier<unwrap_level - 1>(function, element, args...); }
);
return output;
}
else
{
Range output{};
function(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
args...);
return output;
}
}
// recursive_print implementation
template<std::ranges::input_range Range>
constexpr auto recursive_print(const Range& input, const int level = 0)
{
auto output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
return x;
}
);
return output;
}
template<std::ranges::input_range Range> requires (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_print(const Range& input, const int level = 0)
{
auto output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
}
// recursive_replace_copy_if implementation
template<std::ranges::range Range, std::invocable<std::ranges::range_value_t<Range>> UnaryPredicate, class T>
constexpr auto recursive_replace_copy_if(const Range& input, const UnaryPredicate& unary_predicate, const T& new_value)
{
Range output{};
std::ranges::replace_copy_if(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
unary_predicate,
new_value);
return output;
}
template<std::ranges::input_range Range, class UnaryPredicate, class T>
requires (!std::invocable<UnaryPredicate, std::ranges::range_value_t<Range>>)
constexpr auto recursive_replace_copy_if(const Range& input, const UnaryPredicate& unary_predicate, const T& new_value)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&unary_predicate, &new_value](auto&& element) { return recursive_replace_copy_if(element, unary_predicate, new_value); }
);
return output;
}
// recursive_size implementation
template<class T> requires (!std::ranges::range<T>)
constexpr auto recursive_size(const T& input)
{
return 1;
}
template<std::ranges::range Range> requires (!(std::ranges::input_range<std::ranges::range_value_t<Range>>))
constexpr auto recursive_size(const Range& input)
{
return std::ranges::size(input);
}
template<std::ranges::range Range> requires (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_size(const Range& input)
{
return std::transform_reduce(std::ranges::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [](auto& element) {
return recursive_size(element);
});
}
// recursive_transform implementation
// recursive_invoke_result_t implementation
// from https://stackoverflow.com/a/65504127/6667035
template<typename, typename>
struct recursive_invoke_result { };
template<typename T, std::invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };
template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::invocable<F, Container<Ts...>> &&
std::ranges::input_range<Container<Ts...>> &&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};
template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type;
template <std::ranges::range Range>
constexpr auto get_output_iterator(Range& output)
{
return std::inserter(output, std::ranges::end(output));
}
template <class T, std::invocable<T> F>
constexpr auto recursive_transform(const T& input, const F& f)
{
return f(input);
}
template <
std::ranges::input_range Range,
class F>
requires (!std::invocable<F, Range>)
constexpr auto recursive_transform(const Range& input, const F& f)
{
recursive_invoke_result_t<F, Range> output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform(element, f); }
);
return output;
}
template<std::size_t dim, class T>
constexpr auto n_dim_vector_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_vector_generator<dim - 1>(input, times);
std::vector<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_array_generator<dim - 1, times>(input);
std::array<decltype(element), times> output;
std::fill(std::begin(output), std::end(output), element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_deque_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_deque_generator<dim - 1>(input, times);
std::deque<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_list_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_list_generator<dim - 1>(input, times);
std::list<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, template<class...> class Container = std::vector, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<dim - 1, Container, T>(input, times));
}
}
int main()
{
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
std::cout << recursive_count<1>(test_vector, 5) << std::endl;
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
std::cout << recursive_count<2>(test_vector2, 5) << std::endl;
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
std::cout << recursive_count<1>(test_string_vector, "0") << std::endl;
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
std::cout << recursive_count<2>(test_string_vector2, "0") << std::endl;
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
std::cout << recursive_count<1>(test_deque, 1) << std::endl;
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
std::cout << recursive_count<2>(test_deque2, 1) << std::endl;
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
std::cout << recursive_count<1>(test_list, 1) << std::endl;
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
std::cout << recursive_count<2>(test_list2, 1) << std::endl;
std::cout << recursive_count<11>(
n_dim_container_generator<10, std::list>(test_list, 3),
1
) << std::endl;
return 0;
}
</code></pre>
</p>
<p><a href="https://godbolt.org/z/6ofMj1" rel="nofollow noreferrer">A Godbolt link is here.</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/251983/231235">A recursive_count Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/252404/231235">A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/254384/231235">A Function Applier for Applying Various Algorithms on Nested Container Things in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The implementation of <code>recursive_count</code> function with unwrap level is the main idea here.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>In the base comparison part, not sure using <code>input == target</code> as the equivalence condition is OK because <code>ValueType</code> and <code>T</code> may be different. The definition of <code>==</code> operator between <code>ValueType</code> and <code>T</code> is required in this design. If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Comparing using <code>==</code> is fine</h1>\n<blockquote>\n<p>In the base comparison part, not sure using <code>input == target</code> as the equivalence condition is OK because <code>ValueType</code> and <code>T</code> may be different.</p>\n</blockquote>\n<p>This is fine, it does exactly what <a href=\"https://en.cppreference.com/w/cpp/algorithm/count\" rel=\"nofollow noreferrer\"><code>std::count()</code></a> does, and I wouldn't know how else to compare two values for equivalence, apart from passing a predicate function, but then it would become a <code>recursive_count_if()</code>.</p>\n<h1>Use <code>std::ranges::count</code></h1>\n<p>For the non-recursive version of <code>recursive_count()</code>, you can just call <code>std::ranges::count()</code>:</p>\n<pre><code>template<std::ranges::input_range Range, typename T>\nconstexpr auto recursive_count(const Range& input, const T& target)\n{\n return std::ranges::count(input, target);\n}\n</code></pre>\n<p>Unfortunately, there is no <code>std::ranges::transform_reduce()</code> in C++20, but it might come in C++23.</p>\n<h1>Make use of <code>auto</code> parameter types</h1>\n<p>While this doesn't change anything, it might make the code clearer if you use <code>auto</code> for parameters that you don't want the caller to explicitly pass template types for, and <code>template<></code> for those that it should. So for example:</p>\n<pre><code>template<std::size_t unwrap_level>\nconstexpr auto recursive_count(const auto& input, const auto& target)\n{\n ...\n}\n</code></pre>\n<h1>Avoid code duplication</h1>\n<p>You have two versions of <code>recursive_count()</code>, one which takes an <code>unwrap_level</code> parameter, and another which doesn't. You can avoid implementing the latter version by calling the first one with the maximum recursion depth of the <code>input</code> argument:</p>\n<pre><code>template<std::ranges::input_range Range, typename T>\nconstexpr auto recursive_count(const Range& input, const T& target)\n{\n return recursive_count<recursive_depth<Range>()>(input, target);\n}\n</code></pre>\n<p>Implementing <code>recursive_depth()</code> is left as an excercise.</p>\n<h1>Consider checking if <code>unwrap_level</code> is too high</h1>\n<p>If you call <code>recursive_count()</code> with an <code>unwrap_level</code> higher than the recursion depth of <code>input</code>, you'll get a very long and unreadable compiler error message. Consider adding a constraint or <code>static_assert()</code> to make it easier to debug this. For example:</p>\n<pre><code>template<std::size_t unwrap_level, class T, typename ValueType>\nconstexpr auto recursive_count(const T& input, const ValueType& target)\n{\n if constexpr (unwrap_level > 0)\n {\n static_assert(unwrap_level <= recursive_depth<T>(),\n "unwrap level higher than recursion depth of input");\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-23T19:53:33.510",
"Id": "269309",
"ParentId": "254576",
"Score": "3"
}
},
{
"body": "<p>In addition to G. Sliepen's answer:</p>\n<h2>Return Type</h2>\n<ul>\n<li><code>std::count</code> returns a <code>difference_type</code> (i.e. <code>std::ptrdiff_t</code>).</li>\n<li><code>std::transform_reduce</code> returns a <code>std::size_t</code> (because that's what we specify as the "init" argument).</li>\n<li>The other two return statements <code>return 1;</code> and <code>return 0;</code> are <code>int</code>egers.</li>\n</ul>\n<p>So with the <code>auto</code> return type, the user will get a type depending on what version of the function they call, and how exactly they call it.</p>\n<p>I'd probably just go with specifying <code>std::size_t</code> for the return type, but an argument could be made for using <code>difference_type</code> from the relevant iterator traits instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-23T20:52:22.420",
"Id": "269312",
"ParentId": "254576",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "269309",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T00:54:31.907",
"Id": "254576",
"Score": "3",
"Tags": [
"c++",
"recursion",
"template",
"c++20"
],
"Title": "A recursive_count Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++"
}
|
254576
|
<p>(This is the Non-const version, I have to implement the const one too).
Could someone please review this implementation? This is made for std::vector
I'm unsure whether I respected all requirements for LegacyRandomAccessIterator; so if I'm missing something, please do let me know.</p>
<pre><code>namespace random_access
{
template<typename Type>
class iterator
{
private:
Type* m_iterator;
public:
using value_type = Type;
using reference = value_type&;
using pointer = value_type*;
using iterator_category = std::random_access_iterator_tag;
using difference_type = std::ptrdiff_t;
//using iterator_concept = std::contiguous_iterator_tag;
constexpr iterator(Type* iter = nullptr) : m_iterator{ iter } {}
constexpr bool operator==(const iterator& other) const noexcept { return m_iterator == other.m_iterator; }
constexpr bool operator!=(const iterator& other) const noexcept { return m_iterator != other.m_iterator; }
constexpr reference operator*() const noexcept { return *m_iterator; }
constexpr pointer operator->() const noexcept { return m_iterator; }
constexpr iterator& operator++() noexcept { ++m_iterator; return *this; }
constexpr iterator operator++(int) noexcept { iterator tmp(*this); ++(*this); return tmp; }
constexpr iterator& operator--() noexcept { --m_iterator; return *this; }
constexpr iterator operator--(int) noexcept { iterator tmp(*this); --(*this); return tmp; }
constexpr iterator& operator+=(const difference_type other) noexcept { m_iterator += other; return *this; }
constexpr iterator& operator-=(const difference_type other) noexcept { m_iterator -= other; return *this; }
constexpr iterator operator+(const difference_type other) const noexcept { return iterator(m_iterator + other); }
constexpr iterator operator-(const difference_type other) const noexcept { return iterator(m_iterator - other); }
constexpr iterator operator+(const iterator& other) const noexcept { return iterator(*this + other.m_iterator); }
constexpr difference_type operator-(const iterator& other) const noexcept { return std::distance(m_iterator, other.m_iterator); }
constexpr reference operator[](std::size_t index) const { return m_iterator[index]; }
constexpr bool operator<(const iterator& other) const noexcept { return m_iterator < other.m_iterator; }
constexpr bool operator>(const iterator& other) const noexcept { return m_iterator > other.m_iterator; }
constexpr bool operator<=(const iterator& other) const noexcept { return m_iterator <= other.m_iterator; }
constexpr bool operator>=(const iterator& other) const noexcept { return m_iterator >= other.m_iterator; }
};
}
</code></pre>
<p>Thanks !</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T11:38:25.397",
"Id": "502090",
"Score": "0",
"body": "Can I ask what is the purpose of this class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T18:01:40.597",
"Id": "502133",
"Score": "0",
"body": "A pointer already implements the \"Random Access Iterator\" concept. You don't need to wrap it in a class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T18:04:42.357",
"Id": "502135",
"Score": "0",
"body": "What does it mean to add two iterators together? `iterator operator+(const iterator& other)` That does not seem to have any meaning."
}
] |
[
{
"body": "<p>As pointed out by @Martin York in the comments that your class is just a wrapper for a pointer, I don't have much to say. I only have one suggestion</p>\n<ul>\n<li><strong>Better Formatting</strong></li>\n</ul>\n<p>Good formatting IMO plays a major role in how readable your code is. In this case, I find it impossible to navigate through the functions because they all look extremely cramped.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>constexpr pointer operator->() const noexcept { return m_iterator; }\nconstexpr iterator& operator++() noexcept { ++m_iterator; return *this; }\n</code></pre>\n<p>Compare that to</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>constexpr pointer operator->() const noexcept { \n return m_iterator;\n}\n\nconstexpr iterator& operator++() noexcept { \n ++m_iterator; \n return *this; \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T11:58:11.943",
"Id": "254596",
"ParentId": "254577",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "254596",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T02:12:08.520",
"Id": "254577",
"Score": "0",
"Tags": [
"c++",
"iterator"
],
"Title": "Random Access Iterator Implementation"
}
|
254577
|
<p>This is from a leetcode question I am working on. The problem is the following:</p>
<p>create an algorithm that works in the the following fashion:</p>
<p>arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]]</p>
<p>the output is:
[2,7,14,8]</p>
<p>by applying the following series of operations:
The XOR values for queries are:</p>
<p>[0,1] = 1 xor 3 = 2</p>
<p>[1,2] = 3 xor 4 = 7</p>
<p>[0,3] = 1 xor 3 xor 4 xor 8 = 14</p>
<p>[3,3] = 8</p>
<p>The input is a very large list for arr and an even longer list for queries. The output has to be a list and I have tried this several ways.</p>
<p>first attempt: (building a gigantic list in memory and returning it using append() )</p>
<pre class="lang-py prettyprint-override"><code>def XORsubqueries(array, queries):
result = []
for pair in queries:
value = array[pair[0]]
i = pair[0]
while i < pair[1]:
if pair[0] == pair[1]:
result.append(array[pair[i]] ^ array[pair[i]])
break
else:
i += 1
value ^= array[i]
result.append(value)
return result
</code></pre>
<p>As you can imagine this takes FOREVER (53 seconds on my i5 dual core). I then remembered about generator expressions for lazily building values and thought they might come in handy just for this kind of thing.</p>
<pre class="lang-py prettyprint-override"><code>def XORsubqueries(array, queries):
result = [0] * len(array)
def XOR(array, queries):
for pair in queries:
value = array[pair[0]]
i = pair[0]
while i < pair[1]:
i += 1
value ^= array[i]
yield value
return list(XOR(array, queries))
</code></pre>
<p>If i remove the list off that return statement it figures it out in like 0.0001 seconds ! But I have to return it as a list. Is there a way I can rewrite my algorithm to do what I am trying to do with this generator or did I paint myself into a corner ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T06:51:50.177",
"Id": "502061",
"Score": "1",
"body": "Welcome to Code Review. Please format the code and add the link to the programming challenge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T12:34:08.743",
"Id": "502097",
"Score": "0",
"body": "Other than exceeding the time limit are there any other problems in the execution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T17:40:53.740",
"Id": "502128",
"Score": "0",
"body": "The time was the biggest issue. It was a little tricky getting the loop to work right - python range() is a little funky for including the last element which is why i used a while loop as well"
}
] |
[
{
"body": "<p>I would guess the biggest slowdowns are the <code>append</code> and <code>list</code> functions. In your second example, you attempt to pre-create a list, which is a good idea, but a) you use the wrong size, and b) you never use the created list. Here's an example using a pre-made list:</p>\n<pre><code>def xor_subqueries(array, queries):\n result = [0] * len(queries)\n for i,q in enumerate(queries):\n val = array[q[0]]\n for j in range(q[0]+1, q[1]+1):\n val ^= array[j]\n result[i] = val\n return result\n</code></pre>\n<p>Pretty straight forward. I'm not so sure this task calls for a generator function, but here's an example of using one:</p>\n<pre><code>def xor_subqueries(array, queries):\n def genx():\n for q in queries:\n val = array[q[0]]\n for j in range(q[0]+1, q[1]+1):\n val ^= array[j]\n yield val\n\n result = [0] * len(queries)\n for i,q in enumerate(genx()):\n result[i] = q\n return result\n\n</code></pre>\n<p>However, I have read that list comprehension is faster. You could easily re-write the above function using list comprehension (<code>return [x for x in genx()]</code>), but here is an example using the built-in functions <code>reduce</code> and <code>xor</code> which stand-in for your generator function.</p>\n<pre><code>from functools import reduce\nfrom operator import xor\n\ndef xor_subqueries(array, queries):\n return [reduce(xor, array[q[0]:q[1]+1], 0) for q in queries]\n</code></pre>\n<p>It calls <code>reduce</code> on the sub-list <code>array[q[0]:q[1]+1])</code>. <code>reduce</code> calls <code>xor</code> on each element of the sub-list with the previously calculated value and an initial value of <code>0</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T17:42:53.210",
"Id": "502129",
"Score": "0",
"body": "I really appreciate your comments. I will try each of them and see how they compare in runtime ! :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T18:04:30.347",
"Id": "502134",
"Score": "0",
"body": "Good. I am interested in knowing how they perform."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T16:20:30.453",
"Id": "254610",
"ParentId": "254581",
"Score": "0"
}
},
{
"body": "<p>results of benchmarking various solutions from slowest to fastest using timeit():</p>\n<p>building a list and appending to it: (52-55 seconds)</p>\n<pre><code>def XORsubqueries(array, queries):\nresult = []\nfor pair in queries:\n value = array[pair[0]]\n i = pair[0]\n while i < pair[1]:\n if pair[0] == pair[1]:\n result.append(array[pair[i]] ^ array[pair[i]])\n break\n else:\n i += 1\n value ^= array[i]\n result.append(value)\nreturn result \n</code></pre>\n<p>homespun generator : (49 - 53 seconds) slightly faster using list() incidentally</p>\n<pre><code>def XORsubqueries(array, queries):\n\n#result = [0] * len(array)\ndef XOR(array, queries): \n for pair in queries:\n value = array[pair[0]]\n i = pair[0]\n while i < pair[1]:\n i += 1\n value ^= array[i]\n yield value\n\nreturn [x for x in XOR(array, queries)] # 53 seconds\nreturn list(XOR(array, queries)) # 49 seconds\n</code></pre>\n<p>using reduce (thanks @Johnny Mopp ) 13 seconds</p>\n<pre><code>from functools import reduce\nfrom operator import xor\n\ndef xor_subqueries(array, queries):\n return [reduce(xor, array[q[0]:q[1]+1], 0) for q in queries]\n</code></pre>\n<p>using accumulate (thanks @StefanPochmann from leetcode) holy crap 0.009 seconds !</p>\n<pre><code>def xorQueries(self, arr, queries):\n x = [0, *itertools.accumulate(arr, operator.xor)]\n return [x[i] ^ x[j+1] for i, j in queries]\n</code></pre>\n<p>I am curious to know why this last one is SO MUCH faster than the reduce. I am guessing it has to do with using accumulate as an iterator to build the output lazily and then a list comprehension for the output as opposed to building a list comprehension (?)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T15:55:14.210",
"Id": "502220",
"Score": "0",
"body": "Mine is faster because it handles each query with a single operation. All those little technicalities you and Johnny talk about are rather irrelevant. This problem really asks for prefix-xors."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T19:07:15.377",
"Id": "254615",
"ParentId": "254581",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "254610",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T05:09:09.187",
"Id": "254581",
"Score": "0",
"Tags": [
"python-3.x",
"generator"
],
"Title": "Python3: using generator to process a very large list of integers"
}
|
254581
|
<p>I have a function to filter a 2-d array.</p>
<p>It works. But I am not sure if the following mechanism is a sensible concept.</p>
<p>The idea is:</p>
<ol>
<li><p>loop over the input array which is received as <code>input_arr(y,x)</code></p>
</li>
<li><p>store the values in <code>temp_arr(x,y)</code>, since in order to resize the y-dimension it
needs to be last dimension, so I have to transpose the values as I
store them</p>
</li>
<li><p>once the loop is done, transpose <code>temp_arr(x,y)</code> which
becomes the return value</p>
<pre><code>Public Function filter_arr(input_arr As Variant, col_index As Long, filter_value As Variant) As Variant
'the input_arr might be indexed starting from 0 or 1
Dim n1 As Long, n2 As Long
n1 = LBound(input_arr, 2)
n2 = UBound(input_arr, 2)
Dim temp_arr() As Variant
Dim y As Long, x As Long, count As Long
count = 0
If (LBound(input_arr, 1) = 0) Then
For y = LBound(input_arr, 1) To UBound(input_arr, 1)
If (input_arr(y, col_index) = filter_value) Then
ReDim Preserve temp_arr(n1 To n2, 0 To count)
For x = n1 To n2
temp_arr(x, count) = input_arr(y, x)
Next x
count = count + 1
End If
Next y
Else
'if LBound(input_arr, 1) = 1
For y = LBound(input_arr, 1) To UBound(input_arr, 1)
If (input_arr(y, col_index) = filter_value) Then
count = count + 1
ReDim Preserve temp_arr(n1 To n2, 1 To count)
For x = n1 To n2
temp_arr(x, count) = input_arr(y, x)
Next x
End If
Next y
End If
filter_arr = Application.Transpose(temp_arr)
End Function
</code></pre>
</li>
</ol>
<p>Edit: adding some context</p>
<p>Imagine that I have a <code>ws</code> in an <code>.xlam</code> file that contains product information which I've added as an add-in.</p>
<p>I have a function like <code>=getProductData()</code> which returns an array containing that data</p>
<p>So excel has a <code>SORT</code> function which works great with this kind of thing. I can do <code>=SORT(getProductData(), 2, 1)</code> to return my product data sorted by the 2nd column</p>
<p>But excel's <code>FILTER</code> function needs me to specify the data itself as its second parameter, not just its index, like in <code>SORT</code></p>
<p>I can use <code>INDEX</code> to do something like <code>=SORT(FILTER(getProductData(),INDEX(getProductData(),,3)="red",""),2,1)</code> to filter my product data by the 3rd column if the <code>value = red</code>, then sort by the 2nd column of the resulting array</p>
<p>But I was hoping to do something like
<code>=SORT(filter_arr(getProductData(),3,"red"),2,1)</code> to do the same</p>
<p>Naturally I'm still just playing around to determine what I can pull off - maybe using <code>INDEX</code> is the way to go and I'm trying to reinvent the wheel</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T11:25:43.277",
"Id": "502088",
"Score": "0",
"body": "I would think about creating a class which provides the flexibility you want . I would suggest that internal to the class you convert the array to a collection of collections using either Collection, ArrayList or Scripting.Dictionary as your collection object (whichever is the best fit). Write methods or properties to expand/contract access individual items as required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T11:28:20.320",
"Id": "502089",
"Score": "0",
"body": "Just for some context, what is the purpose of this code; is it called from the worksheet as a UDF or from other vba code? What sort of data are you passing in, and is this just 1 step of a bigger process? Are you having performance issues? Update your question to include any of that sort of stuff if you can:)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T16:00:50.687",
"Id": "502110",
"Score": "1",
"body": "I added some details of what my plans were for this function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T16:33:45.617",
"Id": "502229",
"Score": "0",
"body": "Too short for a review, but VBA is slow and it's not too hard to make this work with spreadsheet formulae, but use LET or LAMBDA to avoid repeating the calculation: `=LET(array,getProductData(),FILTER(array,INDEX(array,,3)=\"red\"))`. Or better (but requires beta channel): `FILTERIF = LAMBDA(array,filter_index,include_if,FILTER(array,INDEX(array,,filter_index) = include_if))` called like `=FILTERIF(getProductData(),3,\"red\")`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T01:14:14.990",
"Id": "502290",
"Score": "0",
"body": "@Greedo Although I haven't used them, I believe that my answer would outperform `Let` and `Lambda`. In any case, not every version of Excel supports them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T17:55:04.060",
"Id": "502359",
"Score": "0",
"body": "@TinMan well, only one way to verify that claim, although worksheet functions are not easy to profile (perhaps using evaluate). True, not everywhere but op doesn't state constraints and I think LET is becoming increasingly widely available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T18:19:00.750",
"Id": "502360",
"Score": "0",
"body": "@Greedo I would think that `Range(\"A1\").Formula = Lambda` would automatically synchronously spill. So applying it to a large data set would be timeable. We would then have to time the assignment of values returned by my function. I wish I had the time to do it."
}
] |
[
{
"body": "<p>Based on my comment (and near terminal Covid-19 boredom) here is a starter for 10 for a class called 'FlexArray'. The code compiles cleanly and doesn't generate any untoward Rubberduck code inspections but is otherwise untested.</p>\n<p>Usage is</p>\n<pre><code>Dim myArray as FlexArray\nset myArray = FlexArray.Make(inputarray)\n</code></pre>\n<p>Note the Rubberduck annotations for PredeclaredId and Exposed. If you are unable to use the free and fantastic Rubberduck addin you will need to export the class to a text editor to set the relevant attributes.</p>\n<pre><code>'@PredeclaredId\n'@Exposed\nOption Explicit\n' See https://excelmacromastery.com/vba-arraylist/\n\nPrivate Type State\n\n Data As ArrayList\n \nEnd Type\n\nPrivate s As State\n\nPublic Function Make(ByVal ipTable As Variant) As FlexArray\n\n With New FlexArray\n \n Set Make = .Self(ipTable)\n \n End With\n \nEnd Function\n\n\nPublic Function Self(ByVal ipTable As Variant) As FlexArray\n\n Set s.Data = New ArrayList\n \n Dim myRow As Long\n For myRow = LBound(ipTable, 1) To UBound(ipTable, 1)\n\n s.Data.Add New ArrayList\n\n Dim myCol As Long\n For myCol = LBound(ipTable, 2) To UBound(ipTable, 2)\n \n s.Data.Item(myRow).Add myCol, ipTable(myRow, myCol)\n \n Next\n \n Next\n \n Set Self = Me\n \nEnd Function\n \n \nPublic Property Get Item(ByVal ipRow As Long, ByVal ipCol As Long) As Variant\n\n Item = s.Data.Item(ipRow).Item(ipCol)\n \nEnd Property\n\nPublic Property Let Item(ByVal ipRow As Long, ByVal ipCol As Long, ByVal ipValue As Variant)\n\n s.Data.Item(ipRow).Item(ipCol) = ipValue\n\nEnd Property\n\nPublic Function GetArrayRC() As Variant\n\n Dim myTable As Variant\n ReDim myTable(0 To s.Data.Count - 1, 0 To s.Data.Item(0).Count - 1)\n \n Dim myRow As Long\n For myRow = LBound(myTable, 1) To UBound(myTable, 1)\n \n Dim myCol As Long\n For myCol = LBound(myTable, 2) To UBound(myTable, 2)\n \n myTable(myRow, myCol) = s.Data.Item(myRow).Item(myCol)\n \n Next\n \n Next\n \n GetArrayRC = myTable\n \nEnd Function\n\n\nPublic Function GetArrayCR() As Variant\n \n Dim myTable As Variant\n ReDim myTable(0 To s.Data.Item(0).Count - 1, 0 To s.Data.Count - 1)\n\n Dim myRow As Long\n For myRow = LBound(myTable, 2) To UBound(myTable, 2)\n\n Dim myCol As Long\n For myCol = LBound(myTable, 1) To UBound(myTable, 1)\n \n myTable(myCol, myRow) = s.Data.Item(myCol).Item(myRow)\n \n Next\n \n Next\n \n GetArrayCR = myTable\n \nEnd Function\n\nPublic Sub InsertRow(ByVal ipRow As Long)\n\n s.Data.Insert ipRow, New ArrayList\n \nEnd Sub\n\n\nPublic Sub RemoveRow(ByVal ipRow As Long)\n\n s.Data.RemoveAt ipRow\n \nEnd Sub\n\n\nPublic Sub InsertCol(ByVal ipCol As Long, Optional ByVal ipColArray As Variant)\n\n Dim myRow As Long\n For myRow = 0 To s.Data.Count - 1\n \n If myRow < UBound(ipColArray) Then\n \n s.Data.Item(myRow).Insert ipCol, ipColArray(myRow)\n \n Else\n \n s.Data.Item(myRow).Insert ipCol, Empty\n \n End If\n \n Next\n \nEnd Sub\n\nPublic Sub RemoveCol(ByVal ipCol As Long, Optional ByVal ipColArray As Variant)\n\n Dim myRow As Long\n For myRow = 0 To s.Data.Count - 1\n \n s.Data.Item(myRow).RemoveAt ipCol\n \n Next\n \nEnd Sub\n\nPublic Property Get Row(ByVal ipRow As Long) As Variant\n Row = s.Data.Item(ipRow).Clone\nEnd Property\n\nPublic Property Let Row(ByVal ipRow As Long, ByVal ipRowArray As Variant)\n ' The .AddRange method cannot be used because ArrayList is a new object\n ' and expects an array that implements ICOllection\n ' VBA arrays do not implement ICOllection so the incoming array\n ' has to be added item by item\n \n Dim myRowLen As Long\n myRowLen = UBound(ipRowArray) - LBound(ipRowArray)\n \n Dim myCol As Long\n For myCol = 0 To s.Data.Item(ipRow).Count - 1\n \n If myCol <= myRowLen Then\n \n s.Data.Item(ipRow).Item(myCol) = ipRowArray(myCol)\n \n Else\n \n s.Data.Item(ipRow).Item(myCol) = Empty\n \n End If\n \n Next\n \nEnd Property\n\nPublic Property Get Col(ByVal ipCol As Long) As Variant\n Dim myCol As ArrayList\n Set myCol = New ArrayList\n \n Dim myRow As Long\n For myRow = 0 To s.Data.Count - 1\n \n myCol.Add s.Data.Item(myRow).Item(ipCol)\n \n Next\n \n Col = myCol.Clone\n \nEnd Property\n\nPublic Property Let Col(ByVal ipCol As Long, ByVal ipColArray As Variant)\n ' The .AddRange method cannot be used because ArrayList is a .Net object\n ' and expects an array that implements ICOllection\n ' VBA arrays do not implement ICOllection so the incoming array\n ' has to be added item by item\n \n Dim myColLen As Long\n myColLen = UBound(ipColArray) - LBound(ipColArray)\n \n Dim myRow As Long\n For myRow = 0 To s.Data.Count - 1\n \n If myRow <= myColLen Then\n \n s.Data.Item(myRow).Item(ipCol) = ipColArray(myRow)\n \n Else\n \n s.Data.Item(myRow).Item(ipCol) = Empty\n \n End If\n \n Next\n \nEnd Property\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-25T16:21:33.323",
"Id": "508964",
"Score": "0",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T12:55:09.007",
"Id": "254599",
"ParentId": "254585",
"Score": "0"
}
},
{
"body": "<p><code>ReDim Preserve</code> and <code>Transpose</code> are not free. I use this pattern when I need to filter an array:</p>\n<ol>\n<li>Declare a 1-D array (Indices) with the same number of rows as the 2D array</li>\n<li>When a match is found add the matches index to the Indices array and increment the counter</li>\n<li>If there is matching data, declare a 2-D array (Results) with the same dimensions of the Input array but a row count equal to the counter</li>\n<li>Iterate over the indices in the Indices array and add the matching values to the Results</li>\n<li>Return the Results</li>\n<li>If there are no matches return an empty array</li>\n</ol>\n<h2>Quick Filter</h2>\n<pre><code>Public Function QuickFilter(input_arr As Variant, col_index As Long, filter_value As Variant) As Variant\n Dim r As Long\n Dim Count As Long\n Dim Indices As Variant\n ReDim Indices(LBound(input_arr, 1) To UBound(input_arr, 1))\n Count = LBound(input_arr, 1) - 1\n For r = LBound(input_arr, 1) To UBound(input_arr, 1)\n If input_arr(r, col_index) = filter_value Then\n Count = Count + 1\n Indices(Count) = r\n End If\n Next\n \n Dim Results As Variant\n Dim c As Long\n Dim index As Long\n If Count >= LBound(input_arr, 1) Then\n ``` we want results to hold the entire row\n ReDim Results(LBound(input_arr, 1) To Count, LBound(input_arr, 2) To UBound(input_arr, 2))\n For r = LBound(input_arr, 1) To Count\n index = Indices(r)\n For c = LBound(input_arr, 2) To UBound(input_arr, 2)\n Results(r, c) = input_arr(index, c)\n Next\n Next\n QuickFilter = Results\n Else\n QuickFilter = Array()\n End If\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-13T23:14:13.390",
"Id": "505290",
"Score": "1",
"body": "I really examined this and it makes sense to me. 1. make `indices` w enough space in case every row hits 2. loop over `input_array`, storing the indices of `input_array` that hit, and recording `count` of hits. 3. make `results` w enough space to store `count` elements, 4. loop up to `count` populating `results` w rows from `input_array` corresponding to the values in `incides`. I'm still playing around with this but it feels like a good solution (or simple enough for me to understand)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-14T22:44:16.120",
"Id": "505347",
"Score": "1",
"body": "I did a comparison using a dataset with 8000+ rows between a more elegant version of my function `filter_arr` and `QuickFilter` which showed `QuickFilter` was about 100 times faster. I guess the main point I have to accept is that looping over the data only once can look clean but `redim` is just such a speed bump that the code executes faster by replacing it with a combination of simpler operations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-15T00:34:16.837",
"Id": "505353",
"Score": "0",
"body": "@dactyrafficle The main thing to consider is `redim preserve` isn't free. It is much faster to reserve enough room in memory once (create a buffer) and then trim off the fat in the end. The same is true with strings."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T01:04:02.937",
"Id": "254676",
"ParentId": "254585",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254676",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T05:50:28.240",
"Id": "254585",
"Score": "5",
"Tags": [
"vba",
"excel"
],
"Title": "excel-vba function to filter an array and return an array"
}
|
254585
|
<p>I am trying to generate sequences containing only <code>0</code>'s and <code>1</code>'s. I have written the following code, and it works.</p>
<pre><code>import numpy as np
batch = 1000
dim = 32
while 1:
is_same = False
seq = np.random.randint(0, 2, [batch, dim])
for i in range(batch):
for j in range(i + 1, batch):
if np.array_equal(seq[i], seq[j]):
is_same = True
if is_same:
continue
else:
break
</code></pre>
<p>My <code>batch</code> variable is in the thousands. This loop above takes about 30 seconds to complete. This is a data generation part of another <code>for</code> loop that runs for about 500 iterations and is therefore extremely slow. Is there a faster way to generate this list of sequences without repetition? Thanks.</p>
<p>The desired result is a collection of <code>batch_size</code> number of sequences each of length <code>dim</code> containing only <code>0</code>s and <code>1</code>s such that no two sequences in the collection are the same.</p>
|
[] |
[
{
"body": "<p>Generating all sequences and then checking if they are unique can be quite expensive, as you noticed. Consider this alternative approach:</p>\n<ol>\n<li>Generate one sequence</li>\n<li>Convert it to a tuple and add it to a set</li>\n<li>If the set is of size <code>batch_size</code> return it, else go to step 1</li>\n</ol>\n<p>This approach can be implemented like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def unique_01_sequences(dim, batch_size):\n sequences = set()\n while len(sequences) != batch_size:\n sequences.add(tuple(np.random.randint(0, 2, dim)))\n return sequences\n</code></pre>\n<p>Running the two solutions for <code>dim=32</code> and <code>batch_size=1000</code>:</p>\n<pre><code>Original: 2.296s\nImproved: 0.017s\n</code></pre>\n<p>Note: the result of the function I suggested is a set of tuples, but it can be converted to the format you prefer.</p>\n<p>A few other suggestions and considerations:</p>\n<ul>\n<li><strong>Functions</strong>: consider to encapsulate the code in a function, it is easier to reuse and test.</li>\n<li><strong>Exit condition</strong>: this part:\n<pre><code>if is_same:\n continue\nelse:\n break\n</code></pre>\nCan be simplified to:\n<pre><code>if not is_same:\n break\n</code></pre>\n</li>\n<li><strong>binary vs integer sequence</strong>: probably you know it, but the result is a "sequence" of integers, not a binary sequence as the title says.</li>\n<li><strong>Collisions</strong>: the suggested approach can become very slow for some configurations of <code>dim</code> and <code>batch_size</code>. For example, if the input is <code>dim=10</code> and <code>batch_size=1024</code> the result contains all configurations of 10 "bits", which are the binary representations of the numbers from 0 to 1023. During the generation, as the size of the set <code>sequences</code> grows close to 1024, the number of collisions increases, slowing down the function. In these cases, generating all configurations (as numbers) and shuffling them would be more efficient.</li>\n<li><strong>Edge case</strong>: for <code>dim=10</code> and <code>batch_size=1025</code> the function never ends. Consider to validate the input.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T11:12:23.527",
"Id": "502087",
"Score": "1",
"body": "Set! I totally forgot about set. Thanks! +1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T14:09:01.663",
"Id": "502103",
"Score": "1",
"body": "@learner I am glad I could help. FYI I added a couple of considerations regarding collisions and edge cases."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T08:19:05.660",
"Id": "254590",
"ParentId": "254587",
"Score": "3"
}
},
{
"body": "<p>As noted in the <a href=\"https://codereview.stackexchange.com/a/254590/98493\">other answer</a> by <a href=\"https://codereview.stackexchange.com/users/227157/marc\">@Marc</a>, generating a random sample and then throwing all of it away if there are any duplicates is very wasteful and slow. Instead, you can either use the built-in <code>set</code>, or use <code>np.unique</code>. I would also use the slightly faster algorithm of generating multiple tuples at once and then deduplicating, checking how many are missing and then generating enough tuples to have enough assuming there are now duplicates and then repeating it.</p>\n<pre><code>def random_bytes_numpy(dim, n):\n nums = np.unique(np.random.randint(0, 2, [n, dim]), axis=1)\n while len(nums) < n:\n nums = np.unique(\n np.stack([nums, np.random.randint(0, 2, [n - len(nums), dim])]),\n axis=1\n )\n return nums\n</code></pre>\n<p>Here is an alternative way using a <code>set</code> but the same algorithm, generating always exactly as many samples as are needed assuming no duplicates:</p>\n<pre><code>def random_bytes_set(dim, n):\n nums = set()\n while len(nums) < n:\n nums.update(map(tuple, np.random.randint(0, 2, [n - len(nums), dim])))\n return nums\n</code></pre>\n<p>And here is a comparison of the time they take for increasing <code>batch_size</code>at fixed <code>dim=32</code>, including the function by @Marc and yours:</p>\n<p><a href=\"https://i.stack.imgur.com/O2KpT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/O2KpT.png\" alt=\"enter image description here\" /></a></p>\n<p>And for larger values of <code>batch_size</code>, without your algorithm, since it takes too long:</p>\n<p><a href=\"https://i.stack.imgur.com/WNPTU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WNPTU.png\" alt=\"enter image description here\" /></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T16:41:13.610",
"Id": "502117",
"Score": "0",
"body": "Thank you so much. I guess my method was the worst way to achieve what I wanted to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T11:57:17.213",
"Id": "502203",
"Score": "1",
"body": "@learner Well, I'm sure there are worse ways to solve this problem ;)\nBut look at the bright side, your code at least solved the problem, and you now learned how to solve it in other (faster) ways. And to use functions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T14:19:04.323",
"Id": "254603",
"ParentId": "254587",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254590",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T06:51:34.933",
"Id": "254587",
"Score": "3",
"Tags": [
"python",
"performance",
"array",
"random"
],
"Title": "Generating binary sequences without repetition"
}
|
254587
|
<p>In general, I'd love some comments on this basic queue using dynamic allocation.
In particular, I want comments about whether this queue is good in embedded systems, for example say a a sensor network gateway, which has to queue up packets to be forwarded on say a UART.</p>
<p>I hear normally that mallocs are a bad idea for embedded, so what are the pitfalls in such a scenario?</p>
<p>One thing is, that malloc could return that it was unable to allocate the required memory. But what I thought was that if I did the calculation and I was reasonably certain that I definitely have MAX_QSIZE amount of memory available for the MAX_DATSIZE then realistically I shouldn't be able to see malloc fail. Is that a correct assumption?</p>
<p>I am rewriting the same code for a version with static array and no mallocs as well, so I'll try to analyze how both behave.</p>
<p>Thank you for your time.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#define MAX_QSIZE 100
#define MAX_DATSIZE 128
struct node{
void *data;
struct node *next;
};
typedef struct node node_t;
typedef struct queue_t {
node_t *head;
node_t *tail;
int size;
} queue_t;
queue_t *q_init(void)
{
queue_t *q = malloc(sizeof (*q));
q->size = 0;
q->head = q->tail = NULL;
}
int q_push(queue_t *q, const void *pdata, int bsize)
{
if (q == NULL)
return -1;
if (q->size == MAX_QSIZE)
return -2;
if (bsize > MAX_DATSIZE)
return -3;
node_t *new = malloc(sizeof (*new));
new->next = NULL;
new->data = malloc(bsize);
bzero(new->data, bsize);
memcpy(new->data, pdata, bsize);
if (q->size == 0) {
q->head = new;
} else {
q->tail->next = new;
}
q->tail = new;
q->size++;
return 0;
}
node_t *q_peek(queue_t *q)
{
return q->head;
}
void q_pop(queue_t *q)
{
if (q->size == 0)
return;
node_t *this = q->head;
q->head = this->next;
free(this);
q->size--;
if (q->size == 0)
q->tail = NULL;
}
void freeq(queue_t *q)
{
while (q->head != NULL) {
node_t *t = q->head;
q->head = t->next;
free(t);
}
free(q);
}
void printq(queue_t *q)
{
int i = 0;
for (node_t *h = q->head; h != NULL; h = h->next) {
printf("[%d] %s\n", i++, (char*)h->data);
}
}
int main()
{
char *test[] =
{
"January",
"February",
"Random"
};
int numtest = sizeof test / sizeof test[0];
queue_t *nameq = q_init();
for (int i = 0; i < numtest; i++) {
q_push(nameq, test[i], strlen(test[i]));
}
printq(nameq);
q_pop(nameq);
printq(nameq);
char *hname = (char*)(q_peek(nameq)->data);
printf("head name = %s\n", hname);
freeq(nameq);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>BUG</strong>: <code>q_init()</code> doesn't return a value. Your compiler should have caught this; perhaps you're running without enough diagnostics turned on? (I think this <em>requires</em> a diagnostic, so perhaps you need a better compiler).</p>\n<hr />\n<p><strong>BUG</strong>: We forgot to copy the terminating null character!</p>\n<blockquote>\n<pre><code>for (int i = 0; i < numtest; i++) {\n q_push(nameq, test[i], strlen(test[i]));\n}\n</code></pre>\n</blockquote>\n<p>That should be <code>strlen(test[i])+1</code>. This was quickly revealed by Valgrind.</p>\n<hr />\n<p>Although you don't ever expect <code>malloc()</code> to fail, I think it's better to be in the habit of coding defensively. "Memory available" might be fragmented, and not available in big enough chunks, for instance. It's not hard to add the necessary tests, and it makes your code more re-usable, saving you much time in the longer term.</p>\n<pre><code>queue_t *q_init(void)\n{\n queue_t *q = malloc(sizeof *q);\n if (q) {\n q->size = 0;\n q->head = q->tail = NULL;\n }\n return q;\n}\n</code></pre>\n<hr />\n<p><code>bzero()</code> isn't standard (i.e. portable) C. Use <code>memset()</code> instead. Actually, just remove that call entirely, as it's immediately followed by a <code>memcpy()</code> that completely overwrites it, making the <code>bzero()</code> a <em>dead store</em>.</p>\n<hr />\n<p>We don't need to cast here:</p>\n<blockquote>\n<pre><code> printf("[%d] %s\\n", i++, (char*)h->data);\n</code></pre>\n</blockquote>\n\n<blockquote>\n<pre><code>char *hname = (char*)(q_peek(nameq)->data);\n</code></pre>\n</blockquote>\n<p><code>data</code> is a pointer to void, which can be assigned to any pointer type in C:</p>\n<pre><code> printf("[%d] %s\\n", i++, h->data);\n</code></pre>\n\n<pre><code>const char *hname = q_peek(nameq)->data;\n</code></pre>\n<hr />\n<p>We've included <code><stdint.h></code> but then seemingly ignored it. I would normally use <code>size_t</code> for the queue length and element sizes. I certainly wouldn't use a signed type such as <code>int</code>.</p>\n<hr />\n<p>Naming: why <code>freeq()</code> and not <code>q_free()</code> to match the other functions?</p>\n<hr />\n<p>When pushing a value, we allocate twice, but <code>q_pop()</code> and <code>freeq()</code> don't release the value storage, only the queue node. So we have a memory leak:</p>\n<pre><code>==4943== \n==4943== 21 bytes in 3 blocks are definitely lost in loss record 1 of 1\n==4943== at 0x480B77F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==4943== by 0x10922B: q_push (254594.c:40)\n==4943== by 0x10942E: main (254594.c:100)\n</code></pre>\n<p>We can fix this by adding another <code>free()</code> before the one that releases the node object. But a more elegant fix is to allocate just once, for the node <em>and</em> stored value together:</p>\n<pre><code>node_t *new = malloc(sizeof *new + bsize);\nif (!new) {\n return ENOMEM;\n}\nnew->next = NULL;\nnew->data = (char*)(new + 1);\nmemcpy(new->data, pdata, bsize);\n</code></pre>\n<p>We don't really need the <code>data</code> member any more - the value is always at the same offset from the node pointer.</p>\n<hr />\n<p>The interface can be improved - users shouldn't need to know about <code>node_t</code>. Instead, just return pointer to the data member.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include <stdio.h>\n#include <stdint.h>\n#include <string.h>\n#include <stdlib.h>\n\n#define MAX_QSIZE 100\n#define MAX_DATSIZE 128\n\ntypedef struct node {\n struct node *next;\n char data[]; /* flexible array member */\n} node_t;\n\ntypedef struct queue_t {\n node_t *head;\n node_t *tail;\n size_t size; /* element count */\n} queue_t;\n\nqueue_t *q_init(void)\n{\n queue_t *q = malloc(sizeof *q);\n if (q) {\n q->size = 0;\n q->head = q->tail = NULL;\n }\n return q;\n}\n\nvoid *q_push(queue_t *q, const void *pdata, size_t bsize)\n{\n if (!q || q->size == MAX_QSIZE || bsize > MAX_DATSIZE) {\n return NULL;\n }\n\n node_t *new = malloc(sizeof *new + bsize);\n if (!new) {\n return NULL;\n }\n new->next = NULL;\n memcpy(&new->data, pdata, bsize);\n\n if (q->head) {\n q->tail->next = new;\n } else {\n q->head = new;\n }\n q->tail = new;\n q->size++;\n\n return &new->data;\n}\n\nconst void *q_peek(queue_t *q)\n{\n if (!q || !q->head) { return NULL; }\n return &q->head->data;\n}\n\nvoid q_pop(queue_t *q)\n{\n if (!q || !q->size) { return; }\n node_t *this = q->head;\n q->head = this->next;\n free(this);\n if (!--q->size) {\n q->tail = NULL;\n }\n}\n\nvoid q_free(queue_t *q)\n{\n if (!q) { return; }\n node_t *h = q->head;\n while (h) {\n node_t *t = h;\n h = t->next;\n free(t);\n }\n free(q);\n}\n\n\nstatic void printq(queue_t *q)\n{\n int i = 0;\n for (const node_t *h = q->head; h; h = h->next) {\n printf("[%d] %s\\n", i++, &h->data[0]);\n }\n}\n\nint main(void)\n{\n const char *test[] =\n {\n "January",\n "February",\n "Random"\n };\n int numtest = sizeof test / sizeof test[0];\n queue_t *nameq = q_init();\n if (!nameq) {\n fprintf(stderr, "Failed to create queue\\n");\n return EXIT_FAILURE;\n }\n for (int i = 0; i < numtest; i++) {\n if (!q_push(nameq, test[i], strlen(test[i]) + 1)) {\n fprintf(stderr, "Failed to create element %i\\n", i);\n return EXIT_FAILURE;\n }\n }\n printq(nameq);\n\n q_pop(nameq);\n printq(nameq);\n\n const char *hname = q_peek(nameq);\n printf("head name = %s\\n", hname);\n\n q_free(nameq);\n}\n</code></pre>\n<p>This version has no errors when compiled by <code>gcc -std=c17 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wstrict-prototypes -Wconversion</code>, and no issues reported by Valgrind.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T16:59:10.063",
"Id": "503076",
"Score": "1",
"body": "Thank you very much, I'm not checking your modified code for the moment, I want to take your comments and modify the code myself then I'll compare with what you wrote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T17:01:26.747",
"Id": "503077",
"Score": "0",
"body": "damn, I realized that bits of code for eg the return from init got cut off. It's embarrassing, what happened is that I initially copy pasted from my emacs but the tabs became way off, so I went about correcting that and mistakenly deleted some code too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T17:01:27.740",
"Id": "503078",
"Score": "0",
"body": "Good idea - you'll learn more that way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T17:03:16.757",
"Id": "503079",
"Score": "0",
"body": "Ah, that explains how the code built and worked for you! No harm done (but consider setting `indent-tabs-mode` to `nil` in your Emacs)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T00:24:10.707",
"Id": "254812",
"ParentId": "254594",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T11:12:55.307",
"Id": "254594",
"Score": "2",
"Tags": [
"beginner",
"c",
"queue"
],
"Title": "Basic queue design and implementation"
}
|
254594
|
<p>I'm using a function to determine if resources can be used again or not.
This is the numpy array I'm using.</p>
<pre><code> 'Resource_id', 'Start_date', 'end_date', 'start_time', 'end_time', 'overload'
[548, '2019-05-16', '2019-05-16', '08:45:00', '17:40:00',2],
[546, '2019-05-16', '2019-05-16', '08:45:00', '17:40:00',2],
[546, '2019-05-16', '2019-05-16', '08:45:00', '17:40:00',2],
[543, '2019-05-16', '2019-05-16', '08:45:00', '17:40:00',1],
</code></pre>
<ol>
<li><p>First step is to find all resource available on a date, for example (2019-05-16 from 8:30 to 17:30). To achieve this I used <code>np.where</code> like the example below:</p>
<pre><code> av_resource_np = resource_availability_np[np.where(
(resource_availability_np[:,1] <= '2019-05-16')
& (resource_availability_np[:,2] >= '2019-05-16')
& (resource_availability_np[:,3] <= '17:30:00')
& (resource_availability_np[:,4] >= '08:30:00'))]
</code></pre>
</li>
<li><p>Here I try to find unique resource ids and the sum of their overload factor using <code>np.unique()</code>:</p>
<pre><code> unique_id, count_nb = np.unique(av_resource_np[:,(0,5)], axis=0, return_counts=True)
availability_mat = np.column_stack((unique_id, count_nb ))
</code></pre>
</li>
</ol>
<p>Which yields the following results:</p>
<pre><code>'Resource_id' 'overload' 'Count'
548 2 1
546 2 2
543 1 1
</code></pre>
<ol start="3">
<li><p>A simple filtering is done to select which resource hat can't be used in this date. If a resource is used in the same date <code>more or equal (>=)</code> to its<code>overload</code>, then we can't use it again.</p>
<pre><code> rejected_resources = availability_mat [np.where(availability_mat [:, 2] >= availability_mat [:, 1])]
</code></pre>
</li>
</ol>
<p><strong>Result</strong> here should be both resource <code>543</code> and <code>546</code> which can't be used again.</p>
<p>So this is main idea behind my function, the problem here is that it takes more than 60% of the whole program runtime and I would appreciate any advice about how to make it more efficient/faster. Thank you.</p>
<p>Full code:</p>
<pre><code>def get_available_rooms_on_date_x(date, start_time, end_time, resource_availability_np):
av_resource_np = resource_availability_np[np.where(
(resource_availability_np[:,1] <= date)
& (resource_availability_np[:,2] >= date)
& (resource_availability_np[:,3] <= end_time)
& (resource_availability_np[:,4] >= start_time))]
unique_id, count_nb = np.unique(av_resource_np[:,(0,5)], axis=0, return_counts=True)
availability_mat = np.column_stack((unique_id, count_nb ))
rejected_resources = availability_mat [np.where(availability_mat [:, 2] >= availability_mat [:, 1])]
return rejected_resources
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T12:28:34.643",
"Id": "502095",
"Score": "0",
"body": "Welcome to the Code Review Community. This question could be improved if you change the title to something like `Room Reservation System` and include the entire program. You state that the function takes 60% of the program execution time, it would help us optimize the code if we could see the rest of the program. The title should be about what the code does, and not what your concerns are about the code. Actual questions about the code should be in the body of the post. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask) for more details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T02:00:35.283",
"Id": "502159",
"Score": "0",
"body": "I see you tagged this with pandas, but didn't mention it in your question or use it in your example code. Are you considering using a pandas dataframe instead of your array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T02:01:06.443",
"Id": "502160",
"Score": "0",
"body": "Also, is your numpy array a record array for an ndarray with an object dtype?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:01:59.347",
"Id": "502189",
"Score": "0",
"body": "@PaulH, i was using this with pandas but it gave me worse performance so i tried it with numpy. Also ndarray has the correct type for each column."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:02:57.733",
"Id": "502190",
"Score": "0",
"body": "@pacmaninbw, thank you for your explanation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T15:22:11.153",
"Id": "502217",
"Score": "0",
"body": "Could you add code that generates the ndarray?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T08:22:05.187",
"Id": "502401",
"Score": "0",
"body": "The resource_availability_np array receives data from a converted pandas dataframe to numpy while removing unnecessary columns. I have changed the type of ndarray also so its no longer objects, this made it slightly faster unfortuanly not what i look for."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T11:35:03.950",
"Id": "254595",
"Score": "1",
"Tags": [
"performance",
"python-3.x",
"numpy",
"pandas"
],
"Title": "Resource reservation system"
}
|
254595
|
<p>As a little standard exercise, I wrote an integer to roman numerals converter in F03. The result looks already neat enough, for my standards, but I wonder whether it could be made snappier without sacrificing clarity. For folks not familiar with the simple syntax of modern Fortran, I suggest the following <a href="https://fortran-lang.org/learn/quickstart" rel="nofollow noreferrer">quick modern Fortran tutorial</a>.</p>
<pre class="lang-fortran prettyprint-override"><code>module mRomanStrings
implicit none
private
character(len=*), parameter :: RM_CHARS = "IVXLCDMvxlcdm_"
integer , parameter :: MAX_ORDER = len(RM_CHARS)/2-1
character(len=4) :: ROMAN_STRING(0:9,0:MAX_ORDER)
logical :: mRomanStringsIsNotInitialized = .TRUE.
public :: IntegerToRoman
contains
function IntegerToRoman(i) result(rm)
integer , intent(in) :: i
character(len=:), allocatable :: rm
integer :: n
if( mRomanStringsIsNotInitialized ) call mRomanSring_init()
rm = " "
do n = min(MAX_ORDER,int(log(dble(i))/log(10.d0)+1.d-10)), 0, -1
rm = trim(rm)//trim(ROMAN_STRING(mod(i/10**n,10),n))
enddo
end function IntegerToRoman
subroutine mRomanSring_init()
character :: a0, a1, a2, a3
integer :: n
do n = 0, MAX_ORDER
a0 = " "
a1 = RM_CHARS(2*n+1:2*n+1)
a2 = RM_CHARS(2*n+2:2*n+2)
a3 = RM_CHARS(2*n+3:2*n+3)
ROMAN_STRING(0:9,n) = [&
a0//a0//a0//a0, a1//a0//a0//a0, a1//a1//a0//a0, a1//a1//a1//a0, a1//a2//a0//a0, &
a2//a0//a0//a0, a2//a1//a0//a0, a2//a1//a1//a0, a2//a1//a1//a1, a1//a3//a0//a0 ]
enddo
mRomanStringsIsNotInitialized = .FALSE.
end subroutine mRomanSring_init
end module mRomanStrings
program ConvertIntegersToRoman
use, intrinsic :: iso_fortran_env
use mRomanStrings
implicit none
integer :: i
do i=1,10000
write(OUTPUT_UNIT,"(i6,x,a)") i, IntegerToRoman(i)
enddo
end program ConvertIntegersToRoman
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T14:32:47.107",
"Id": "502104",
"Score": "0",
"body": "There is an error in your the initialization routine. `2 * MAX_ORDER + 3 > size(RM_CHARS)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T14:33:43.000",
"Id": "502105",
"Score": "0",
"body": "If you compile with `gfortran -g -Wall -Wextra -Warray-temporaries -Wconversion -fimplicit-none -fbacktrace -ffree-line-length-0 -fcheck=all -ffpe-trap=zero,overflow,underflow -finit-real=nan` You get automatically warned about boundary violations."
}
] |
[
{
"body": "<p>It is overall good code, but there are of course some points to improve.</p>\n<p><strong>Objectively wrong and severe</strong>:</p>\n<ol>\n<li><p>Always compile with as much debug options as possible with your compiler. It detects errors such as</p>\n<pre><code>2 * MAX_ORDER + 3 == 2 * (size(RM_CHARS) / 2 - 1) + 3 > size(RM_CHARS)\n</code></pre>\n<p>in your initialization loop.</p>\n</li>\n<li><p>The function expects a number that is larger than zero and smaller than 10^6. This is nowhere documented nor checked.</p>\n</li>\n</ol>\n<p><strong>Small things that could be made better</strong>:</p>\n<ol>\n<li><p>There are unnecessary many <code>trim</code> calls when you build up the string. If you only append trimmed strings, you know that the result is trimmed.</p>\n</li>\n<li><p>There is <code>log10</code> for the decadic logarithm.</p>\n</li>\n<li><p>It helps sometimes to introduce additional variable names for self documentation.</p>\n</li>\n<li><p>I would recommend to use the words magnitude, exponent, and mantissa in the code. This is more self-explaining than "order".</p>\n</li>\n<li><p>It is not necessary to start from Zero for the first dimension of <code>ROMAN_STRING</code></p>\n</li>\n<li><p>I would never name a logical variable with its negated form. You can always use <code>.not.</code> and it quickly becomes hard to read if you doubly negate it. The name could be shorter in addition.</p>\n<pre><code>mRomanStringsIsNotInitialized == .not. mRomanStringInitialized\n.not. mRomanStringsIsNotInitialized == mRomanStringInitialized\n</code></pre>\n</li>\n<li><p>I would use <code>floor</code> instead of <code>int</code>. It is a common error to use <code>int</code> instead of <code>nint</code> so it is nice to explicitly say <code>floor</code>.</p>\n</li>\n</ol>\n<p><strong>Architecture</strong>:</p>\n<p>At the moment you have runtime checks in your function to ensure initialization of <code>ROMAN_STRING</code>. This is not necessary since <code>ROMAN_STRING</code> could be made a compile time constant (with <code>parameter</code>).\nIf you do this then your function does not depend anymore on a global variable that can be mutated at run time, can be made <code>pure</code> and is probably a tiny bit faster.</p>\n<p><strong>Opinion based</strong>:</p>\n<p>I would add more whitespace around your operators and after commata and use an indentation of at least 4 spaces.\nYou can format Fortran code pretty much according to the PEP8 guidelines of python, to achieve convincing results. (Especially since a lot of people in scientific computing use both languages.)</p>\n<p>Everything together leads to:</p>\n<pre><code> module mRomanStrings\n \n implicit none\n private\n integer , parameter :: MAX_MAGNITUDE = 5 \n character(len=4), parameter :: ROMAN_STRING(9, 0 : MAX_MAGNITUDE) = & \n reshape([character(4) :: &\n 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', &\n 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', &\n 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', &\n 'M', 'MM', 'MMM', 'Mv', 'v', 'vM', 'vMM', 'vMMM', 'Mx', &\n 'x', 'xx', 'xxx', 'xl', 'l', 'lx', 'lxx', 'lxxx', 'xc', &\n 'c', 'cc', 'ccc', 'cd', 'd', 'dc', 'dcc', 'dccc', 'cm'], &\n [9, MAX_MAGNITUDE + 1]) \n public :: IntegerToRoman\n \n contains\n \n !> Expects an integer 1 <= n <= (10^6 - 1) and returns\n !> the Roman number literal as string.\n pure function IntegerToRoman(n) result(rm)\n integer, intent(in) :: n\n character(len=:), allocatable :: rm\n integer :: largest_magnitude, mag, mantissa\n if (n <= 0) error stop\n \n largest_magnitude = floor(log10(dble(n)))\n if (largest_magnitude > MAX_MAGNITUDE) error stop\n \n rm = ""\n do mag = largest_magnitude, 0, -1\n mantissa = mod(n / 10**mag, 10) \n if (mantissa > 0) then\n rm = rm // trim(ROMAN_STRING(mantissa, mag))\n end if\n end do\n end function IntegerToRoman\n \n end module mRomanStrings\n \n program ConvertIntegersToRoman\n use, intrinsic :: iso_fortran_env, only: OUTPUT_UNIT\n use mRomanStrings\n implicit none\n integer :: i\n do i = 1, 99999\n write(OUTPUT_UNIT,"(i6,x,a)") I, IntegerToRoman(i)\n end do\n end program ConvertIntegersToRoman\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:19:52.693",
"Id": "502195",
"Score": "0",
"body": "Thanks for the detailed and informative feedback mcocdawc. Not sure about the four-space indentation: I like the default in emacs. By the way, it looks like julia should be a more natural companion to people in the fortran community than python. Any thoughts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T14:26:37.907",
"Id": "502212",
"Score": "0",
"body": "When I see floor instead of int I am starting to look what is going on with negative numbers and get confused when it is in fact nothing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T16:23:24.377",
"Id": "502225",
"Score": "0",
"body": "@LucaArgenti I worked once with Julia for a numeric task when it had version 0.6. Even then I liked it, and I guess they have improved the things that I did not like. (It was fast after JIT compilation, but the first execution of a function was really slow. Since you could not easily precompile functions, it was slower than python if you only executed functions once.) \nIf I started a new numerics project now, I would definitely consider Julia, \nbut since our number crunching tasks rely on existing Fortran code with more than 10^6 lines of code you just don't rewrite it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T16:29:09.203",
"Id": "502227",
"Score": "0",
"body": "For postprocessing/plotting I have good workflow with numpy/pandas/matplotlib and speed does not matter, so I won't change it. I assume it is the case for a lot of colleagues. \nNevertheless I am happy to have at least written a short serious program with Julia, because their multiple dispatch paradigm is really nice. \nIt definitely improved my code to use a bit less OOP and a bit more overloaded but free functions. (free as in not a method) PS: With vim you write much better Fortran code. ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T16:31:23.560",
"Id": "502228",
"Score": "0",
"body": "@VladimirF I am sorry, but I don't really get your argument `floor(-3.5) == -4` is IMHO not nothing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:05:19.943",
"Id": "502232",
"Score": "0",
"body": "Once again. Once I see floor, I see what the code is doing there and why it cares so much about negative numbers that it introduces floor instead of int and why it must specifically round towards smaller negative numbers. The nothing means the confusion when I realize the author just used floor because they felt like using it today instead of the usual int."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:22:02.860",
"Id": "502240",
"Score": "0",
"body": "Ok, that makes also sense but I still think, that the danger of not using `nint` is much larger, so let's agree to disagree."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:56:06.770",
"Id": "502249",
"Score": "0",
"body": "@mcocdawc I use vim as well, to inspect files quickly, and indent by hand. Not sure why the code would be better though, apart for the personal teste of indentation. I am still unsure whether to invest in Julia. Speed apart, I am not convinced that it will eliminate the two-code problem (prototype in a high-level language, and subsequently implement in a low level one)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:57:45.610",
"Id": "502251",
"Score": "0",
"body": "I imagine they'll eventually find a way to bypass some of the overhead of the on-demand compilation. I like multiple-dispatch too. However, it does not add much to fortran, since it already has this feature. And I agree that OOP as a single paradigm brings more conceptual tangles than necessary. We'll see how it goes. I should embrace more python, though, because I see the advantage of having a large community with well crafted best practices where to plunge students to learn clean coding (and a shower from time to time is good for me as well)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T15:52:04.837",
"Id": "254607",
"ParentId": "254601",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254607",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T13:09:22.403",
"Id": "254601",
"Score": "3",
"Tags": [
"performance",
"converting",
"fortran"
],
"Title": "Integer to Roman Numeral conversion"
}
|
254601
|
<p>As an exercise in using channels in Go I implemented a breadth-first traversal of a binary tree, using a channel as a queue to store the order of the nodes to traverse. After ironing out a bunch of bugs related to all goroutines sleeping I ended up with this code:</p>
<pre class="lang-golang prettyprint-override"><code>package main
import "fmt"
type Node struct {
Value int
Left *Node
Right *Node
}
var tree *Node
func init() {
tree = &Node{1, &Node{2, &Node{4, &Node{6, nil, nil}, nil}, &Node{5, nil, &Node{7, nil, nil}}}, &Node{3, nil, nil}}
}
func (t *Node) BFS() {
c := make(chan *Node, 512)
c <- t
bfs(c)
close(c)
}
func bfs(c chan *Node) {
empty := false
for {
select {
case next := <-c:
if next != nil {
c <- next.Left
c <- next.Right
fmt.Println(next.Value)
}
default:
empty = true
}
if empty {
break
}
}
}
func main() {
tree.BFS()
}
</code></pre>
<p>While I appreciate advice on any part of the code, I am specifically concerned about the tight <code>for</code> loop in the body of <code>bfs()</code>, the not particularly safe-for-concurrency code and other possible issues mentioned in <a href="https://stackoverflow.com/q/3398490">this question on stackoverflow</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T15:47:18.630",
"Id": "254606",
"Score": "1",
"Tags": [
"go",
"queue",
"breadth-first-search"
],
"Title": "Breadth first search of a binary-tree with channels"
}
|
254606
|
<p><strong>Original problem:</strong>
Given <span class="math-container">\$x\$</span> number of tests that should run in <span class="math-container">\$y\$</span> number of seconds shift the time per test so that each test takes a little longer than the next.</p>
<p><strong>Example:</strong> If running 10 tests over 10 seconds, the equal time per test would be 1 second each.
Instead, have the first test take .5 seconds and the last test take 1.5 seconds while each subsequent test take a progressively longer duration. We shift the time per test around while still maintaining the original duration of 10 seconds for the 10 tests.</p>
<p>I am slightly ignorant of what math principles are occurring. I knew <em>how</em> I wanted to solve the problem but I can't <em>describe</em> the problem. I've made it possible to adjust how much shifting can be done. Since the array of times is linear (and we can't really have negative times) I put a limit on that 'shifting' value.</p>
<ol>
<li>How do you describe this function / math problem? (which would hopefully result in a better name for it).</li>
<li>What should the <code>pct</code> variable be called? I originally thought it to be a percentage of each second, but as I developed the function I realized this was inaccurate; since after the first value, the percentage of shifting per time slice goes down then back up again.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>def duration_spread(tests: float, seconds: float, pct: float = .75):
assert -1 <= pct <= 1, "pct must be within +/-100% otherwise it will push times into negative"
pct *= 2
original_velocity = seconds/tests
seconds_per_tests = original_velocity # couldn't decide on naming convention
average_velocity = original_velocity
diff_average_velocity = pct * average_velocity
acceleration = diff_average_velocity/tests
multiplier_list = get_multipliers(tests)
results = []
for i, multiplier in enumerate(multiplier_list):
newadjustment = (multiplier * acceleration)
newtime = original_velocity + newadjustment
print(f"{original_velocity} -> {newtime} :: {abs(newadjustment)}")
results.append(newtime)
return results
def get_multipliers(tests: float):
odd = int(tests % 2)
half_tests = int(tests // 2)
result = list(range(-half_tests, half_tests+1))
if not odd:
result.pop(half_tests)
return result
</code></pre>
|
[] |
[
{
"body": "<p>This first, superficial refactor does the following:</p>\n<ul>\n<li>Rearrange functions in order of dependency</li>\n<li>Represent the return value of <code>get_multipliers</code> as a range and not a list for greater efficiency</li>\n<li>You're accepting a fraction, not a percentage; your inputs are -1 through 1, not -100 through 100</li>\n<li>some minor variable name abbreviations</li>\n<li>convert <code>duration_spread</code> to a generator</li>\n<li>delete some unused variables</li>\n<li>do not debug-print within your routine</li>\n<li>show the results in a test method</li>\n</ul>\n<p>This gets us to</p>\n<pre><code>from typing import Iterable, Sequence\n\n\ndef get_multipliers(n_tests: int) -> Sequence[float]:\n odd = int(n_tests % 2)\n half_tests = int(n_tests // 2)\n if odd:\n yield from range(-half_tests, half_tests+1)\n else:\n yield from range(-half_tests, 0)\n yield from range(1, half_tests + 1)\n\n\ndef duration_spread(n_tests: int, seconds: float, frac: float = .75) -> Iterable[float]:\n assert -1 <= frac <= 1, "frac must be within +/-100%"\n orig_velocity = seconds / n_tests\n diff_avg_velocity = frac * 2 * orig_velocity\n accel = diff_avg_velocity / n_tests\n\n multipliers = get_multipliers(n_tests)\n for multiplier in multipliers:\n adj = multiplier * accel\n new_time = orig_velocity + adj\n yield new_time\n\n\ndef test():\n new_times = tuple(duration_spread(10, 10, .5))\n print(new_times)\n print(sum(new_times))\n\n\ntest()\n</code></pre>\n<p>Do some math and you'll see that for a series of <span class=\"math-container\">\\$n\\$</span> integers, the total is:</p>\n<p><span class=\"math-container\">\\$\n\\sigma = \\sum _1 ^n i = \\frac {n(n+1)} 2\n\\$</span></p>\n<p>If you introduce a spacing parameter <span class=\"math-container\">\\$\\alpha\\$</span> and base offset <span class=\"math-container\">\\$\\delta\\$</span>, this becomes</p>\n<p><span class=\"math-container\">\\$\n\\sigma = \\sum _1 ^n \\left(\\alpha i + \\delta\\right) = \\frac {\\alpha n(n+1)} 2 + n\\delta\n\\$</span></p>\n<p>Since your <span class=\"math-container\">\\$\\alpha\\$</span> and <span class=\"math-container\">\\$n\\$</span> are fixed, you need to solve for <span class=\"math-container\">\\$\\delta\\$</span>:</p>\n<p><span class=\"math-container\">\\$\n\\delta = \\frac \\sigma n - \\frac {\\alpha(n+1)} 2\n\\$</span></p>\n<p>Applying this to some simplified code yields the correct results:</p>\n<pre><code>from math import isclose\nfrom typing import Iterable\n\n\ndef duration_spread(n_tests: int, seconds: float, alpha: float) -> Iterable[float]:\n delta = seconds/n_tests - alpha*(n_tests - 1)/2\n for i in range(n_tests):\n yield delta + i*alpha\n\n\ndef test():\n times = tuple(duration_spread(10, 20, .3))\n total = sum(times)\n print(' + '.join(f'{x:.1f}' for x in times), f'= {total:.1f}')\n\n assert isclose(total, 20)\n for i in range(1, 10):\n assert isclose(.3, times[i] - times[i-1])\n\n\ntest()\n</code></pre>\n<pre><code> 0.7 + 1.0 + 1.2 + 1.6 + 1.9 + 2.1 + 2.5 + 2.8 + 3.0 + 3.4 = 20.0\n</code></pre>\n<p>As an exercise to you: to re-introduce validation now that we're using a spacing parameter instead of a fraction, what would be an upper bound on the spacing parameter? You were in the right direction in chat; the criterion boils down to verifying that <code>delta > 0</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T06:41:59.670",
"Id": "502300",
"Score": "0",
"body": "`this should output 10 but actually outputs 9.5`. Right, but OP's original code outputs 10."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T14:40:59.967",
"Id": "502340",
"Score": "0",
"body": "@Marc Good catch; I've fixed that regression. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T15:44:39.420",
"Id": "502343",
"Score": "0",
"body": "This is thoughtfully considered. A new problem arises in your refactored version whereby the returned durations contain negative values when the number of tests exceeds the number of seconds. If I plug in 10 seconds for 20 tests with an alpha of .3, the first 9 values returned are negative. It was this problem alone caused me to realize I didn't know what the argument `pct` actually was."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T15:45:22.743",
"Id": "502344",
"Score": "0",
"body": "That's why I've included my last sentence about upper bounds :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T15:49:07.783",
"Id": "502345",
"Score": "0",
"body": "Try `duration_spread(20, 10, .02)`. The number of tests exceeds the number of seconds and the output is correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T15:50:03.323",
"Id": "502346",
"Score": "0",
"body": "To answer your question, I think only upper bound to the spacing value should be the total number of seconds. I can see now, my limit was based on how much of each slice could be taken off; e.g. the limit was the size of each slice. The lower bounds on the returned seconds between tests ought to be 0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T15:51:41.290",
"Id": "502347",
"Score": "0",
"body": "Part of my issue in trying to understand the problem is I never took calculus. (which is making it much hard to even discuss, let alone solve)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T15:52:32.107",
"Id": "502348",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/118458/discussion-between-reinderien-and-marcel-wilson)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:11:09.223",
"Id": "254661",
"ParentId": "254609",
"Score": "2"
}
},
{
"body": "<blockquote>\n<p>How do you describe this function / math problem?</p>\n</blockquote>\n<p>The input is a list of tests with the same duration. For example, <span class=\"math-container\">\\$input=[2,2,2,2]\\$</span>. Given the indexes from 0 to 3, we can see it in a graph:</p>\n<p><a href=\"https://i.stack.imgur.com/Xigc1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Xigc1.png\" alt=\"enter image description here\" /></a></p>\n<p>So we can define the input as a (discrete) function <span class=\"math-container\">\\$f(x)=2\\$</span>, or in general <span class=\"math-container\">\\$f(x) = seconds/tests\\$</span>. Where <span class=\"math-container\">\\$0<=x<=tests,x∈Z\\$</span>.</p>\n<p>The function <span class=\"math-container\">\\$durationSpread\\$</span> can be described as <span class=\"math-container\">\\$durationSpread = g(x) * f(x)\\$</span>. Where <span class=\"math-container\">\\$g(x)\\$</span> is a function that depends on <span class=\"math-container\">\\$pct\\$</span> and <span class=\"math-container\">\\$tests\\$</span>. In the following I am going to refer it as <span class=\"math-container\">\\$g(pct,tests)\\$</span>.</p>\n<h2>Function analysis</h2>\n<p>For <code>pct=0</code> the input remains the same: <span class=\"math-container\">\\$g(pct,tests) * input = g(0,4) * [2,2,2,2] = [2, 2, 2, 2]\\$</span>. Meaning that all elements of the input are multiplied by 1. So <span class=\"math-container\">\\$g\\$</span> should look like this:\n<a href=\"https://i.stack.imgur.com/1TCx8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1TCx8.png\" alt=\"enter image description here\" /></a></p>\n<p>For <code>pct=-1</code> the result "should be": <span class=\"math-container\">\\$g(-1,4) * [2,2,2,2] = [4.0, 2.67, 1.33, 0.0]\\$</span>. The first element of of the input is multiplied by 2, the last one by 0, and the elements in between by a descending factor.</p>\n<p>I said "should be" because your code outputs <span class=\"math-container\">\\$[4.0,3.0,1.0,0.0]\\$</span>, which is not possible if we consider a constant factor (the gap betweenn 4.0 and 3.0 is 1, but between 3.0 and 1.0 is 2).</p>\n<p>So <span class=\"math-container\">\\$g\\$</span> should look like this:\n<a href=\"https://i.stack.imgur.com/nnSpP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nnSpP.png\" alt=\"enter image description here\" /></a>\nFor <code>pct=1</code> the result is: <span class=\"math-container\">\\$g(1,4) * [2,2,2,2] = [0.0, 1.33, 2.67, 4.0]\\$</span>. In this case, the first element is multiplied by 0 and the last one by 2. So the function <span class=\"math-container\">\\$g\\$</span> is:\n<a href=\"https://i.stack.imgur.com/CaSHW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CaSHW.png\" alt=\"enter image description here\" /></a></p>\n<p>How to find <span class=\"math-container\">\\$g\\$</span>? From the three examples, we know that <span class=\"math-container\">\\$g\\$</span> is a <strong>linear function</strong>. A linear function can be represented as <code>y = mx + b</code>. How to find <code>m</code> and <code>b</code>? They can be found given two points.</p>\n<p>Let's choose the first point <code>(x0,y0)</code> in the origin. <code>x0</code> is always 0. While <code>y0</code> depends on <code>pct</code>. Looking at the examples, we can tell that it's equal to <code>abs(pct - 1)</code>. Explanation:</p>\n<ul>\n<li>In the first example <code>pct=0</code> and <code>y0=1</code>. In fact, <code>y0 = abs(0 - 1) = 1</code></li>\n<li>In the second example <code>pct=-1</code> and <code>y0=2</code>. In fact, <code>y0 = abs(- 1 - 1) = abs(-2) = 2</code></li>\n<li>In the third example <code>pct=1</code> and <code>y0=0</code>. In fact, <code>y0 = abs(1 - 1) = abs(0) = 0</code></li>\n</ul>\n<p>For the second point <code>(x1,y1)</code>, we can choose the center. Where <code>y1</code> is always 1. While <code>x1</code> can be found as <code>x1 = (tests-1)/2</code>. (You can double-check in the three examples).</p>\n<p>Given two points we can find the <strong>slope</strong> <code>m</code> as <code>m = (y1 - y0) / (x1 - x0)</code>. Once we have <code>m</code>, we calculate the <strong>constant</strong> <code>b</code> as <code>b = y0 - (m * x0)</code>.</p>\n<p>Now that we found <span class=\"math-container\">\\$g\\$</span>, we can multiply the input by <span class=\"math-container\">\\$g\\$</span>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def duration_spread(tests, seconds, pct):\n x0, y0 = 0, abs(pct - 1)\n x1, y1 = (tests - 1) / 2, 1\n m = (y1 - y0) / (x1 - x0)\n b = y0 - (m * x0)\n unit_time = seconds / tests\n return [unit_time * (m * x + b) for x in range(tests)]\n</code></pre>\n<p>Some tests:</p>\n<pre><code>times = duration_spread(4, 8, 1)\nprint(' '.join(f'{x:.1f}' for x in times))\n# output: 0.0 1.3 2.7 4.0\n\ntimes = duration_spread(5, 10, -1)\nprint(' '.join(f'{x:.1f}' for x in times))\n# output: 4.0 3.0 2.0 1.0 0.0\n\ntimes = duration_spread(5, 10, .5)\nprint(' '.join(f'{x:.1f}' for x in times))\n# output: 1.0 1.5 2.0 2.5 3.0\n</code></pre>\n<h2>Code review</h2>\n<p>Very short since @Reinderien covered most of the ground.</p>\n<ul>\n<li><strong>Input type</strong>: <code>tests</code> represents the number of tests, so I am not sure why it's a <code>float</code>. It should be an integer.</li>\n<li><strong>Missing return type hint</strong>: the return type hint is missing in both functions.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T17:40:02.143",
"Id": "502450",
"Score": "0",
"body": "It took me a while to get there, but @Reinderien 's explanation of the formula for sum of integers with a spacing parameter got me to understand where my solution was insufficient. You point it out as well, I used the trick of dividing the range in half which doesn't allow the resulting slope to remain linear. I knew what needed to be done for the first and last elements in the array and extrapolated (incorrectly) for the rest of the array. Looking back; I didn't know what I didn't know -- which was the proper math behind this type of problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T14:04:02.200",
"Id": "502522",
"Score": "0",
"body": "@MarcelWilson sure, this is just another way of solving the same problem. It keeps the original parameter `pct` and uses simpler math, but maybe it's less elegant than Reinderien's solution. I tried to make it as simple as possible. When you are satisfied, don't forget to accept an answer ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T07:57:02.053",
"Id": "254734",
"ParentId": "254609",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254661",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T16:12:44.277",
"Id": "254609",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Redistributing times"
}
|
254609
|
<p><strong>Problem</strong></p>
<p>I'm seeking a clean and efficient way to determine whether one string is an initialism/acronym of another.</p>
<p>Example: <strong>IBM</strong> => <strong>I</strong>nternational <strong>B</strong>usiness <strong>M</strong>achines</p>
<p><strong>However</strong>, a key condition for my use case is that an initialism might be constructed using <em>more than one</em> letter from each consecutive word.</p>
<p>Example: <strong>ANEXAIST</strong> = <strong>An</strong> <strong>Exa</strong>mple <strong>Is</strong> <strong>T</strong>his</p>
<p><strong>Working solution</strong></p>
<p>My solution works, though only returns a single answer (even when multiple might exist - this is fine for my use case). I wonder if there's a cleaner and more efficient implementation?</p>
<pre><code>s1 = 'anexithi'
s2 = 'an example is this'
def recursive_split(s1, s2, mapping=[]):
for s1_sub in [s1[:i] for i in range(4)]:
if s1_sub!='' and s1_sub == s2[:len(s1_sub)]:
mapping_ = mapping + [(s1_sub, s2.split()[0])]
if s1_sub == s1:
return mapping_
rec = recursive_split(s1[len(s1_sub):], ' '.join(s2.split()[1:]), mapping_)
if rec is not None:
return rec
recursive_split(s1, s2)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>[('an', 'an'), ('ex', 'example'), ('i', 'is'), ('thi', 'this')]
</code></pre>
|
[] |
[
{
"body": "<h1>Correctness</h1>\n<ul>\n<li><p>Your code allows partial acronyms which doesn't seem right. "I'm seeking a clean and efficient way to determine whether one string is an initialism/acronym of another."</p>\n<pre><code>recursive_split('aei', 'an example is this')\n# [('a', 'an'), ('e', 'example'), ('i', 'is')]\n</code></pre>\n</li>\n</ul>\n<h1>Performance 1</h1>\n<ol>\n<li><p>A list comprehension being fed into a for loop is not idiomatic. It would be better if you move the expression into the for's expression.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(4):\n s1_sub = s1[:i]\n</code></pre>\n</li>\n<li><p>It should be clear if <code>len(s1_sub) != i</code> then <code>s1_sub == s2[:len(s1_sub)]</code> is going to call the body multiple times with the same values. To address this wastage we can bound the for loop.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(min(4, 1 + len(s2))):\n</code></pre>\n</li>\n<li><p>Rather than <code>s1_sub!=''</code> we can start the range at 1.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(1, min(4, 1 + len(s2))):\n</code></pre>\n</li>\n<li><p>If <code>len(s1) < len(s2)</code> then we are wasting iterations of the for loop when we could just adjust the range.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(1, min(4, 1 + len(s1), 1 + len(s2))):\n</code></pre>\n</li>\n<li><p>If <code>s1[:i] != s2[:i]</code> then i+1 will always be false too. You should instead <code>break</code> if this is ever false.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(1, min(4, 1 + len(s1), 1 + len(s2))):\n s1_sub = s1[:i]\n if s1_sub != s2[:i]:\n break\n # do stuff\n</code></pre>\n</li>\n<li><p>We don't need to slice <code>s1</code> and <code>s2</code> to compare the values. We can just index. This makes the range a little simpler.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(min(3, len(s1), len(s2))):\n if s1[i] != s2[i]:\n break\n s1_sub = s1[:1 + i]\n</code></pre>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def recursive_split(s1, s2, mapping=[]):\n for i in range(min(3, len(s1), len(s2))):\n if s1[i] != s2[i]:\n break\n s1_sub = s1[:1 + i]\n mapping_ = mapping + [(s1_sub, s2.split()[0])]\n if s1_sub == s1:\n return mapping_\n rec = inner(s1[len(s1_sub):], ' '.join(s2.split()[1:]), mapping_)\n if rec is not None:\n return rec\n</code></pre>\n<h1>Clean code</h1>\n<p>Many of the changes above have increased the readability of your code.</p>\n<ul>\n<li>The names <code>s1</code> and <code>s2</code> aren't very descriptive.</li>\n</ul>\n<h1>Performance 2</h1>\n<p>These are some more advanced performance changes. Depending on the person the decreased readability may not outweigh the performance gains.</p>\n<ol start=\"7\">\n<li><p>Rather than using <code>mapping=[]</code> you can use a closure and pass a fresh mapping.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def recursive_split(s1, s2):\n def inner(s1, s2, mapping):\n for i in range(min(3, len(s1), len(s2))):\n if s1[i] != s2[i]:\n break\n s1_sub = s1[:1 + i]\n mapping_ = mapping + [(s1_sub, s2.split()[0])]\n if s1_sub == s1:\n return mapping_\n rec = inner(s1[len(s1_sub):], ' '.join(s2.split()[1:]), mapping_)\n if rec is not None:\n return rec\n return inner(s1, s2, [])\n</code></pre>\n</li>\n<li><p>Constantly calling <code>s2.split()</code> and <code>' '.join(s2.split()[1:])</code> are very wasteful. Instead you could call <code>str.split</code> <em>once</em> and just work with the split list.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def recursive_split(s1, s2):\n def inner(s1, s2_index, mapping):\n try:\n s2 = s2s[s2_index]\n except IndexError:\n return None\n for i in range(1, min(4, 1 + len(s1), 1 + len(s2))):\n s1_sub = s1[:i]\n if s1_sub != s2[:i]:\n break\n mapping_ = mapping + [(s1_sub, s2s[s2_index])]\n if s1_sub == s1:\n return mapping_\n rec = inner(s1[len(s1_sub):], s2_index + 1, mapping_)\n if rec is not None:\n return rec\n s2s = s2.split()\n return inner(s1, 0, [])\n</code></pre>\n</li>\n<li><p>We don't need to add <code>s2s[s2_index]</code> to <code>mapping_</code> because <code>s2_index</code> only ever increases by 1 each time so we can do that outside of <code>inner</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>mapping_ = mapping + [s1_sub]\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>ret = inner(s1, 0, [])\nif ret is None:\n return None\nreturn list(zip(ret, s2s))\n</code></pre>\n</li>\n<li><p>With <code>mapping + [s1_sub]</code> will make near duplicate copy each time you recurse. We can improve the performance by mutating the mapping.</p>\n<p>To do this we just append to the stack where you did <code>mapping + [s1_sub]</code> and then pop after any recursion.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def recursive_split(s1, s2):\n def inner(s1, s2_index, mapping):\n try:\n s2 = s2s[s2_index]\n except IndexError:\n return None\n for i in range(min(3, len(s1), len(s2))):\n if s1[i] != s2[i]:\n break\n s1_sub = s1[:1 + i]\n mapping.append(s1_sub)\n if s1_sub == s1:\n return mapping\n else:\n rec = inner(s1[1 + i:], s2_index + 1, mapping)\n if rec is not None:\n return rec\n mapping.pop()\n s2s = s2.split()\n ret = inner(s1, 0, [])\n if ret is None:\n return None\n return list(zip(ret, s2s))\n</code></pre>\n</li>\n<li><p>We can do something similar to <code>s1</code>. However instead of appending and popping we can pop in the for loop and then extend after the for loop. As such we just need to reverse <code>s1</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def recursive_split(s1, s2):\n def inner(s1, s2_index, mapping):\n try:\n s2 = s2s[s2_index]\n except IndexError:\n return None\n s1_sub = []\n for i in range(min(3, len(s1), len(s2))):\n s1_sub.append(s1.pop())\n if s1_sub[-1] != s2[i]:\n break\n mapping.append(s1_sub)\n if not s1:\n return mapping\n else:\n rec = inner(s1, s2_index + 1, mapping)\n if rec is not None:\n return rec\n mapping.pop()\n s1.extend(s1_sub[::-1])\n s2s = s2.split()\n ret = inner(list(reversed(s1)), 0, [])\n if ret is None:\n return None\n return [\n (''.join(s1_sub), s2)\n for s1_sub, s2 in zip(ret, s2s)\n ]\n</code></pre>\n</li>\n<li><p>We can use generators and a couple of tricks to reduce the line count.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def recursive_split(s1, s2):\n def inner(s1, s2_index, mapping):\n s2 = s2s[s2_index]\n s1_sub = []\n for i in range(min(3, len(s1), len(s2))):\n s1_sub.append(s1.pop())\n if s1_sub[-1] != s2[i]:\n break\n mapping.append(s1_sub)\n if not s1:\n yield mapping\n elif s2_index + 1 < len(s2s):\n yield from inner(s1, s2_index + 1, mapping)\n mapping.pop()\n s1.extend(s1_sub[::-1])\n s2s = s2.split() or ['']\n rets = (\n [(''.join(s1_sub), s2) for s1_sub, s2 in zip(ret, s2s)]\n for ret in inner(list(reversed(s1)), 0, [])\n )\n return next(rets, None)\n</code></pre>\n</li>\n<li><p>Given your examples it would be better to use a greedy search. For each letter you recurse straight away however if you went from the point we break in the <code>for</code> loop then <code>inner</code> would never return <code>None</code> on your example data.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def recursive_split(s1, s2):\n def inner(s1, s2_index, mapping):\n s2 = s2s[s2_index]\n s1_sub = []\n for i in range(min(3, len(s1), len(s2))):\n s1_sub.append(s1.pop())\n if s1_sub[-1] != s2[i]:\n break\n while s1_sub:\n mapping.append(s1_sub)\n if not s1:\n yield mapping\n elif s2_index + 1 < len(s2s):\n yield from inner(s1, s2_index + 1, mapping)\n mapping.pop()\n s1.append(s1_sub.pop())\n # nonlocal counter\n # counter += 1\n # counter = 0\n s2s = s2.split() or ['']\n rets = (\n [(''.join(s1_sub), s2) for s1_sub, s2 in zip(ret, s2s)]\n for ret in inner(list(reversed(s1)), 0, [])\n )\n ret = next(rets, None)\n # print(counter)\n return ret\n</code></pre>\n<p>This prints 0, if you uncomment the code, where as the previous code printed 2 because it recursed on <code>a</code> from <code>an</code> and <code>e</code> from <code>ex</code>.</p>\n</li>\n<li><p>We can remove the recursion and so we can remove the stack frames.</p>\n<p>In the previous example it should be clear that <code>mapping</code> is acting like a stack and we can actually get <code>s2_index</code> from it.\nAdditionally we can see that the code is quite reliant now on the fact that we're mutating <code>s1</code>.</p>\n<p>So we can think of the code another way.</p>\n<ol>\n<li><p>Build the rest of the stack based on the state of <code>s1</code>.</p>\n<ul>\n<li>At first this is just the same as the <code>for i in range(...)</code> loop.</li>\n<li>If there are no matches, <code>s1_sub</code> is empty, then we have to start the popping process.</li>\n<li>Otherwise we add the value to the stack.</li>\n<li>Then if the length of the stack is the same as <code>s2s</code> then we have a value to return.</li>\n</ul>\n</li>\n<li><p>Pop from the stack.</p>\n<ul>\n<li>If we make a value in the stack empty, then we need to pop again from the stack, otherwise we'll have an infinite loop. As the builder will just build the exact same way.</li>\n<li>If we pop from the entire stack, we're done.</li>\n</ul>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def recursive_split(s1, s2):\n s1_ = list(reversed(s1))\n s2s = s2.split()\n stack = []\n while True:\n while len(stack) < len(s2s):\n s1_sub = []\n for value in s2s[len(stack)]:\n if not s1_ or value != s1_[-1]:\n break\n s1_sub.append(s1_.pop())\n if not s1_sub:\n break\n else:\n stack.append(s1_sub)\n if len(stack) == len(s2s):\n return [(''.join(values), s2) for values, s2 in zip(stack, s2s)]\n for _ in range(len(stack)):\n s1_.append(stack[-1].pop())\n if stack[-1]:\n break\n stack.pop()\n else:\n return\n</code></pre>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T23:53:08.700",
"Id": "502155",
"Score": "0",
"body": "Amazing how we hit most of the same inefficiencies, and yet our optimized solutions are so very different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T00:32:27.740",
"Id": "502157",
"Score": "0",
"body": "@AJNeufeld Yeah I really focused on not having any unneeded copies / calls to \\$O(n)\\$ functions, so my code is... not as nice as many would normally write it :) Makes me think it looks more like C like than Python..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:23:54.893",
"Id": "502196",
"Score": "0",
"body": "Brilliant answers both, it hardly seems fair to accept a single answer!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T23:05:36.913",
"Id": "254628",
"ParentId": "254612",
"Score": "5"
}
},
{
"body": "<h1>Inefficiencies</h1>\n<h2>Split/join</h2>\n<p>You are calling <code>s2.split()</code> a lot. This seems wasteful.</p>\n<p>Moreover, you are calling <code>' '.join(s2.split()[1:])</code> to get a string containing everything but the first word of <code>s2</code>. So not only are you repeatedly splitting the string, you're also rejoining the splits.</p>\n<p>You're doing a lot of work, just to throw it away and redo it in subsequent steps.</p>\n<h2>range(4)</h2>\n<p>The first value of <code>range(4)</code> is <code>0</code>. That value is used in <code>s1[:i]</code>, as <code>s1[:0]</code> which is an empty string. After constructing a list, which always starts with this empty string, you test <code>if s1_sub != '' and ...</code>, which will never be true on the first pass.</p>\n<p>Instead, you could use <code>range(1, 4)</code>, who's first value is <code>1</code>, avoiding the first empty string.</p>\n<h2>len(s1_sub)</h2>\n<p>You are using <code>len(s1_sub)</code> in a few places. This value used to be <code>i</code>, in the <code>for i in range(4)</code> statement. Instead of building up a list of possible prefixes, and then repeatedly determining the length of those prefixes, you could simply loop over the desired lengths directly:</p>\n<pre class=\"lang-py prettyprint-override\"><code>\n for i in range(1, 4):\n s1_sub = s1[:i]\n if s1_sub != '' and s1_sub == s2[:i]:\n ...\n</code></pre>\n<h2>Search pruning</h2>\n<p>On the first pass, you find the <code>'A'</code> from <code>s1</code> matches the first letter of the first word <code>an</code>. So you descend into the next recursive level with <code>'nexithi'</code> and <code>'example is this'</code>. You test <code>'n'</code> and discover that <code>'example is this'</code> doesn't start with an <code>'n'</code>.</p>\n<p>And then you proceed to test <code>'ne'</code>, followed by <code>'nex'</code>. Why? If it didn't start with <code>'n'</code>, it can't start with any longer substring. You could prune your searching!</p>\n<h2>Limit</h2>\n<p>Why <code>range(4)</code>? You're adding a restriction that the maximum prefix in each word is at most 3 characters. This wasn't part of the original problem statement.</p>\n<p>The limit should depend on the length of the remaining acronym and the remaining number of words. At the first level, with 3 words remaining (<code>example is this</code>), at most 5 characters of <code>'anexithi'</code> could be used, leaving at least 1 each for the remaining words. (Since the first word is only 2 letters long, we can further drop the limit to 2.)</p>\n<h1>Reworked Code</h1>\n<pre class=\"lang-py prettyprint-override\"><code>from os.path import commonprefix\n\ndef recursive_split(acronym, words):\n\n def recurse(acronym, words):\n head, *tail = words\n\n # Base case: when there are no more words\n if not tail:\n if acronym and head.startswith(acronym):\n return [(acronym, head)]\n return None\n\n # Determine longest allowed prefix for the first word\n limit = min(len(acronym) - len(tail), len(head))\n\n # Determine longest common prefix between acronym & first word \n longest_prefix = commonprefix([acronym, head])[:limit]\n \n for length in range(1, len(longest_prefix)+1):\n mapping = recurse(acronym[length:], tail)\n if mapping is not None:\n mapping.insert(0, (acronym[:length], head))\n return mapping\n \n return None \n\n words = words.split() # Only split s2 once, at the start!\n\n return recurse(acronym, words)\n\n\ns1 = 'anexithi'\ns2 = 'an example is this'\n\nresult = recursive_split(s1, s2)\nprint(result)\n</code></pre>\n<p>Notes:</p>\n<ol>\n<li>Although <code>commonprefix</code> is in <code>os.path</code>, it is an easy way to determine the common starting prefix of a group of strings. Since <code>commonprefix(['exithi', 'example']) == 'ex'</code>, we use this to determine we only need to test <code>'e'</code> and <code>'ex'</code> as possible prefixes at that level.</li>\n<li>When the last word is reached, <code>first.startswith(acronym)</code> is used to determine if the entire remaining <code>acronym</code> begins the last word, instead of uselessly trying each all leading substrings first.</li>\n<li>We now have an outer function, which can preprocess the input (such as calling <code>words.split()</code>).</li>\n<li>The outer function is no longer recursively called, so the <code>mapping=[]</code> default argument has been removed from the outer function.</li>\n<li>The inner function could have still had the <code>mapping</code> argument, but it wouldn't need a default, since the outer function could explicitly provide the required "default".</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T23:43:31.693",
"Id": "254630",
"ParentId": "254612",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "254628",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T16:55:43.543",
"Id": "254612",
"Score": "11",
"Tags": [
"python",
"recursion"
],
"Title": "Finding acronyms with >=1 letters at the start of each consecutive word"
}
|
254612
|
<p>I'm interested in feedback on my approach to handling cluster on Next.js SSG app with express hosted on Heroku.</p>
<p>The app is working however, please let me know if this is the wrong approach or if you see any potential mistake.</p>
<p><strong>Project specs:</strong></p>
<ul>
<li><a href="/questions/tagged/sticky-session" class="post-tag" title="show questions tagged 'sticky-session'" rel="tag">sticky-session</a> : ^1.1.2</li>
<li><a href="/questions/tagged/express" class="post-tag" title="show questions tagged 'express'" rel="tag">express</a> : ^4.17.1</li>
<li><a href="/questions/tagged/next" class="post-tag" title="show questions tagged 'next'" rel="tag">next</a> : ^10.0.5</li>
<li><a href="/questions/tagged/socket.io" class="post-tag" title="show questions tagged 'socket.io'" rel="tag">socket.io</a> : ^2.4.0</li>
<li><a href="/questions/tagged/socket.io-client" class="post-tag" title="show questions tagged 'socket.io-client'" rel="tag">socket.io-client</a> : ^2.4.0</li>
<li><a href="/questions/tagged/socket.io-redis" class="post-tag" title="show questions tagged 'socket.io-redis'" rel="tag">socket.io-redis</a> : ^5.4.2</li>
</ul>
<p><strong>Server code:</strong><br/></p>
<pre><code>const sticky = require("sticky-session");
const app = require("express")();
const server = require("http").Server(app);
const io = require("socket.io").listen(server);
io.set("transports", ["websocket"]);
const redis = require("socket.io-redis");
const PORT = process.env.PORT || 3000;
const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const nextApp = next({ dev });
const handle = nextApp.getRequestHandler();
const keys = require("./config/keys");
const mongoose = require("mongoose");
const cookieSession = require("cookie-session");
const passport = require("passport");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const sslRedirect = require("heroku-ssl-redirect").default;
io.adapter(redis(keys.REDIS_URL));
const worker = () => {
nextApp
.prepare()
.then(() => {
app.use(cookieParser());
app.use(bodyParser.json());
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey],
})
);
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
// IMPORT MODELS
mongoose.connect(keys.mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = mongoose.connection;
db.once("open", function () {
console.log("MongoDB database connection established successfully");
});
db.on("error", console.error.bind(console, "MongoDB connection error:"));
require("./sockets/index")(io);
require("./routes/api")(app, io);
app.get("*", (req, res) => {
return handle(req, res);
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
};
//sticky.listen() will return false if Master
if (!sticky.listen(server, PORT)) {
} else {
worker();
}
</code></pre>
<p><strong>On the client I simply use:</strong><br/></p>
<pre><code>const socket = io({ transports: ["websocket"] });
</code></pre>
<p><strong>Heroku settings:</strong></p>
<pre><code>heroku features:enable http-session-affinity
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T17:17:25.010",
"Id": "254613",
"Score": "0",
"Tags": [
"node.js",
"session",
"clustering",
"redis",
"socket.io"
],
"Title": "My approach on nextjs cluster with socket.io"
}
|
254613
|
<p>I have written Haskell code to my spec to help me grasp types and syntax, because I am learning.
I hope to generalize it further to accommodate more kinds of equations. I am (perhaps prematurely) worried that repeated usage of <code>delta</code> in multiple places is going to slow down my code, but I don't see how I can avoid it.</p>
<p>I am a bit confused about whether I should use <code>Floating</code> class or just use <code>Float</code> concrete type everywhere.</p>
<p>I appreciate any and all tips.</p>
<p>Here's the expected output</p>
<pre><code>Equation -10.0x^2 +4.0x +1.0 = 0 has following 2 solutions:
0.28708285
-8.708288e-2
</code></pre>
<p>And the code</p>
<pre><code>-- MathPrimer
delta :: Floating a => a -> a -> a -> a
x1 :: Floating a => a -> a -> a -> a
x2 :: Floating a => a -> a -> a -> a
delta a b c = b * b - 4 * a * c
x1 a b c = ( - b - sqrt(delta a b c)) / ( 4 * a * c )
x2 a b c = ( - b + sqrt(delta a b c)) / ( 4 * a * c )
class Algebraic equ where
algebraicForm :: equ -> String
class (ZeroEquation equ) where
solve :: equ -> [Float]
solutionCount :: equ -> Int
data Equation = Quadratic {a :: Float, b :: Float, c :: Float}
deriving (Show, Read, Eq)
instance (ZeroEquation Equation) where
solve (Quadratic a b c) = solutions
where
both = [x1 a b c, x2 a b c]
one = [x1 a b c]
zero = []
solutions = if _delta < 0 then zero else if _delta == 0 then one else both
_delta = (delta a b c)
solutionCount (Quadratic a b c) = count
where
count = if _delta < 0 then 0 else if _delta == 0 then 1 else 2
_delta = (delta a b c)
instance (Algebraic Equation) where
algebraicForm (Quadratic a b c) = show a ++ "x^2 +" ++ show b ++ "x +" ++ show c
showEquation :: Equation -> String
showEquation equ = "Equation " ++ description ++ " = 0 has following " ++ count ++ " solutions:\n" ++ solutions
where
count = show $ solutionCount equ
description = algebraicForm equ
solutions = unlines $ map show $ solve equ
main = do
let equation = Quadratic (-10) 4 1
putStrLn $ showEquation equation
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T21:35:19.763",
"Id": "502144",
"Score": "0",
"body": "Welcome to posting on Code Review (long time lurker, I see!). Just out of interest, since I don't do Haskell myself - does this find only the real roots, or will it find complex roots where they exist?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T21:59:11.260",
"Id": "502147",
"Score": "0",
"body": "only real, but I just have to substitute `sqrt` for a complex one to get complex. But I decided against it because it was no fun when there's only 2 or 0 solutions. I also would have to adjust `Float` and `Floating` to some complex types I don't know yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T22:03:53.443",
"Id": "502149",
"Score": "0",
"body": "Also thank you very much! Code Review can be very helpful with learning I saw so I decided to try it myself @TobySpeight"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T22:04:25.620",
"Id": "502150",
"Score": "1",
"body": "No problem - I'm just taking the opportunity to learn something about Haskell. Micro-review: consider changing the word \"solutions\" to \"solution\" when b² = 4ac. How would you ensure that the message is translatable (remembering that different languages inflect by number very differently)?"
}
] |
[
{
"body": "<p>It's hard to tell if the compiler would be able to eliminate duplicate calls to delta. It may do that, by inlining the <code>x1</code> and <code>x2</code> functions and then eliminating common subexpressions. Personally though, I prefer to do this myself. The following modification is guaranteed to call <code>delta</code> only once:</p>\n<pre><code>solve (Quadratic a b c) = solutions\n where\n both = [x1, x2]\n one = [x1]\n zero = []\n solutions = if _delta < 0 then zero else if _delta == 0 then one else both\n _delta = (delta a b c)\n x1 = ( - b - sqrt _delta) / ( 4 * a * c )\n x2 = ( - b + sqrt _delta) / ( 4 * a * c )\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T23:29:33.120",
"Id": "502284",
"Score": "0",
"body": "That's a fair suggestion. I guess I'll have to resort to benchmarking."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T23:09:06.337",
"Id": "254672",
"ParentId": "254618",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T19:52:20.240",
"Id": "254618",
"Score": "3",
"Tags": [
"beginner",
"haskell"
],
"Title": "Haskell basic typeclass primer (quadratic equations)"
}
|
254618
|
<p>I've written a working and complete proof of concept that shows a spectrograph in Matplotlib. I want to nail down this proof of concept before I continue with development, and I'm not thrilled with the way I've had to hack around using numpy.</p>
<p>The graph shows the spectrum as divided into five harmonics. Each harmonic section is shown centered around a harmonic multiple of the fundamental, with deviation from that center measured in <a href="https://en.wikipedia.org/wiki/Cent_(music)" rel="nofollow noreferrer">cents</a>. The crux of my problem is that these harmonic sections are of variable length. All sections are pulled as slices from a single, flat FFT output array. This output array is currently represented as a global (though that will change when I continue development), and its reference must remain intact and it must not be reallocated: this is necessary due to the way that the FFTW library works. The planner runs on a specific section of memory that must be mutated as needed.</p>
<p>My first approach was to get as close to a jagged array representation as numpy allows, which is <a href="https://numpy.org/doc/stable/reference/maskedarray.generic.html" rel="nofollow noreferrer">masked arrays</a>. I use a masked array for <code>cents</code>, the horizontal axes, so that the <code>linspace</code>, <code>*=</code> and <code>log</code> statements can be fully vectorized over all harmonics. It works, but doesn't seem to benefit me much since the masked array still needs to be sliced in <code>animate</code> before being passed to <code>plot.set_data()</code>. <code>animate</code> is more performance-critical than <code>set_note</code> as I plan for the former to be called for each animation frame, and the latter to only be called on key presses.</p>
<pre><code>from math import sqrt, log
import matplotlib.pyplot as plt
import numpy as np
n_harmonics = 5 # Number of harmonics to display
f_upper = 24_000 # Nyquist frequency
n_fft_out = 32769 # FFT output size for an input of 64k
h_indices = np.arange(1, n_harmonics + 1) # Harmonic indices
coefficients = np.empty(n_harmonics + 1) # Frequency coefficients to find harmonic section bounds
coefficients[0] = n_fft_out/f_upper / sqrt(2)
coefficients[1:] = n_fft_out/f_upper * np.sqrt(h_indices*(h_indices + 1))
# A spectrum that is linear from its lower to upper frequency
# This will eventually receive an actual spectrum
fft_out = np.linspace(0, f_upper, n_fft_out, dtype=np.complex64)
def f_to_fft(f: float) -> int:
return round(f / f_upper * n_fft_out)
def fft_to_f(i: int) -> float:
return i / n_fft_out * f_upper
def set_note(f_tune_exact: float):
"""
will eventually be invoked via keyboard on an irregular basis (once every few seconds)
"""
bounds_flat = np.empty(n_harmonics + 1, dtype=np.uint32)
np.rint(f_tune_exact * coefficients, casting='unsafe', out=bounds_flat)
bounds = np.vstack((bounds_flat[:-1], bounds_flat[1:])).T
sizes = (bounds[:, 1] - bounds[:, 0])[..., np.newaxis]
longest = np.max(sizes)
cents = np.ma.empty((n_harmonics, longest))
cents[:, :] = np.linspace(bounds[:, 0], bounds[:, 0] + longest - 1, longest).T
past_end = np.arange(longest)[np.newaxis, ...] >= sizes
cents[past_end] = np.ma.masked
cents *= (f_upper / f_tune_exact / n_fft_out / h_indices)[..., np.newaxis]
cents = 1_200/log(2) * np.log(cents)
return cents, bounds
def plot():
fig, ax = plt.subplots()
plots = [
ax.plot([], [], label=str(h))[0]
for h in range(1, n_harmonics + 1)
]
ax.set_title('Harmonic spectrogram')
ax.legend(title='Harmonic')
ax.grid()
ax.set_xlim(-600, 600)
ax.set_ylim(0, 3_000)
ax.set_xlabel('Deviation, cents')
ax.set_ylabel('Spectral power')
return plots
def animate():
"""
Will eventually be invoked often, at the framerate of the matplotlib animation.
fft_out needs to remain outside of this scope because FFT routines need to
refer to the same segment of memory without it being reallocated.
"""
for plot, x, (left, right) in zip(plots, cents, bounds):
x = x[:right-left]
y = np.abs(fft_out[left: right])
plot.set_data(x, y)
if __name__ == '__main__':
cents, bounds = set_note(440)
plots = plot()
animate()
plt.show()
</code></pre>
<p>This shows the right thing:</p>
<p><a href="https://i.stack.imgur.com/Aikkj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Aikkj.png" alt="spectrum" /></a></p>
<p>My second attempt is a trade-off: it has less vectorisation, but also a simpler <code>animate</code> that does not need to slice anything, since <code>harmonics</code> is completely stored by-reference:</p>
<pre><code>from math import sqrt, log
import matplotlib.pyplot as plt
import numpy as np
n_harmonics = 5 # Number of harmonics to display
f_upper = 24_000 # Nyquist frequency
n_fft_out = 32769 # FFT output size for an input of 64k
h_indices = np.arange(1, n_harmonics + 1) # Harmonic indices
coefficients = np.empty(n_harmonics + 1) # Frequency coefficients to find harmonic section bounds
coefficients[0] = n_fft_out/f_upper / sqrt(2)
coefficients[1:] = n_fft_out/f_upper * np.sqrt(h_indices*(h_indices + 1))
# A spectrum that is linear from its lower to upper frequency
# This will eventually receive an actual spectrum
fft_out = np.linspace(0, f_upper, n_fft_out, dtype=np.complex64)
def f_to_fft(f: float) -> int:
return round(f / f_upper * n_fft_out)
def fft_to_f(i: int) -> float:
return i / n_fft_out * f_upper
def set_note(f_tune_exact: float):
"""
will eventually be invoked via keyboard on an irregular basis (once every few seconds)
"""
bounds_flat = np.empty(n_harmonics + 1, dtype=np.uint32)
np.rint(f_tune_exact * coefficients, casting='unsafe', out=bounds_flat)
bounds = np.vstack((bounds_flat[:-1], bounds_flat[1:])).T
sizes = (bounds[:, 1] - bounds[:, 0])[..., np.newaxis]
longest = np.max(sizes)
cents = np.linspace(bounds[:, 0], bounds[:, 0] + longest - 1, longest).T
cents *= (f_upper / f_tune_exact / n_fft_out / h_indices)[..., np.newaxis]
cents = 1_200/log(2) * np.log(cents)
cents = [
cent[:size[0]]
for cent, size in zip(cents, sizes)
]
harmonics = [
fft_out[left: right]
for left, right in bounds
]
return cents, harmonics
def plot():
fig, ax = plt.subplots()
plots = [
ax.plot([], [], label=str(h))[0]
for h in range(1, n_harmonics + 1)
]
ax.set_title('Harmonic spectrogram')
ax.legend(title='Harmonic')
ax.grid()
ax.set_xlim(-600, 600)
ax.set_ylim(0, 3_000)
ax.set_xlabel('Deviation, cents')
ax.set_ylabel('Spectral power')
return plots
def animate():
"""
Will eventually be invoked often, at the framerate of the matplotlib animation.
fft_out needs to remain outside of this scope because FFT routines need to
refer to the same segment of memory without it being reallocated.
"""
for plot, x, y in zip(plots, cents, harmonics):
plot.set_data(x, np.abs(y))
if __name__ == '__main__':
cents, harmonics = set_note(440)
plots = plot()
animate()
plt.show()
</code></pre>
<p>My opinion is that the second, mask-less, by-reference, non-vectorised approach to forming <code>harmonics</code> and <code>cents</code> is more reasonable. I'm open to all feedback, but specifically what I'm really looking for is feedback on the benefits and drawbacks to these two approaches; if there is a way to use numpy/matplotlib better; and especially if there's a way to have my cake and eat it too - to have a truly jagged numpy array, which I have not been able to find.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T20:36:26.110",
"Id": "254619",
"Score": "1",
"Tags": [
"python",
"comparative-review",
"numpy",
"matplotlib"
],
"Title": "Spectrograph using array-of-slice-references"
}
|
254619
|
<p>Just looking for some feedback and constructive criticism. This is the second script I ever made. Just recently started learning the basics. Anyway just wanted to post the script and see if maybe I can get some input on where I can maybe do things better.</p>
<p>The script is for extracting the compressed file types you run into the most on Linux. I added the option to extract to a directory of the user's choosing and not just keep it limited to only the working directory.</p>
<p>I feel like I have too many <code>if</code>/<code>then</code> statements and they can somehow be better but I'm not sure. And not sure if I Implemented the exits the right way. Some of you are probably gonna cringe when you see this lol! Anyway if you can help thanks.</p>
<pre><code>#!/bin/bash
error() {
echo "For help, type: nzip -h"
}
usage() {
echo "Usage: nzip [FILE]..."
echo "By default file(s) will be extracted to the working directory."
echo
echo "OPTIONS.."
echo
echo "-d, --directory, eg. nzip [file] [-d] [directory]"
echo
echo
}
if [ $# -eq 0 ]
then
error >&2
exit 1
fi
if [ $# -eq 1 ]
then
case $1 in
-h) usage
exit 0
;;
*.7z) 7z e "$1"
;;
*.tar.bz2) tar xjvf "$1"
;;
*.tar.gz) tar xzvf "$1"
;;
*.rar) unrar e "$1"
;;
*.tar) tar xvf "$1"
;;
*.bz2) bunzip2 "$1"
;;
*.tbz) tar xjvf "$1"
;;
*.gz) gunzip "$1"
;;
*.tgz) tar xzvf "$1"
;;
*.jar) unzip "$1"
;;
*.xz) tar xvf "$1"
;;
*.zip) unzip "$1"
;;
*.Z) uncompress "$1"
;;
*) echo "No extraction option for $1" >&2
exit 1
esac
exit 0
fi
if [ $# -eq 3 ] && [ "$2" = "-d" ]
then
case $1 in
*.7z) 7z e "$1" -o"$3"
;;
*.tar.bz2) tar xjvf "$1" -C "$3"
;;
*.tar.gz) tar xzvf "$1" -C "$3"
;;
*.rar) unrar e "$1" "$3"
;;
*.tar) tar xvf "$1" -C "$3"
;;
*.bz2) bunzip2 "$1" -c > "$3"
;;
*.tbz) tar xjvf "$1" -C "$3"
;;
*.gz) gunzip "$1" -c > "$3"
;;
*.tgz) tar xzvf "$1" -C "$3"
;;
*.jar) unzip "$1" -d "$3"
;;
*.xz) tar xvf "$1" -C "$3"
;;
*.zip) unzip "$1" -d "$3"
;;
*.Z) uncompress "$1" -c > "$3"
;;
*) echo "No extraction option for $1" >&2
exit 1
esac
else
error >&2
exit 1
fi
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T22:49:51.360",
"Id": "502154",
"Score": "1",
"body": "Make sure you use the https://shellcheck.net tool to validate your syntax."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T03:07:18.860",
"Id": "502168",
"Score": "1",
"body": "Taking a second look at this, it's admirable quality for (as you say) as scripting newbie. The only real oops I see is that your help says that multiple input files are allowed, but this code only handles one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:29:23.887",
"Id": "502244",
"Score": "0",
"body": "I use shellcheck.net constantly, its great. And I see what you mean going to change that. Thanks!"
}
] |
[
{
"body": "<p>I'm not sure why we have <code>#!/bin/bash</code> - it looks like plain, portable <code>#!/bin/sh</code> would be fine here.</p>\n<p>Things I immediately like include the good error handling, using <code>&2</code> for error messages and exiting non-zero.</p>\n<p>All the <code>tar</code> commands can be combined, as <code>tar</code> is able (with <code>-a</code>) to automatically identify any compression scheme it handles.</p>\n<p>As there's no need to continue once the archiver is run, we can replace the shell process using <code>exec</code>. E.g.</p>\n<pre><code>case $1 in\n *.7z) exec 7z e "$1"\n ;;\n</code></pre>\n<p>Don't do that if we extend the program to process multiple input files, though (see below).</p>\n<p>If we take the usual convention of flags first, then it makes it easier when we decide we want to handle more options (e.g. <code>-v</code>, so we can default to quiet operation). And we can combine the two big <code>case</code> constructs by always passing a directory, but defaulting to the current working directory:</p>\n<pre><code>destination=.\n\ndie() {\n printf '%s\\n' "$@" >&2\n exit 1\n}\n\ndo_extract() {\n case $1 in\n *.tar.*|*.t[bg]z) tar xaf "$1" -C "$destination"\n ;;\n *.jar|*.zip) unzip "$1" -d "$destination"\n ;;\n # ...\n esac\n}\n\nwhile [ $# -ge 1 ]\ndo\n case "$1" in\n -d)\n [ $# -gt 1 ] || die "Usage: $0 [-d directory] file..."\n destination=$2\n shift 2\n ;;\n -*)\n die "Unrecognised option: $1"\n *)\n do_extract "$1"\n shift\n esac\ndone\n</code></pre>\n<p>Be careful with <code>echo</code>:</p>\n<blockquote>\n<pre><code>usage() {\n echo "Usage: nzip [FILE]..."\n echo "By default file(s) will be extracted to the working directory."\n echo\n echo "OPTIONS.."\n echo\n echo "-d, --directory, eg. nzip [file] [-d] [directory]"\n echo\n echo\n}\n</code></pre>\n</blockquote>\n<p>Other (e.g. future) versions of <code>echo</code> may treat that <code>-d</code> as indicating a flag.</p>\n<p>I'd be inclined to use a here-file for this:</p>\n<pre><code>usage() {\n cat <<'END'\nUsage: nzip [FILE] [-d DESTINATION]\nBy default file(s) will be extracted to the working directory.\n\nOPTIONS:\n -d destination\nEND\n}\n</code></pre>\n<p>Note that I've changed the usage line, because we support only one file, and <code>-d</code> and the destination argument go together (and it's misleading to call it "directory" when it may be a non-directory name if we're unpacking a single file).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T16:15:50.057",
"Id": "502224",
"Score": "0",
"body": "thanks for all that great information. I implemented most of what you suggested. at least the parts I understood. I still have a lot to learn. i know \"-eq\" is equal to, does \"-ge\" mean greater or equal to? and \"-gt\" is just greater than? also not sure what shift does. and why not just set destination=$2 from the start."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:10:44.170",
"Id": "502235",
"Score": "1",
"body": "Yes, you've guessed those operators correctly. `man test` or `man [` for the full details (though Bash has its own `test` built-in, so `man bash-builtins` is probably what you want; that's also where to find a description of `shift`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:18:18.713",
"Id": "502237",
"Score": "1",
"body": "The `while [ $# -ge 1 ]` (or simply `while [ \"$@\" ]`) loop with `shift` is a fairly common idiom for reading option arguments in shell scripts; expect to see that fairly frequently when working with shell."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T22:01:20.307",
"Id": "254625",
"ParentId": "254620",
"Score": "5"
}
},
{
"body": "<p>Building on <a href=\"https://codereview.stackexchange.com/a/254625/3219\">Toby's excellent answer</a>, this offers 2 alternate ways to parse the options.</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>#!/usr/bin/env bash\n\nreadonly PROGRAM=${0##*/}\n\nreadonly USAGE=$(cat <<END_USAGE\nUsage: $PROGRAM [FILE]...\n\nBy default file(s) will be extracted to the working directory.\n\nOPTIONS\n\n-d, --directory, eg. nzip [file] [-d directory]\n\nEND_USAGE\n)\n\ndie() { printf '%s\\n' "$*" >&2; exit 1; }\nerror() { die "For help, type: $PROGRAM -h"; }\nusage() { echo "$USAGE"; exit 0; }\n\nextract() {\n local file=$1 dest=$2\n echo "various ways to decompress $file to $dest"\n}\n\n# default destination is the current directory\ndestination="."\n\n\n############################################################\n# parse options\n</code></pre>\n<p>Now, we can use the bash builtin <code>getopts</code> to parse the options, but it only allows for short options</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>while getopts :hd: opt; do\n case $opt in\n h) usage ;;\n d) destination=$OPTARG ;;\n :) die "Missing option for -$OPTARG" ;;\n *) error ;;\n esac\ndone\nshift $((OPTIND - 1))\n</code></pre>\n<p>Or use the external <code>getopt</code> tool to allow long options too</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>tmp=$( getopt -o 'hd:' --long 'help,directory:' -n "$PROGRAM" -- "$@" ) || exit $?\neval set -- "$tmp"\n\nwhile true; do\n case $1 in\n '-h'|'--help') usage ;;\n '-d'|'--directory') \n destination=$2\n shift 2\n ;;\n '--')\n shift\n break\n ;;\n *) die 'Internal error' ;;\n esac\ndone\n</code></pre>\n<p>And then:</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>############################################################\n# after option parsing\n\n(( $# > 0 )) || usage\n\nfor file in "$@"; do\n extract "$file" "$destination"\ndone\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T22:49:19.620",
"Id": "254627",
"ParentId": "254620",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "254625",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T20:38:05.667",
"Id": "254620",
"Score": "4",
"Tags": [
"beginner",
"bash"
],
"Title": "Script to unpack archives of various kinds"
}
|
254620
|
<h1>Background</h1>
<p>The function computes moving arrange and offers some other minor widgets like possibility to return data frame in original order or automatically derive variable name for the moving average. In majority of actual use cases similar results could be easily achieved using combinations of usual suspects like <a href="https://dplyr.tidyverse.org/reference/across.html" rel="nofollow noreferrer"><code>across</code></a>, <code>mutate</code> and so on. However, I was interested in an implementation that:</p>
<ol>
<li>Is fairly generic and easily applicable to multiple data sets</li>
<li>Makes use of fairy standard dplyr verbs for easier usage in <code>sparklyr</code>, especially when working on old Spark backends that do not support <code>apply</code>. The function proved convoluted so I feel that I've failed in that goal, but that's a side point.</li>
</ol>
<h2>Sought feedback</h2>
<ol>
<li><p>Better approach to generating multiple <code>lag</code> calls. Through string manipulation I arrive at <code>lag(var, n)...</code> and then do:</p>
<pre><code>dplyr::mutate(data_sorted,"{{val}}_mavg" := !!rlang::parse_expr(lag_call))
</code></pre>
<p>This feels naff and I would be grateful for suggestions on improvement.</p>
</li>
<li><p>Is there an elegant way of forcing evaluation on the left hand side of <code>:=</code>. Currently I'm doing:</p>
<pre><code>if (res_val != "{{val}}_mavg") {
data_avg <- dplyr::rename(res_val = "{{val}}_mavg")
}
</code></pre>
<p>This works but one-liner like evaluating <code>res_val</code> <em>and then</em> doing potentially necessary magic with <a href="https://dplyr.tidyverse.org/articles/programming.html" rel="nofollow noreferrer">curly-curly</a> would be nice.</p>
</li>
<li><p>Any other observations</p>
</li>
</ol>
<hr />
<h1>Function</h1>
<pre><code>#' Add Moving Average for an Arbitrary Number of Intervals
#'
#' The functions adds moving average for an arbitrary number of intervals. The
#' data can be returned sorted or according to the original order.
#'
#' @details The function can be used independently or within dplyr pipeline.
#'
#' @param .data A tibble or data frame.
#' @param sort_cols Columns used for sorting passed in a manner consistent with
#' \code{\link[dplyr]{arrange}}
#' @param val Column used to calculate moving average passed as bare column
#' name or a character string.
#' @param res_val Resulting moving average, defaults to name of \code{val}
#' suffixed with \code{_mavg}.
#' @param restore_order A logical, defaults to \code{FALSE} if \code{TRUE} it
#' will restore original data order.
#'
#' @return A tibble with appended moving average.
#' @export
#'
#' @examples
#' add_moving_average(mtcars, sort_cols = c("mpg", "cyl"), val = hp, intervals = 2)
add_moving_average <-
function(.data,
sort_cols,
val,
intervals = 2,
res_val = "{{val}}_mavg",
restore_order = FALSE) {
unique_id_name <- tail(make.unique(c(colnames(.data), "ID")), 1)
data_w_index <- dplyr::mutate(.data, {{unique_id_name}} := dplyr::row_number())
index_col_name <- tail(names(data_w_index), 1)
# Create desired number of calls to get moving average calculation
lag_calls <- paste0("lag(", rlang::as_string(rlang::ensym(val)), ", ", 1:intervals, ")")
lag_call <- paste(lag_calls, collapse = " + ")
lag_call <- paste0("(", lag_call, ") / ", intervals)
data_sorted <- dplyr::arrange(data_w_index, dplyr::across(sort_cols))
data_avg <- dplyr::mutate(data_sorted,"{{val}}_mavg" := !!rlang::parse_expr(lag_call))
if (res_val != "{{val}}_mavg") {
data_avg <- dplyr::rename(data_avg, res_val = "{{val}}_mavg")
}
if (restore_order) {
data_avg <- dplyr::arrange(data_avg, !!rlang::sym(index_col_name))
}
data_avg <- dplyr::select(data_avg, -dplyr::last_col(1))
data_avg
}
</code></pre>
<h2>Tests</h2>
<pre><code>add_moving_average(.data = mtcars, sort_cols = c("am", "gear"), val = disp, intervals = 3)
add_moving_average(.data = mtcars, sort_cols = c("am", "gear"), val = disp, intervals = 3)
add_moving_average(.data = mtcars, sort_cols = c("am", "gear"), val = disp, intervals = 3,
restore_order = TRUE)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T20:58:44.883",
"Id": "254621",
"Score": "1",
"Tags": [
"functional-programming",
"r"
],
"Title": "Dplyr friendly function for computing moving average"
}
|
254621
|
<p>This is my first ever created program I've made. It's not very good but I'm pretty proud of it.</p>
<p>If you have any suggestions I could add into the calculator I would gladly do that.</p>
<pre class="lang-csharp prettyprint-override"><code>using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace CSharp_Shell
{
public static class Program
{
public static void Main()
{
try
{
Console.WriteLine("--------------------------------");
Console.WriteLine("Operators:");
Console.WriteLine("+ = Add");
Console.WriteLine("- = Subtract");
Console.WriteLine("* = Multiply");
Console.WriteLine("/ = Divide");
Console.WriteLine("^ = Power");
Console.WriteLine("--------------------------------");
Console.Write("Enter operator: ");
string op = (Console.ReadLine());
Console.Write("Enter First Number: ");
double num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Second Number: ");
double num2 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("--------------------------------");
if (op == "+")
{
Console.WriteLine(num1 + num2);
Console.WriteLine("--------------------------------");
}
else if (op == "-")
{
Console.WriteLine(num1 - num2);
Console.WriteLine("--------------------------------");
}
else if (op == "/")
{
Console.WriteLine(num1 / num2);
Console.WriteLine("--------------------------------");
}
else if (op == "*")
{
Console.WriteLine(num1 * num2);
Console.WriteLine("--------------------------------");
}
else if (op == "^")
{
double value1 = Math.Pow(num1, num2);
Console.WriteLine("{0}", value1);
Console.WriteLine("--------------------------------");
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("error");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("--------------------------------");
}
}
catch
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("--------------------------------");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("error");
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("--------------------------------");
}
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("Press any key to stop the program");
Console.ReadKey();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T07:18:57.437",
"Id": "502184",
"Score": "1",
"body": "A couple of days ago a quite similar question had been posted. Please check [my answer](https://codereview.stackexchange.com/questions/254363/calculator-program-improvements/254374#254374), most of the recommendations can be applied here as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T14:59:32.343",
"Id": "502216",
"Score": "1",
"body": "@Chocolate it is not a duplicate. Refer to answer to [this meta post](https://codereview.meta.stackexchange.com/q/8/120114)."
}
] |
[
{
"body": "<h1>Dividing work</h1>\n<p>The job of your calculator is to take some input, process it, and show the output to the user. If you split those 3 steps into functions of their own you add a lot of clarity to the person who reads your code. Moreover, you can re-use those functions if you want to perform the same step again.</p>\n<p>Something along the lines of</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var numbers = getNumbersInput();\nvar op = getOperatorInput();\n\nvar result = calcResult(op, numbers.Item1, number2.Item2);\nConsole.WriteLine($"The result is {result}."); \n</code></pre>\n<p>Here it is clear the job of <code>getNumbersInput()</code> is to get the two numbers and return them. <code>getOperatorInput()</code> will return the operator the user wants to use and <code>calcResult()</code> will use the input, process it, and return you the result.</p>\n<hr />\n<h1>Don't wrap your whole program in a <code>try/catch</code></h1>\n<p>There are only a few areas where your program can run into an exception. Such as the point where you are taking the integer input from the user. Upon invalid input, you can use <code>catch</code> to provide specific errors to guide the user on what he did wrong. Just 2 white lines with the word <code>error</code> doesn't tell you what happened does it?</p>\n<p>Instead, use <code>try/catch</code> in specific areas with proper error messages such as <code>Invalid number input: Please enter a number</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T06:52:20.047",
"Id": "254637",
"ParentId": "254622",
"Score": "3"
}
},
{
"body": "<p>Over all, if this is your first time coding, you've really done a stellar job. I'm having a hard time believing this was a first attempt without replicating someone else's code, just because of how cleanly you've approached it. Very well done.</p>\n<p>The below suggestions are more <em>further improvements</em> than they are corrections on what you were doing. Some of the things I suggest may not make full sense now, but are good habits to breed early on, because when you start working on more complex applications, you'll significantly benefit from not having to learn every mistake the hard way.</p>\n<hr />\n<p><strong>Avoid repetition</strong></p>\n<p>How often do you see this code:</p>\n<pre><code>Console.ForegroundColor = /* some color */;\nConsole.WriteLine(/* some message */);\n</code></pre>\n<p>The answer is <strong>a lot</strong>. So to save yourself some repeated code, abstract it into a method:</p>\n<pre><code>public void WriteMessage(string message, ConsoleColor color = ConsoleColor.White)\n{\n Console.ForegroundColor = color;\n Console.WriteLine(message);\n}\n</code></pre>\n<p>It seems like a little thing, but it effectively halves amount of lines (revolving around printing logic) in your main method, since you can now just do:</p>\n<pre><code>WriteMessage("error", ConsoleColor.Red);\n</code></pre>\n<p>Note that I also made the color an optional parameter, so it can be omitted when no special color is needed:</p>\n<pre><code>WriteMessage("a message without special color");\n</code></pre>\n<p><strong>Syntax improvements</strong></p>\n<p>This is just a little thing, but notice how every condition ends with drawing a line:</p>\n<pre><code>if (op == "+")\n{\n Console.WriteLine(num1 + num2);\n Console.WriteLine("--------------------------------");\n}\nelse if (op == "-")\n{\n Console.WriteLine(num1 - num2);\n Console.WriteLine("--------------------------------");\n}\n// and so on...\n</code></pre>\n<p>If all of them end on the same instruction, it's easier to just put that instruction behind the if/else:</p>\n<pre><code>if (op == "+")\n{\n Console.WriteLine(num1 + num2);\n}\nelse if (op == "-")\n{\n Console.WriteLine(num1 - num2);\n}\n// and so on... \n\nConsole.WriteLine("--------------------------------"); \n</code></pre>\n<p>But you can go further. The same applies to printing the result. So you can also move that outside of the chain:</p>\n<pre><code>double result = 0;\n\nif (op == "+")\n{\n result = num1 + num2;\n}\nelse if (op == "-")\n{\n result = num1 - num2;\n}\n// and so on... \n\nConsole.WriteLine(result); \nConsole.WriteLine("--------------------------------"); \n</code></pre>\n<p><strong>Syntax improvements</strong></p>\n<p>You should avoid <code>if else</code> chains where you keep checking if the same variable matches a given value. That's precisely what a <code>switch</code> was made for:</p>\n<pre><code>switch(op)\n{\n case "+":\n Console.WriteLine(num1 + num2);\n break;\n case "-":\n Console.WriteLine(num1 - num2);\n break;\n case "*":\n Console.WriteLine(num1 * num2);\n break;\n // and so on...\n} \n</code></pre>\n<p><strong>Break it up</strong></p>\n<p>The code you wrote is relatively neat for a beginner program. Good indentation, reasonable whitespace separation between lines.</p>\n<p>But the next step is breaking your method down into smaller steps. If I were to sum up what this code does, I'd list it as follows:</p>\n<ul>\n<li>Takes in a number (twice)</li>\n<li>Takes in a mathematical operation</li>\n<li>Writes messages to the console, sometimes in color.</li>\n<li>Performs the selected operation on the selected numbers</li>\n</ul>\n<p>You could add a lot more bullet points here if you wanted, e.g whether you consider drawing a horizontal separator as a different task from writing a message to the console. I'm sticking with these four as it's a basic example.</p>\n<p>These four bullet points are a great (but not complete) guideline to how you need to break down your application. Anything you consider a separate task, is generally going to want to be in a method on its own. So in this case you'd be looking at methods like:</p>\n<ul>\n<li><code>double GetNumber()</code></li>\n<li><code>char GetOperation()</code> - I'd consider using a custom enum here instead of a character, but let's keep it simple for now.</li>\n<li><code>void WriteMessage(string message, ConsoleColor color = ConsoleColor.White)</code> - see previous point section</li>\n<li>Separate operator methods:\n<ul>\n<li><code>double Add(double a, double b)</code></li>\n<li><code>double Subtract(double a, double b)</code></li>\n<li><code>double Multiply(double a, double b)</code></li>\n<li><code>double Divide(double a, double b)</code></li>\n<li><code>double Power(double a, double b)</code> - This mirrors <code>Math.Pow</code> and you could technically skip your own method and use <code>Math.Pow</code> directly. However, due to abstraction considerations, it's good practice to still define your own method. This is maybe beyond your current skill level, but the idea behind it is that if you suppose that you change your calculation logic in the future, it's easier to rewrite the content of your <code>Power</code> method once, than it is to go hunt for all references to <code>Math.Pow</code> and substitute them all individually.</li>\n</ul>\n</li>\n</ul>\n<p>There's definitely still room for improvement, but you're still a beginner and this is a good first step. Try to write the code in your <code>Main</code> method in a way that it relies on these methods I just listed, instead of having the <code>Main</code> menu do all the heavy lifting by itself.</p>\n<p>Think of it this way: when you stop being a cook and instead become a chef (= better code), then you're no longer doing the small jobs yourself, e.g. peeling the potatoes and washing the dishes. Tasks get delegated. Chefs (the <code>Main</code> method) rely on the small things being done by others (the submethods).</p>\n<p><strong>Refactoring</strong></p>\n<p>I noticed this:</p>\n<pre><code>Console.WriteLine("{0}", value1);\n</code></pre>\n<p>It's needlessly complex. Just do:</p>\n<pre><code>Console.WriteLine(value1);\n</code></pre>\n<p>I suspect that this is a refactoring remnant. It used to do more than just print <code>value1</code>, but over time you changed the code, and never steered away from using the <code>String.Format</code> approach.</p>\n<p>That's completely normal, but this is precisely why developers should always revisit code when it's "finished", to see if there are some remnants of past attempts that can be cleaned up or refactored into something better.</p>\n<p><strong>A better user experience</strong></p>\n<p>It helps to sometimes think like a user instead of like a developer. When adding 1 and 2 together, how do we write things?</p>\n<ul>\n<li><code>+ 1 2</code></li>\n<li><code>1 + 2</code></li>\n<li><code>1 2 +</code></li>\n</ul>\n<p>I hope you'll agree that the second bullet point is vastly preferred. Note that the first bullet point also exists (it's called <a href=\"https://en.wikipedia.org/wiki/Polish_notation\" rel=\"noreferrer\">Polish notation</a>), but unless you have reason to believe that your users predominantly use Polish notation, the second bullet point is how users think.</p>\n<p>But when you ask for user input, you are asking for <code>+ 1 2</code>:</p>\n<pre><code>Console.Write("Enter operator: ");\nstring op = (Console.ReadLine());\n \nConsole.Write("Enter First Number: ");\ndouble num1 = Convert.ToDouble(Console.ReadLine());\n \nConsole.Write("Enter Second Number: ");\ndouble num2 = Convert.ToDouble(Console.ReadLine()); \n</code></pre>\n<p>That doesn't match with how users think. It's a very simple improvement to just change the order of your code. It doesn't change how your code works, but it does improve the user experience.</p>\n<p><strong>An even better user experience</strong></p>\n<p>This is not as simple, but as a next challenge, you could see if you could move away from users having to input separate values and having to press enter inbetween.</p>\n<p>See if you can figure out how to let users input the whole formula, e.g. <code>"1+2"</code> and take it from there. Or, alternatively, read every key the user presses and dynamically figure out what they mean.</p>\n<p>If you think about a real-world calculator, it works without needing to press enter inbetween its data input. So try and make yours similar. It's a great user experience improvement, and a good exercise for someone who's new to coding.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T13:03:02.203",
"Id": "502209",
"Score": "1",
"body": "Thank you very much! This helped a lot, I will try to improve the user input and the UI, and hopefully make the code more simple to read. I was struggling with the Power so I looked up a example of it, but everything else is made by me. I've watched an 4 hour video of how to program, but I think the way to learn more is just to do more programming and improving the code. Again thank you very much for this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T23:36:24.720",
"Id": "502285",
"Score": "0",
"body": "@Sipuli saying thanks is not enough on Stack Exchange and not a mandatory even if you thankful person. The best way to say thanks is marking the answer as accepted instead. Checkbox is to the left of the answer's text."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T11:51:01.190",
"Id": "254648",
"ParentId": "254622",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T21:39:22.147",
"Id": "254622",
"Score": "3",
"Tags": [
"c#",
"beginner",
"calculator"
],
"Title": "My first ever calculator C#"
}
|
254622
|
<p>I have written a program that takes the original file (the script of 'the bee movie') and does a word count, a unique word count and replaces some of the words. This is really just a rushed version, so if there are any errors or ways of fixing/making the code more efficient, please let me know.</p>
<p>Link to the script: <a href="https://github.com/esker-luminous/Bee-Movie-Knock-off/blob/main/script.py" rel="noreferrer">https://github.com/esker-luminous/Bee-Movie-Knock-off/blob/main/script.py</a> - it is a very large file.</p>
<p>Code:</p>
<pre><code>file = open('script.py', 'r')
words = []
punctuation = '1234567890!@#$%^&*()_-+=-/*{}[];:\'"\<>~`|?'
for line in file:
line = line.lower()
for char in punctuation:
line = line.replace(char, '')
words += line.split()
print(len(words))
print(len(set(words)))
file.seek(0)
text = file.read()
print(text)
file.close()
word_replacement ={'bee': 'turtle', 'hive': 'cow', 'flower': 'algae', 'bees': 'turtle', 'flowers' : 'algae'}
for wor_repl in word_replacement.keys():
text = text.replace(wor_repl, word_replacement[wor_repl])
file = open('knock off.py', 'w')
file.write(text)
file.close()
</code></pre>
|
[] |
[
{
"body": "<p>For the part where you first read the file, you could write it like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import collections\nimport re\n\nfile = open('bee_movie.txt', 'r')\n\ntext = ""\nwords = collections.Counter()\npunctuation = '1234567890!@#$%^&*()_-+=-/*{}[];:\\'"\\\\<>~`|?'\nall_upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"\nall_lower = "abcdefghijklmnopqrstuvwxyz"\ntranslation = str.maketrans(all_upper, all_lower, punctuation)\n\nfor line in file:\n text += line # concatenating like this is optimized in python 3\n words.update(line.translate(translation).split())\n\nprint(sum(words.values()))\nprint(len(words))\nfile.close()\n</code></pre>\n<p>For the part where you’re replacing words, it would be faster if you used re.sub. When you use text.replace, it needs to remake the entire script every time it’s used.</p>\n<p>Also you should save the text files as .txt files, they don’t need the .py extension.</p>\n<p>Btw you can import string and use string.ascii_uppercase, string.ascii_lowercase, and string.punctuation if you don’t want to type out all the characters.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T16:02:45.410",
"Id": "502221",
"Score": "1",
"body": "@Peilonrayz thank you for your input!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T16:03:12.837",
"Id": "502222",
"Score": "1",
"body": "@my_first_c_program thank you so much for letting me know! appreciate it :))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T16:05:57.177",
"Id": "502223",
"Score": "1",
"body": "Could you source \"concatenating like this is optimized in python 3\" last I heard it was a CPython implementation detail, but I couldn't find anything about it when I looked for it last."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T19:23:51.980",
"Id": "502265",
"Score": "0",
"body": "https://web.archive.org/web/20190715231220/https://blog.mclemon.io/python-efficient-string-concatenation-in-python-2016-edition"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T19:35:30.653",
"Id": "502267",
"Score": "1",
"body": "Please be careful about conflating CPython and Python. That post only talks about CPython."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T20:14:45.577",
"Id": "502269",
"Score": "0",
"body": "I will, thanks. Because I’ve also read that in pypy it isn’t the same, so it isn’t the same on all implementations. https://blog.ganssle.io/articles/2019/11/string-concat.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T22:13:22.437",
"Id": "502281",
"Score": "2",
"body": "`maketrans` was interesting for me to learn about; I'd never encountered it before. On the whole I actually like it better than using a regular expression for this application."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T22:43:28.050",
"Id": "502282",
"Score": "0",
"body": "You have to use re.sub for the word replacement part because translate only looks for single characters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T23:44:02.813",
"Id": "502286",
"Score": "1",
"body": "There's not really a point to using `re.sub` for word replacement, since regular expressions can't represent a one-to-one mapping with many potential outputs, only one. Might as well use basic `replace()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T00:08:02.140",
"Id": "502287",
"Score": "0",
"body": "You can give re.sub a function as its second argument which takes the match object as an argument. You can use that as a way to replace with different strings depending on the match."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T00:06:06.687",
"Id": "254631",
"ParentId": "254626",
"Score": "3"
}
},
{
"body": "<blockquote>\n<p>it is a very large file</p>\n</blockquote>\n<p>Perhaps if you're running on a microcontroller. Otherwise, 52kB is <em>not</em> considered large, and can comfortably fit in memory many thousands of times over.</p>\n<p>Consider the following adjustments:</p>\n<ul>\n<li>Do not iterate over lines, particularly since your input file has a weird format where most sentences are already broken up into many separate lines this is not efficient. Just read the entire thing into memory.</li>\n<li>Tell the user the meaning of the two lengths you're outputting.</li>\n<li>Avoid explicit <code>close</code>, and use a <code>with</code> context manager instead.</li>\n<li>Do not re-read your file; just hold onto an unmodified version of its contents in memory.</li>\n<li>Do not call <code>keys</code>; instead call <code>items</code> which gives you both the key and value.</li>\n<li>Avoid looping over every single punctuation character. Instead, use <code>str.transate</code> to remove every match in one pass.</li>\n</ul>\n<p>Suggested:</p>\n<pre><code>from string import ascii_lowercase, ascii_uppercase\n\nwith open('bee-movie.txt') as f:\n text = f.read()\n\ntrans = str.maketrans(ascii_uppercase, ascii_lowercase, r'1234567890!@#$%^&*()_-+=-/*{}[];:\\'"\\<>~`|?')\nno_punc_text = str.translate(text, trans)\n\nwords = no_punc_text.split()\nprint('Total words:', len(words))\nprint('Total unique words:', len(set(words)))\n\nword_replacement = {'bee': 'turtle', 'hive': 'cow', 'flower': 'algae',\n 'bees': 'turtles', 'flowers': 'algae'}\nfor source, dest in word_replacement.items():\n text = text.replace(source, dest)\n\nwith open('turtle-movie.txt', 'w') as f:\n f.write(text)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T22:02:57.100",
"Id": "502280",
"Score": "1",
"body": "thank you so much for this! appreciate it "
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T19:59:49.977",
"Id": "254664",
"ParentId": "254626",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T22:39:01.650",
"Id": "254626",
"Score": "5",
"Tags": [
"python"
],
"Title": "A Bee Movie Knock-off"
}
|
254626
|
<p>I have 2 files</p>
<p>wholesaler_a.csv</p>
<pre><code>id;ean;manufacturer;product;description;packaging product;foo;packaging unit;amount per unit;items on stock (availability);warehouse
12345600001;23880602029774;Drinks Corp.;Soda Drink, 12 * 1,0l;Lorem ipsum usu amet dicat nullam ea;case 12;bar;bottle;1.0l;123;north
</code></pre>
<p>and
wholesaler_b.json</p>
<pre><code>{
"data": [
{
"PRODUCT_IDENTIFIER": "12345600001",
"EAN_CODE_GTIN": "24880602029766",
"BRAND": "Drinks Corp.",
"NAME": "Soda Drink, 12x 1L",
"PACKAGE": "case",
"ADDITIONAL_INFO": "",
"VESSEL": "bottle",
"LITERS_PER_BOTTLE": "1",
"BOTTLE_AMOUNT": "12"
}
]
}
</code></pre>
<p>The goal is to convert them to the following JSON format</p>
<pre><code>{
"id": "",
"gtin": "",
"manufacturer": "",
"name": "",
"packaging": "",
"baseProductPackaging": "",
"baseProductUnit": "",
"baseProductAmount": "",
"baseProductQuantity": ""
}
</code></pre>
<p>Here is my implementation:</p>
<pre><code><?php
namespace Egy\Test;
abstract class AbstractProductAdapter implements ProductAdapterInterface
{
protected $data;
public function getMappedKeys(): array
{
return [
$this->getId() => DataAdapter::FIELD_ID,
$this->getGtin() => DataAdapter::FIELD_GTIN,
$this->getManufacture() => DataAdapter::FIELD_MANUFACTURE,
$this->getName() => DataAdapter::FIELD_NAME,
$this->getPackaging() => DataAdapter::FIELD_PACKAGING,
$this->getBaseProductPackaging() => DataAdapter::FIELD_BASE_PRODUCT_PACKAGING,
$this->getBaseProductUnit() => DataAdapter::FIELD_BASE_PRODUCT_UNIT,
$this->getBaseProductAmount() => DataAdapter::FIELD_BASE_PRODUCT_AMOUNT,
$this->getBaseProductQuantity() => DataAdapter::FIELD_BASE_PRODUCT_QUANTITY
];
}
public function __construct(DataProvider $dataProvider)
{
$this->data = $dataProvider->getProducts();
}
public function mapData(): array
{
$mappedData = [];
foreach ($this->data['data'] as $item) {
$mappedData[] = array_combine(array_merge($item, $this->getMappedKeys()), $item);
}
return $mappedData;
}
}
</code></pre>
<pre><code><?php
namespace Egy\Test;
interface DataProvider
{
public function getProducts();
}
</code></pre>
<pre><code><?php
namespace Egy\Test;
class CsvData implements DataProvider
{
protected $file;
public function __construct(string $file)
{
$this->file = $file;
}
public function getProducts(): array
{
$rows = array_map(function ($value) {
return str_getcsv($value, ";");
},
file($this->file)
);
$header = array_shift($rows);
$data = [];
foreach ($rows as $row) {
$data['data'][] = array_combine($header, $row);
}
return $data;
}
}
</code></pre>
<pre><code><?php
namespace Egy\Test;
class CsvProductAdapter extends AbstractProductAdapter
{
const FIELD_ID = 'id';
const FIELD_GTIN = 'ean';
const FIELD_MANUFACTURE = 'manufacturer';
const FIELD_NAME = 'product';
const FIELD_PACKAGING = 'packaging product';
const FIELD_BASE_PRODUCT_PACKAGING = 'packaging unit';
const FIELD_BASE_PRODUCT_UNIT = 'amount per unit';
const FIELD_BASE_PRODUCT_AMOUNT = 'items on stock (availability)';
const FIELD_BASE_PRODUCT_QUANTITY = 'warehouse';
public function getId(): string
{
return self::FIELD_ID;
}
public function getGtin(): string
{
return self::FIELD_GTIN;
}
public function getManufacture(): string
{
return self::FIELD_MANUFACTURE;
}
public function getName(): string
{
return self::FIELD_NAME;
}
public function getPackaging(): string
{
return self::FIELD_PACKAGING;
}
public function getBaseProductPackaging(): string
{
return self::FIELD_BASE_PRODUCT_PACKAGING;
}
public function getBaseProductUnit(): string
{
return self::FIELD_BASE_PRODUCT_UNIT;
}
public function getBaseProductAmount(): string
{
return self::FIELD_BASE_PRODUCT_AMOUNT;
}
public function getBaseProductQuantity(): string
{
return self::FIELD_BASE_PRODUCT_QUANTITY;
}
}
</code></pre>
<p>And same implementation for JSON format</p>
<p>Could you please review my code</p>
|
[] |
[
{
"body": "<p>I recommend fewer loops in CsvData's <code>getProducts()</code></p>\n<pre><code>public function getProducts(): array\n{\n $lines = file($this->file);\n $header = str_getcsv(array_shift($lines), ';');\n\n return [\n 'data' => array_map(\n function($line) use ($header) {\n return array_combine(\n $header,\n str_getcsv($line, ';')\n );\n },\n $lines\n )\n ];\n}\n</code></pre>\n<p>Or if you are on PHP7.4 or higher, use an arrow function for less verbose syntax:</p>\n<pre><code>public function getProducts(): array\n{\n $lines = file($this->file);\n $header = str_getcsv(array_shift($lines), ';');\n\n return [\n 'data' => array_map(\n fn($line) => array_combine($header, str_getcsv($line, ';')),\n $lines\n )\n ];\n}\n</code></pre>\n<hr />\n<p>I'm not sure that I am sold on the <code>array_merge()</code>-<code>array_combine()</code> technique in <code>mapData()</code>. (Just quietly, I think <code>array_replace()</code> is more semantically appropriate versus <code>array_merge()</code> -- though the effect is the same.) The use of <code>array_combine()</code> -- a function which is rather strict regarding its data requirements -- in <code>getProducts()</code> is more-or-less forgivable assuming the data sources are reliably valid. However, in <code>mapData()</code>, there may be some development or change to file contents which is not covered by your <code>getMappedKeys()</code>. This makes me think that there should be some conditions to throw exceptions in the class. I also wonder if instead of individual <code>const</code> declarations, I might use a lookup array to perform the translation. Maybe something for you to ponder, as I am not settled on my opinion yet.</p>\n<p>Finally, I don't see any benefit in nesting the relevant data inside of <code>$data['data']</code>. Always try to design the least complex data structures possible. In other words, strip out the needless first level as soon as possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T11:20:05.217",
"Id": "254647",
"ParentId": "254629",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-12T23:21:20.533",
"Id": "254629",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"design-patterns",
"json",
"csv"
],
"Title": "Transform Data from JSON and CSV to another JSON format"
}
|
254629
|
<p>I started learning Python these days and made my first code. Guess_The_Number and I would like some comments to improve or if I am on the right track. Thank you very much in advance
P.s: I am trying to create my own function.</p>
<pre class="lang-py prettyprint-override"><code>def guess_number (answer):
trys = 0
while trys < 5:
guessing = int(input("Your guessing is? "))
if guessing == answer:
print ("Yes!! it's Right!!")
break
elif guessing < answer:
print ("Big")
elif guessing > answer:
print ("smaller")
trys = trys+1
if trys == 5:
print("WoW, your trys are over , try again!!")
print("The number was ", answer)
print("Welcome to guess the number!!")
print("You have 5 trys to guess the number")
print("Good Luck!!")
print("I'm thiking in a number from 0 to 100")
print('')
import random
num_right = random.randint(0,100)
guess_number(num_right)
</code></pre>
|
[] |
[
{
"body": "<p>This might seem a bit much, but I'm reviewing this as if it were intended for production code:</p>\n<ol>\n<li><p><code>black</code> and <code>isort</code> can reformat this code to be more idiomatic without changing the functionality.</p>\n</li>\n<li><p><code>pylint</code>, <code>flake8</code> or both can tell you of some issues with this code:</p>\n<pre><code>$ pylint --disable=missing-function-docstring,missing-module-docstring q.py \n************* Module q\nq.py:3:0: C0303: Trailing whitespace (trailing-whitespace)\nq.py:14:0: C0303: Trailing whitespace (trailing-whitespace)\nq.py:6:8: R1723: Unnecessary "elif" after "break" (no-else-break)\nq.py:23:0: C0413: Import "import random" should be placed at the top of the module (wrong-import-position)\n\n------------------------------------------------------------------\nYour code has been rated at 8.26/10\n</code></pre>\n</li>\n<li><p>The plural of "try" is "tries".</p>\n</li>\n<li><p><code>trys += 1</code> is syntactic sugar for <code>trys = trys + 1</code>.</p>\n</li>\n<li><p>The code mixes I/O (<code>input</code>/<code>print</code>) and logic, which generally makes the code harder to maintain. It might be better to split this into two functions, one to check the answer against the right answer, and one to receive input and print output.</p>\n</li>\n<li><p>To enable reuse of the code I would add a <code>main</code> function and the idiomatic</p>\n<pre><code>if __name__ == "__main__":\n main()\n</code></pre>\n<p>lines at the bottom of the script to actually run it. Basically, if you just import your file into another nothing should print when importing it. Right now it's impossible to import cleanly from the script:</p>\n<pre><code>$ python\nPython 3.9.1 (default, Dec 13 2020, 11:55:53) \n[GCC 10.2.0] on linux\nType "help", "copyright", "credits" or "license" for more information.\n>>> import q\nWelcome to guess the number!!\nYou have 5 trys to guess the number\nGood Luck!!\nI'm thiking in a number from 0 to 100\n\nYour guessing is? \n</code></pre>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T03:10:07.367",
"Id": "502169",
"Score": "1",
"body": "thanks for the feedback,I'm yet a beginner and have some terms i never see before like 'isort', but i search in google so no problem. I have many things to improve and work. thanks again i'll try to apply your tips ^_^."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T02:57:47.980",
"Id": "254633",
"ParentId": "254632",
"Score": "2"
}
},
{
"body": "<p>What I have to add here, is that you should always validate/sanitize user input.</p>\n<pre><code>guessing = int(input("Your guessing is? "))\n</code></pre>\n<p>Converting plain user input to an <code>int</code>, without checking, is prone to cause problems. I would suggest creating an <code>isInteger(something: str)</code> (something will always be a string) function to validate that.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def safeInt(something: str): # maybe you could be more creative with that name\n """ If `something` can be converted to an int return that otherwise reutrn False """\n try:\n return int(something)\n except ValueError:\n return False\n</code></pre>\n<p>And now, you can keep asking the user again, if their <code>input</code> is incorrect</p>\n<pre><code>while trys < 5:\n guessing = input("Your guessing is? ")\n # Keep asking until you get a valid response\n while type(guessing := safeInt(guessing)) != int: # walrus operator \n guessing = input("You did not enter a valid int. Your guessing is? ")\n # Once this point is reached `guessing` will be an `int`.\n # guessing := safeInt(guessing) sets guessing = safeInt(guessing) \n # and evaluates `type(safeInt(guessing)) != int` at the same time\n</code></pre>\n<p>On a side note, <code>if trys == 5</code> is redundant. That is, because it comes after <code>while trys < 5</code> which will exit once <code>tries >= 5</code> and because you are incrementing by <code>1</code>, when the loop breaks, <code>trys</code> will be exactly <code>5</code>. So it is safe to say, that you can remove that <code>if</code> statement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T19:33:04.330",
"Id": "502266",
"Score": "0",
"body": "Good concept, except rather than a function with a return type of `Union[int, Literal[False]]` I'd prefer to just catch `ValueError` in the function with the `input` call."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T08:21:43.640",
"Id": "254639",
"ParentId": "254632",
"Score": "1"
}
},
{
"body": "<p><strong>I suggest to refactor it as follows:</strong></p>\n<pre><code>import random\n\ndef guess_number (answer):\n for num_tries in range(5):\n try:\n guess = int(input("Your guess: "))\n except:\n break\n if guess < answer:\n print ("Too low")\n elif guess > answer:\n print ("Too high")\n else:\n print ("Yes! It's right!")\n return\n \n print("Wow, your guesses are over!")\n print(f"The number was {answer}")\n \nprint("Welcome to guess the number!")\nprint("You have 5 tries to guess the number")\nprint("Good Luck!")\nprint("I'm thinking of a number from 0 to 100")\n\nmy_num = random.randint(0, 100)\nguess_number(my_num)\n</code></pre>\n<p><strong>Below are some comments on your code:</strong></p>\n<pre><code>def guess_number (answer):\n # Needs a better name. Also, plural of try is tries:\n trys = 0\n \n while trys < 5:\n # guess is a better name.\n guessing = int(input("Your guessing is? "))\n if guessing == answer:\n print ("Yes!! it's Right!!")\n # change to return:\n break\n elif guessing < answer:\n # Improve the message - it is not clear:\n print ("Big")\n elif guessing > answer:\n print ("smaller")\n # Use a for loop instead, which combines incrementing \n # and < 5 check:\n trys = trys+1\n \n # It is 5 anyway, after the while loop exits. Remove this if:\n if trys == 5:\n print("WoW, your trys are over , try again!!")\n # Use an f-string instead:\n print("The number was ", answer)\n \nprint("Welcome to guess the number!!")\nprint("You have 5 trys to guess the number")\nprint("Good Luck!!")\nprint("I'm thiking in a number from 0 to 100")\nprint('')\n# import should be at the top:\nimport random\n# use a better name:\nnum_right = random.randint(0,100)\nguess_number(num_right)\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T16:27:48.563",
"Id": "254657",
"ParentId": "254632",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254633",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T02:36:09.387",
"Id": "254632",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Guess the number Feedback Please"
}
|
254632
|
<p><strong>EDIT</strong></p>
<p>To me <code>JSON.stringify</code> is not the solution here, as it is much slower than recursion</p>
<pre><code> JSON.stringify(fakeData)
.replace(/,/g, ';')
.replace(/:(?={)/g, '')
.replace(/"/g, '')
</code></pre>
<pre><code>//Result
Recursion with reduce x 816,321 ops/sec ±7.38% (80 runs sampled)
JSON.stringify x 578,221 ops/sec ±1.72% (92 runs sampled)
Fastest is Recursion with reduce
</code></pre>
<p>I am making a css-in-js library, and I need to use recursion to turn object into string like this:</p>
<p>Input:</p>
<pre><code>const fakeData = {
a: {
b: 'c',
d: 'e'
}
}
</code></pre>
<p>Output:</p>
<pre><code>a{b:c;d:e;}
</code></pre>
<p>My recursion function:</p>
<pre><code>const buildKeyframe = (obj) => {
return Object.entries(obj).reduce((acc, [prop, value]) => {
if (typeof value === 'string') {
return `${acc}${prop}:${value};`
}
return `${acc}${prop}:{${buildKeyframe(value)}}`
}, '')
}
</code></pre>
<p>This function works, but I think there is room for improvement(e.g. use TCO, avoid using <code>reduce</code>)... How can I write a better function to recurse this data structure?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T04:37:21.493",
"Id": "502171",
"Score": "0",
"body": "The function does not work. Eg for object `{a:{b:\"1\",c:{d:\"2\"}}}` the pair `b:\"1\"` is missing from the returned string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T04:47:08.420",
"Id": "502173",
"Score": "0",
"body": "Fixed the function now"
}
] |
[
{
"body": "<p>I agree that JSON.stringify isn't the most appropriate for this problem, not just because it's slower, but also because it's a bit harder to understand. And you're also right in assuming that reduce() isn't the best tool for the job. Using a .map() reads in a much more natural way.</p>\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 convert = obj => (\n Object.entries(obj)\n .map(([key, value]) => (\n typeof value === 'string'\n ? `${key}:${value};`\n : `${key}{${convert(value)}}`\n ))\n .join('')\n)\n\nconsole.log(convert({\n a: {\n b: 'c',\n d: 'e'\n },\n}))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>When optimizing this, think about the use case. While tail-call recursion may or may not be possible, it will make the code much more difficult to read, and it really won't help. The main advantage to tail-call recursion is to save memory on the call stack, and to let a recursive function call into itself an unlimited amount of times while still using just one call-frame worth of memory on the stack. There's no practical chunk of extremely nested CSS that can be written to make tail-call optimization worth it.</p>\n<p>In your question, speed seems to be one of your primary concerns, but I'll play a bit of devil's advocate here and ask if it really should be for this use case. How much CSS-in-JS would you need to write before any of these micro-performance improvements even become noticeable? Tens of thousands of lines? Hundreds of thousands? I would suggest just building out the library first, run some benchmarks afterwards, and find out what parts of it actually run slow. Then only worry about fixing the slower areas.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T08:48:26.343",
"Id": "254736",
"ParentId": "254634",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "254736",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T03:42:33.137",
"Id": "254634",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "How to use recursion to turn object into string?"
}
|
254634
|
<p>I wrote a simple encryption function that uses argon2d as the KDF and XChaCha20-Poly1305 as the AEAD. Since it is very easy to not get things right when dealing with encryption, I would appreciate if someone could review my script and tell me if it has any vulnerabilities and could be used in the real world to encrypt real data.</p>
<pre><code>import argon2
from Cryptodome.Cipher import ChaCha20_Poly1305
import secrets
def encrypt(password, data):
salt = secrets.token_bytes(32)
nonce = secrets.token_bytes(24)
key = argon2.low_level.hash_secret_raw(secret=password, salt=salt, time_cost=3, memory_cost=1000000, parallelism=4, hash_len=32, type=argon2.low_level.Type.D, version=19)
cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce)
ciphertext, tag = cipher.encrypt_and_digest(data)
return salt + nonce + ciphertext + tag
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T14:12:55.727",
"Id": "502523",
"Score": "1",
"body": "Note for future questions: when reviewing encryption code, it's helpful to also see the corresponding decryptor (even if that's in a different language) and examples of use. Normally, your test program will show both of these, and it's a good idea to include that in your question."
}
] |
[
{
"body": "<p>You can add annotations in function parameters, like <code>password: str</code> and so on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T10:17:42.820",
"Id": "502201",
"Score": "2",
"body": "They may be [called something else](https://www.python.org/dev/peps/pep-0484/#abstract)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T00:09:57.083",
"Id": "502288",
"Score": "2",
"body": "@greybeard \"Annotation\" should be fine, although it's a bit general. From your link: \"here is a simple function whose argument and return type are declared **in the annotations**:\". The syntax is called an [annotation](https://www.python.org/dev/peps/pep-3107/), and they're being used as type hints here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:45:24.617",
"Id": "254642",
"ParentId": "254641",
"Score": "1"
}
},
{
"body": "<p>It's not clear whether the parameters <code>password</code> and <code>data</code> should be passed as strings or as byte-arrays. Use type-hint annotations, or at least a doc-comment so that users know which they should be passing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T02:50:10.153",
"Id": "502560",
"Score": "0",
"body": "Besides that, would the rest of the code be safe for encryption?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T14:10:27.303",
"Id": "254796",
"ParentId": "254641",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:39:25.787",
"Id": "254641",
"Score": "3",
"Tags": [
"python",
"cryptography",
"encryption"
],
"Title": "Correct implementation of encryption function"
}
|
254641
|
<p>I have a an if statement that works just fine, however, it has become a bit long and I need help to figure out how I can reduce the lines of code and thereby the readability.</p>
<p>I have a <code>defaultMonth</code> and set of <code>months</code> and a corresponding <code>price</code>. I need to add or reduce the price depending on the <code>defaultMonth</code> and <code>month</code> selected by the user.</p>
<p>Here are some examples of the output I need (note the interval is the same):</p>
<p>If default month is 60 - set price accordingly:</p>
<pre><code>Month - Price
60 0.0
48 0.1
36 0.2
24 0.35
12 0.5
</code></pre>
<p>If default month is 48 - set price accordingly:</p>
<pre><code>Month - Price
60 -0.1
48 0.0
36 0.1
24 0.25
12 0.4
</code></pre>
<p>If default month is 36 - set price accordingly:</p>
<pre><code>Month - Price
60 -0.2
48 -0.1
36 0.0
24 0.15
12 0.3
</code></pre>
<p>The way I've built it now is with an if statement for each default month and nested ifs for each month.</p>
<pre><code>if (defaultMonth === 60) {
if (month === 60) {
this.price += 0.0
}
if (month === 48) {
this.price += 0.1
}
if (month === 36) {
this.price += 0.2
}
if (month === 24) {
this.price += 0.35
}
if (month === 12) {
this.price += 0.5
}
}
if (defaultMonth === 48) {
if (month === 60) {
this.price -= 0.1
}
if (month === 48) {
this.price += 0.0
}
if (month === 36) {
this.price += 0.1
}
if (month === 24) {
this.price += 0.25
}
if (month === 12) {
this.price += 0.4
}
}
if (defaultMonth === 36) {
if (month === 60) {
this.price -= 0.2
}
if (month === 48) {
this.price -= 0.1
}
if (month === 36) {
this.price += 0.0
}
if (month === 24) {
this.price += 0.15
}
if (month === 12) {
this.price += 0.3
}
}
if (defaultMonth === 24) {
if (month === 60) {
this.price -= 0.35
}
if (month === 48) {
this.price -= 0.25
}
if (month === 36) {
this.price -= 0.15
}
if (month === 24) {
this.price += 0.0
}
if (month === 12) {
this.price += 0.15
}
}
if (defaultMonth === 12) {
if (month === 60) {
this.price -= 0.5
}
if (month === 48) {
this.price -= 0.4
}
if (month === 36) {
this.price -= 0.3
}
if (month === 24) {
this.price -= 0.15
}
if (month === 12) {
this.price += 0.0
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:56:01.483",
"Id": "502200",
"Score": "3",
"body": "Something I forgot to tell you on SO, but we'd need your whole code (your whole if else if part), not just a piece of code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T12:49:46.103",
"Id": "502208",
"Score": "0",
"body": "Looks like you want to look up both `month` and `defaultMonth` in `0.0, 0.1, 0.2, 0.35, 0.5`, and then return the difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T14:42:54.987",
"Id": "502214",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>If I were doing this, I'd start by putting the data into a 2 dimensional array. As raw data, it seems to be pretty much this:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>default</th>\n<th>12</th>\n<th>24</th>\n<th>36</th>\n<th>48</th>\n<th>60</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>36</td>\n<td>-0.2</td>\n<td>-0.1</td>\n<td>0.0</td>\n<td>0.15</td>\n<td>0.3</td>\n</tr>\n<tr>\n<td>48</td>\n<td>-0.1</td>\n<td>0.0</td>\n<td>0.1</td>\n<td>0.25</td>\n<td>0.4</td>\n</tr>\n<tr>\n<td>60</td>\n<td>0.0</td>\n<td>0.1</td>\n<td>0.2</td>\n<td>0.35</td>\n<td>0.5</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>I don't do a lot of JavaScript, but I think in JavaScript syntax, that works out to something on this general order:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>var priceTable = { \n "36": { "12": -0.2, "24": -0.1, "36": 0.0, "48": 0.15, "60": 0.3 }, \n "48": { "12": -0.1, "24": 0.0, "36": 0.1, "48": 0.25, "60": 0.4 }, \n "60": { "12": 0.0, "24": 0.1, "36": 0.2, "48": 0.35, "60": 0.5 } \n};\n\nthis.price += priceTable[defaultMonth][month];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T22:28:42.553",
"Id": "254669",
"ParentId": "254643",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "254669",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T09:55:25.113",
"Id": "254643",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Improving or replacing a long if statement"
}
|
254643
|
<p>I have a training dataset from which I want to draw samples in a random fashion such that all samples are used before getting randomly shuffled again. For this reason I implemented a simple random index generator.</p>
<p>For a dataset of 10 samples, the output looks something like this:</p>
<pre><code>0 1 2 3 4 5 6 7 8 9
4 3 7 8 0 5 2 1 6 9
0 5 7 8 4 3 9 2 1 6
5 7 6 3 8 4 2 0 1 9
4 6 0 2 8 1 3 9 5 7
4 0 5 1 7 9 6 2 8 3
3 8 5 6 1 7 2 4 0 9
0 4 6 2 9 5 8 3 1 7
1 3 6 8 2 7 5 9 0 4
5 1 7 9 8 0 6 4 2 3
</code></pre>
<p>I would appreciate advice especially in the following areas:</p>
<ul>
<li>Code style (readability, naming conventions, etc...)</li>
<li>Class design</li>
<li>Efficiency (how to avoid unnecessary complexity)</li>
<li>Reinventing the wheel (does the STL offer functionality that I should use?)</li>
<li>Are there perhaps bugs that I am not seeing right now?</li>
</ul>
<p>Please be as hard as possible with this implementation and give me constructive feedback.</p>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include "random_index.hpp"
int main() {
unsigned int size = 10;
RandomIndex rand_idx(size);
unsigned int n = 0;
for (unsigned int i=0; i<100; ++i, ++n) {
std::cout << rand_idx.get_index() << ' ';
if ((n+1) % size == 0) {
std::cout << '\n';
}
}
std::cout << '\n';
}
</code></pre>
<p><strong>random_index.cpp</strong></p>
<pre><code>#include "random_index.hpp"
RandomIndex::RandomIndex(unsigned int _size) {
size = _size;
index.resize(_size, 0);
std::iota(index.begin(), index.end(), 0);
}
unsigned int RandomIndex::get_index() {
if (counter < size) {
return index[counter++];
} else {
counter = 0;
std::random_shuffle(index.begin(), index.end());
return index[counter++];
}
}
</code></pre>
<p><strong>random_index.hpp</strong></p>
<pre><code>#ifndef RANDOM_INDEX_H
#define RANDOM_INDEX_H
#include <vector>
#include <numeric>
#include <algorithm>
class RandomIndex {
public:
RandomIndex(unsigned int _size);
unsigned int get_index();
private:
unsigned int size;
unsigned int counter = 0;
std::vector<unsigned int> index;
};
#endif
</code></pre>
<p>I compiled the code using the following command:</p>
<pre><code>g++ -O -Wall main.cpp random_index.cpp
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T13:45:46.507",
"Id": "502211",
"Score": "0",
"body": "You might want to use [`std::sample`](https://en.cppreference.com/w/cpp/algorithm/sample) instead."
}
] |
[
{
"body": "<h2>Overview</h2>\n<p>Your code produces the exact same set of samples each time you <code>random_shuffle</code>. So the output is always</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>0 1 2 3 4 5 6 7 8 9 \n4 3 7 8 0 5 2 1 6 9 \n0 5 7 8 4 3 9 2 1 6 \n5 7 6 3 8 4 2 0 1 9 \n4 6 0 2 8 1 3 9 5 7 \n4 0 5 1 7 9 6 2 8 3 \n3 8 5 6 1 7 2 4 0 9 \n0 4 6 2 9 5 8 3 1 7 \n1 3 6 8 2 7 5 9 0 4 \n5 1 7 9 8 0 6 4 2 3 \n</code></pre>\n<hr />\n<p>You should initialize the <a href=\"https://cutt.ly/gjn8NAx\" rel=\"nofollow noreferrer\">seed</a>. You do that before you call <code>random_shuffle</code>. If you do not do that it will give the same result each time since it relies on the seed.</p>\n<p>You can fix that by calling <code>std::srand</code> in the beginning.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int main() {\n std::srand(std::time(0));\n}\n</code></pre>\n<p>Now you can see the difference in the output</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>0 1 2 3 4 5 6 7 8 9\n9 2 8 3 6 4 0 7 1 5\n8 9 4 6 7 2 1 5 0 3\n4 6 0 2 3 1 5 8 9 7\n2 3 0 1 6 8 9 5 7 4\n8 9 6 5 2 1 3 7 4 0\n9 3 2 8 6 7 5 0 4 1\n8 1 2 5 9 6 4 3 0 7\n7 1 4 6 8 9 3 0 5 2\n3 1 9 4 2 7 6 0 5 8\n</code></pre>\n<p>But the top row still will always be the same. The problem lies here</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>RandomIndex::RandomIndex(unsigned int _size) {\n size = _size;\n index.resize(_size, 0);\n std::iota(index.begin(), index.end(), 0);\n}\n\n</code></pre>\n<p><code>iota</code> will always will it starting with <code>0</code> and incrementing it will it reaches <code>index.end()</code>. <code>get_index</code> will only shuffle the container after the first row since that's when <code>counter < size</code> evaluates to false.</p>\n<p>To fix that you can also shuffle in the beginning, when you construct the vector.</p>\n<hr />\n<h2>Use <code>std::shuffle</code></h2>\n<p><a href=\"https://meetingcpp.com/blog/items/stdrandom_shuffle-is-deprecated.html\" rel=\"nofollow noreferrer\"><code>random_shuffle</code> has been deprecated</a>. Use <code>shuffle</code> with a random number generator so that your code can compile on the later c++ versions.</p>\n<hr />\n<h2>Avoid using <code>_</code> as a prefix for your variables</h2>\n<p>There are some <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier#:%7E:text=You%20should%20avoid%20using%20one,by%20a%20lower%2Dcase%20letter.\">naming conventions</a> you need to follow when it comes to underscores to avoid collisions. Moreover, it just looks ugly. To initialize <code>size</code> in your class constructor you are better off using <a href=\"https://en.cppreference.com/w/cpp/language/constructor\" rel=\"nofollow noreferrer\">member initializer lists</a>.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>RandomIndex::RandomIndex(unsigned int size)\n : size(size) {\n\n //...\n}\n</code></pre>\n<hr />\n<h2>use an <code>array</code> with a fixed size over vector</h2>\n<p>In your class <code>size</code> is a value that is never going to change. If you plan on keeping it that way you can, use <code>std::array</code> here with a template so you can have a fixed size. This will avoid all the resizing and heap fiddling resulting in faster execution. <code>std::shuffle</code> will work the same way it does with <code>vector</code> thanks to the way STL is designed.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template < size_t s >\nclass RandomIndex {\n //...\n\nprivate:\n std::array < uint32_t, s > index;\n \n};\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T13:31:39.200",
"Id": "254651",
"ParentId": "254646",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T11:09:54.050",
"Id": "254646",
"Score": "2",
"Tags": [
"c++",
"beginner",
"c++11"
],
"Title": "Random index generator in C++"
}
|
254646
|
<p>Several years ago (must have been 2012 or so) I wrote a module to manage command-line parameters in a unix-like fashion. At the time, the compilers I had access to were still working their way up to the 2003 standard. In particular, allocatable strings and class(*) still had issues. So far, the module has served me well. Indeed, I hope someone may find it useful too. However, I also think it is about time for other eyes to have a look at it and suggest possible improvements. I provide below the module with a test at the end. I look forward to your feedback.</p>
<p>For folks not familiar with the simple syntax of modern Fortran, I suggest the following <a href="https://fortran-lang.org/learn/quickstart" rel="nofollow noreferrer">quick modern Fortran tutorial</a>.</p>
<pre class="lang-fortran prettyprint-override"><code>!! ModuleCommandLineParameterList, Copyright (C) 2020 by Luca Argenti, PhD - Some Rights Reserved
!! ModuleCommandLineParameterList is licensed under a
!! Creative Commons Attribution-ShareAlike 4.0 International License.
!! A copy of the license is available at <http://creativecommons.org/licenses/by-nd/4.0/>.
!!
!! Luca Argenti is Associate Professor of Physics, Optics and Photonics
!! Department of Physics and the College of Optics
!! University of Central Florida
!! 4111 Libra Drive, Orlando, Florida 32816, USA
!! email: luca.argenti@ucf.edu
! {{{ Detailed description
!> \file
!!
!! Defines the package of classes for reading
!! run time parameters from the command line.
!!
! }}}
module ModuleCommandLineParameterList
use, intrinsic :: ISO_FORTRAN_ENV
implicit none
private
!> Creates a list with all the parameters to be read from the command line.
type, public :: ClassCommandLineParameterList
!
private
!
!> Stores detailed description about the parameters should be written in the command line.
character(len=:) , allocatable :: Description
!> Points to the first command line parameter available in the analized interval.
type(ClassParameter), pointer :: First => NULL()
!> Points to the last command line parameter available in the analized interval.
type(ClassParameter), pointer :: Last => NULL()
!
contains
!
!> Sets the ClassCommandLineParameterList's Description variable, from an external string.
procedure, public :: SetDescription
!> Prints the program usage.
procedure, public :: PrintUsage
!> Adds any parameter to the list of run time parameters to be read.
generic , public :: Add => AddSwitchParameter, AddValuedParameter
!> Parses the command line.
procedure, public :: Parse => ParseCommandLine
!> Retrieves whether a parameter is present in the command line or not.
procedure, public :: Present => ParameterIsPresent
!> Gets the parameter value.
procedure, public :: Get => GetParameterFromList
!> Frees ClassCommandLineParameterList.
procedure, public :: Free => FreeParameterList
!> Prints on a unit all the parameters.
procedure, public :: PrintAll => ParameterListPrint
!
procedure, private :: AddValuedParameter
procedure, private :: AddSwitchParameter
procedure, private :: WhichParameter
procedure, private :: Check
procedure, private :: Insert
!
end type ClassCommandLineParameterList
!> Stores the properties of any run time parameter.
type, private :: ClassParameter
!
!> Points to the previous run time parameter.
type(ClassParameter), pointer :: Prev => NULL()
!> Points to the next run time parameter.
type(ClassParameter), pointer :: Next => NULL()
!
!> Run time parameter's name.
character(len=:) , allocatable :: Name
!> Run time parameter's purpose.
character(len=:) , allocatable :: Purpose
!> Run time parameter's value.
class(*) , allocatable :: Value
!
!> Indicates whether the parameter is required for the program execution or not.
logical :: IsRequired = .FALSE.
!> Indicates whether the parameter is present in the command line or not.
logical :: IsPresent = .FALSE.
!> Indicates whether the parameter has a value or not.
logical :: IsValued = .FALSE.
!
contains
!
!> Gets the value of the parameter.
procedure :: Get => GetFromParameter
!> Sets the ClassParameter objects corresponding to the requested parameter.
procedure :: Set => ParameterSet
!> Print the usage of a run time parameter on the screen, e.g.:
!!
!! [--help (print usage)]
!! -ne <number of energies>
!!
procedure :: Print => ParameterPrint
!> Frees the ClassParameter objects.
procedure :: Free => FreeParameter
!> Converts the parameter value from string format to the appropiated one (integer, double precision, logical or character).
procedure :: StringToValue
!> Gets the kind of the parameter: "Integer", "Double", "Logical", "String" or " " for other kind.
procedure :: Kind => ParameterKind
!> Gets the parameter default value in string format.
procedure :: DefaultValueString => ParameterDefaultValueString
!
end type ClassParameter
contains
!> Sets the ClassCommandLineParameterList's Description variable, from an external string.
subroutine SetDescription( List, Description )
class(ClassCommandLineParameterList), intent(out) :: List
character(len=*) , intent(in) :: Description
if(allocated(List%Description))deallocate(List%Description)
allocate(List%Description,source=trim(adjustl(Description)))
end subroutine SetDescription
subroutine AddSwitchParameter( List, Name, Purpose )
class(ClassCommandLineParameterList), intent(inout) :: List
character(len=*) , intent(in) :: Name
character(len=*) , intent(in) :: Purpose
!
logical, parameter :: IS_VALUED = .FALSE.
class(ClassParameter), pointer :: Parameter
allocate(Parameter)
call Parameter%Set(Name,"optional",Purpose,IS_VALUED)
call List%Insert(Parameter)
end subroutine AddSwitchParameter
subroutine AddValuedParameter( List, Name, Purpose, Value, Condition )
class(ClassCommandLineParameterList), intent(inout) :: List
character(len=*) , intent(in) :: Name
character(len=*) , intent(in) :: Purpose
Class(*) , intent(in) :: Value
character(len=*) , intent(in) :: Condition
!
logical, parameter :: IS_VALUED = .TRUE.
class(ClassParameter), pointer :: Parameter
Parameter => CreateParameter( Value )
call Parameter%Set(Name,Condition,Purpose,IS_VALUED)
call List%Insert(Parameter)
end subroutine AddValuedParameter
function CreateParameter( Value ) result(Parameter)
class(*), intent(in) :: Value
class(ClassParameter), pointer :: Parameter
allocate(Parameter)
allocate(Parameter%value,source=Value)
end function CreateParameter
!> Sets the ClassParameter objects corresponding to the requested parameter.
subroutine ParameterSet( Parameter, Name, Condition, Purpose, IsValued )
class(classParameter), intent(inout) :: Parameter
character(len=*) , intent(in) :: Name
character(len=*) , intent(in) :: Condition
character(len=*) , intent(in) :: Purpose
logical , intent(in) :: IsValued
Parameter%Prev => Null()
Parameter%Next => Null()
allocate(Parameter%Name,source=trim(adjustl(Name)))
Parameter%IsPresent=.FALSE.
select case( Condition )
case("optional")
Parameter%IsRequired=.FALSE.
case("required")
Parameter%IsRequired=.TRUE.
case DEFAULT
call Assert("Invalid parameter condition")
end select
allocate( Parameter%Purpose, source = trim( adjustl( Purpose ) ) )
Parameter%IsValued = IsValued
end subroutine ParameterSet
subroutine Insert( List, Parameter )
class(ClassCommandLineParameterList), intent(inout) :: List
class(ClassParameter), pointer , intent(in) :: Parameter
if( .not.associated(List%First) )then
List%First => Parameter
List%Last => Parameter
else
Parameter%Prev => List%Last
List%Last%Next => Parameter
List%Last => Parameter
endif
end subroutine Insert
!> Print the usage of a run time parameter on the screen, e.g.:
!!
!! [--help (print usage)]
!! -ne <number of energies>
!!
subroutine ParameterPrint( Parameter, uid )
class(ClassParameter), intent(in) :: Parameter
integer , intent(in) :: uid
character(len=512) :: Synopsis
Synopsis=" "
Synopsis=trim(Synopsis)//trim(Parameter%Name)
if( Parameter%IsValued )then
Synopsis=trim(Synopsis)//" <"//Parameter%Purpose//"> "
if(.not.Parameter%IsRequired)then
Synopsis=trim(Synopsis)//", default="//Parameter%DefaultValueString()
endif
Synopsis=trim(Synopsis)//" ("//Parameter%Kind()//") "
else
Synopsis=trim(Synopsis)//" ("//Parameter%Purpose//") "
endif
if( Parameter%IsRequired )then
Synopsis=" "//trim(Synopsis)
else
Synopsis="["//trim(Synopsis)//"]"
endif
write(uid,"(a)") trim(Synopsis)
end subroutine ParameterPrint
!> Gets the kind of the parameter: "Integer", "Double", "Logical", "String" or " " for other kind.
function ParameterKind( Parameter ) result( KindStrn )
Class(ClassParameter), intent(in) :: Parameter
character(len=:), allocatable :: KindStrn
select type(ptr=>Parameter%Value)
type is(integer)
allocate(KindStrn,source="Integer")
type is(real(kind(1d0)))
allocate(KindStrn,source="Double")
type is(logical)
allocate(KindStrn,source="Logical")
type is(character(len=*))
allocate(KindStrn,source="String")
class DEFAULT
allocate(KindStrn,source=" ")
end select
end function ParameterKind
!> Gets the parameter default value in string format.
function ParameterDefaultValueString( Parameter ) result( DefaultValueStrn )
Class(ClassParameter), intent(in) :: Parameter
character(len=:), allocatable :: DefaultValueStrn
character(len=512) :: strn
if(.not.allocated(Parameter%Value))then
strn = "[Not Valued]"
else
select type(ptr=>Parameter%Value)
type is(integer)
write(strn,"(i0)") ptr
type is(real(kind(1d0)))
write(strn,"(d11.3)") ptr
type is(logical)
write(strn,*) ptr
type is(character(len=*))
strn=trim(adjustl(ptr))
class DEFAULT
strn = "[Unrecognized Value Kind]"
end select
endif
allocate(DefaultValueStrn,source=trim(adjustl(strn)))
end function ParameterDefaultValueString
!> Prints the program usage.
subroutine PrintUsage( List, OutputUnit )
!
class(ClassCommandLineParameterList), intent(in) :: List
integer, optional , intent(in) :: OutputUnit
character(len=64) :: ProgramName
integer :: stat, LastSlash, uid
!
!> Determines the current name of the executable
call Get_Command_Argument(0,ProgramName,status=stat)
if(stat/=0)ProgramName="<Program Name>"
LastSlash=index(ProgramName,"/",back=.true.)
ProgramName=adjustl(ProgramName(LastSlash+1:))
!
uid = OUTPUT_UNIT
if(present(OutputUnit))uid=OutputUnit
!> Print the underlined name of the program followed
!! by its description
write(uid,"(a)")
write(uid,"(a)") trim(ProgramName)
write(uid,"(a)") repeat("=",Len_Trim(ProgramName))
write(uid,"(a)") trim(List%Description)
write(uid,"(a)")
call List%PrintAll( uid )
write(uid,"(a)")
!
end subroutine PrintUsage
subroutine ParameterListPrint( List, uid )
class(ClassCommandLineParameterList), intent(in) :: List
integer , intent(in) :: uid
class(ClassParameter), pointer :: Parameter
Parameter=>List%First
do while(associated(Parameter))
call Parameter%Print(uid)
Parameter=>Parameter%Next
enddo
end subroutine ParameterListPrint
!> Gets the parameter value.
subroutine GetParameterFromList( List, Name, Value )
Class(ClassCommandLineParameterList), intent(in) :: List
character(len=*) , intent(in) :: Name
class(*) :: Value
Class(ClassParameter), pointer :: Parameter
Parameter => List%WhichParameter( trim( Name ) )
if(.not.Associated(Parameter)) call Assert("Unrecognized Parameter "//trim(Name))
call Parameter%Get(Value)
end subroutine GetParameterFromList
function WhichParameter( List, Name ) result( Parameter )
Class(ClassCommandLineParameterList), intent(in) :: List
character(len=*) , intent(in) :: Name
Class(ClassParameter) , pointer :: Parameter
Parameter => List%First
do while( associated( Parameter ) )
if(trim(Parameter%Name)==trim(Name))return
Parameter => Parameter%Next
enddo
end function WhichParameter
!> Gets the value of the parameter.
subroutine GetFromParameter( Parameter, Value )
Class(ClassParameter), intent(in) :: Parameter
class(*) :: Value
!.. I would have liked sooo much that the following
! worked. But unfortunately it doesn't.
!if(SAME_TYPE_AS(Parameter%value,value))then
! value=Parameter%value
!end if
select type(ptr=>Parameter%value)
type is (Integer)
select type(value)
type is (Integer)
value=ptr
class DEFAULT
call Assert("Invalid type request")
end select
type is (real(kind(1d0)))
select type(value)
type is (real(kind(1d0)))
value=ptr
class DEFAULT
call Assert("Invalid type request")
end select
type is (logical)
select type(value)
type is (logical)
value=ptr
class DEFAULT
call Assert("Invalid type request")
end select
type is (character(len=*))
select type(value)
type is (character(len=*))
value=trim(ptr)
class DEFAULT
call Assert("Invalid type request")
end select
class DEFAULT
call Assert("Unknown type")
end select
end subroutine GetFromParameter
!> Parses the command line.
subroutine ParseCommandLine( List )
!
class(ClassCommandLineParameterList), intent(inout) :: List
!
integer, parameter :: MAX_COMMAND_LINE_LENGTH = 2000
character(len=*), parameter :: HERE = ":ParseCommandLine:"
character(len=MAX_COMMAND_LINE_LENGTH) :: CommandLine
character(len=MAX_COMMAND_LINE_LENGTH) :: ParameterLine
integer :: status
integer :: EndOfExecutableName
type(ClassParameter), pointer :: Parameter
integer :: ParameterPosition
integer :: EndOfParameterName
integer :: EndOfParameterSpec
integer :: iostat
logical :: SUCCESS
SUCCESS = .TRUE.
!.. Read the command line
call Get_Command( CommandLine, status = status )
if(status/=0)call ASSERT(HERE//" Internal Error")
!.. Purge the name of the command from the command line
CommandLine=adjustl(CommandLine)
EndOfExecutableName=index(CommandLine," ")
CommandLine=CommandLine(EndOfExecutableName:)
!.. Cycle over Formal Run Time Parameters
Parameter => List%First
list_scan : do while( associated( Parameter ) )
!.. Search for the parameter in the command line.
! The spaces around the name are necessary to distinguish
! " -n 100" from " -next 2" and " -strn fool-name "
ParameterPosition = index( CommandLine, " "//trim(Parameter%Name)//" " )
Parameter%IsPresent = ParameterPosition > 0
if( Parameter%IsPresent )then
ParameterPosition = ParameterPosition + 1
else
!.. If the parameter is absent but required, issue a warning and stop,
! otherwise update the pointer and move on
if( Parameter%IsRequired )then
!call ErrorMessage("Parameter "//trim(Parameter%Name)//" is required")
SUCCESS = .FALSE.
endif
Parameter => Parameter%Next
cycle list_scan
endif
!.. If the parameter is valued, read the value.
if( Parameter%IsValued )then
!
!.. Extract Parameter Specification
ParameterLine = adjustl(CommandLine(ParameterPosition:))
!
!.. Purge Parameter Name
EndOfParameterName = Index(ParameterLine," ")
ParameterLine = adjustl(ParameterLine(EndOfParameterName:))
!
!.. Extract the string that supposedly contains the parameter value
EndOfParameterSpec = Index(ParameterLine," ")
if( EndOfParameterSpec <= 0 )then
EndOfParameterSpec=len_trim(ParameterLine)
else
EndOfParameterSpec=EndOfParameterSpec-1
endif
ParameterLine(EndOfParameterSpec+1:)=" "
!
!.. Assign the value
call Parameter%StringToValue( trim(ParameterLine), iostat )
SUCCESS = SUCCESS .and. ( iostat == 0 )
!
endif
Parameter => Parameter%Next
cycle list_scan
enddo list_scan
call List%Check(iostat)
SUCCESS = SUCCESS .and. ( iostat == 0 )
if( .not. SUCCESS )then
call List%PrintUsage( OUTPUT_UNIT )
STOP
endif
end subroutine ParseCommandLine
!> Converts the parameter value from string format to the appropiated one (integer, double precision, logical or character).
subroutine StringToValue( Parameter, ValueStrn, iostat )
class(ClassParameter), intent(inout) :: Parameter
character(len=*) , intent(in) :: ValueStrn
integer , intent(out) :: iostat
character(len=512) :: iomsg
iostat=0
iomsg=" "
select type (ptr=>Parameter%value)
type is(integer)
read(ValueStrn,*,iostat=iostat,iomsg=iomsg) ptr
type is(real(kind(1d0)))
read(ValueStrn,*,iostat=iostat,iomsg=iomsg) ptr
type is(logical)
read(ValueStrn,*,iostat=iostat,iomsg=iomsg) ptr
type is(character(len=*))
deallocate(Parameter%value)
allocate(Parameter%value,source=ValueStrn)
class DEFAULT
call ErrorMessage("Non-standard type")
end select
if(iostat/=0)then
call ErrorMessage("Invalid parameter "//trim(Parameter%Name))
endif
Parameter%IsPresent=.TRUE.
end subroutine StringToValue
!> Retrieves whether a parameter is present in the command line or not.
logical function ParameterIsPresent( List, Name ) result( Present )
class(ClassCommandLineParameterList), intent(in) :: List
character(len=*) , intent(in) :: Name
class(ClassParameter), pointer :: Parameter
Parameter=> List%WhichParameter(Name)
Present=.FALSE.
if(Associated(Parameter)) Present=Parameter%IsPresent
end function ParameterIsPresent
!> Frees the ClassParameter objects.
subroutine FreeParameter( Parameter )
class( ClassParameter ), intent(inout) :: Parameter
if(allocated(Parameter%Name ))deallocate(Parameter%Name)
if(allocated(Parameter%Purpose))deallocate(Parameter%Purpose)
if(allocated(Parameter%Value ))deallocate(Parameter%Value)
Parameter%IsRequired=.FALSE.
Parameter%IsPresent =.FALSE.
Parameter%IsValued =.FALSE.
Parameter%Prev=>NULL()
Parameter%Next=>NULL()
end subroutine FreeParameter
!> Frees ClassCommandLineParameterList.
subroutine FreeParameterList( List )
class( ClassCommandLineParameterList ), intent(inout) :: List
type( ClassParameter ), pointer :: Parameter, Next
Parameter => List%First
do while(associated(Parameter))
Next => Parameter%Next
call Parameter%Free()
deallocate(Parameter)
Parameter => Next
enddo
List%First => NULL()
List%Last => NULL()
end subroutine FreeParameterList
subroutine Check( List, iostat )
Class(ClassCommandLineParameterList), intent(in) :: List
integer , intent(out):: iostat
Class(ClassParameter), pointer :: Parameter
iostat=0
Parameter => List%First
do while( associated( Parameter ) )
if( Parameter%IsRequired .and. .not. Parameter%IsPresent )then
call ErrorMessage("Required Parameter "//trim(Parameter%Name)//" is missing.")
iostat=-1
endif
Parameter => Parameter%Next
enddo
end subroutine Check
subroutine ASSERT(Message)
use ISO_FORTRAN_ENV
character(len=*), intent(in) :: Message
write(OUTPUT_UNIT,"(a)")trim(Message)
stop
end subroutine ASSERT
subroutine ErrorMessage(Message)
use ISO_FORTRAN_ENV
character(len=*), intent(in) :: Message
write(OUTPUT_UNIT,"(a)")trim(Message)
end subroutine ErrorMessage
end module ModuleCommandLineParameterList
!=========================
module ModuleMainInterface
contains
subroutine GetCommandLineParameters( &
ConfigFile , &
EnergyMin , &
EnergyMax , &
NEnergies , &
Verbose )
!
use ModuleCommandLineParameterList
!
implicit none
character(len=:), allocatable, intent(out) :: ConfigFile
real(kind(1d0)) , intent(out) :: EnergyMin
real(kind(1d0)) , intent(out) :: EnergyMax
integer , intent(out) :: NEnergies
logical , intent(out) :: Verbose
!
character(len=*), parameter :: PROGRAM_DESCRIPTION = &
"Reads command-line parameters of assorted types to illustrate " // &
"the capability of ModuleCommandLineParameters "
type( ClassCommandLineParameterList ) :: List
character(len=100) :: StrnBuf
call List%SetDescription(PROGRAM_DESCRIPTION)
!.. Parameters are identified by their name, hyphen included
! The initialization of non-valued parameters only require name and description
call List%Add( "--help" , "Print Command Usage" )
!.. Initialitazion of valued parameters requires a default value, which defines their type,
! as well as a string specifying whether they are optional or not.
! If a optional, the parameter is set to default, otherwise the default is overridden.
call List%Add( "-f" , "Config File" , "test.inp", "optional" )
call List%Add( "-Emin" , "Minimum Energy", 0.d0 , "optional" )
call List%Add( "-Emax" , "Maximum Energy", 0.d0 , "required" )
call List%Add( "-n" , "Num. Energies ", 2 , "required" )
call List%Add( "-v" , "Verbose" )
call List%Parse()
if(List%Present("--help"))then
call List%PrintUsage()
stop
end if
call List%Get( "-f" , StrnBuf ); ConfigFile = trim( StrnBuf )
call List%Get( "-Emin", EnergyMin )
call List%Get( "-Emax", EnergyMax )
call List%Get( "-n" , NEnergies )
Verbose = List%Present("-v")
call List%Free()
end subroutine GetCommandLineParameters
end module ModuleMainInterface
Program TestCommandLineParameterList
use, intrinsic :: ISO_FORTRAN_ENV, only: OUTPUT_UNIT
use ModuleMainInterface
implicit none
!.. Command-line parameters
character(len=:), allocatable :: ConfigFile
real(kind(1d0)) :: EnergyMin
real(kind(1d0)) :: EnergyMax
integer :: NEnergies
logical :: Verbose
call GetCommandLineParameters( &
ConfigFile , &
EnergyMin , &
EnergyMax , &
NEnergies , &
Verbose )
if( Verbose )then
write(OUTPUT_UNIT,"(a)" ) " Config File : "//ConfigFile
write(OUTPUT_UNIT,"(a,e14.6)") " Min Energy : ", EnergyMin
write(OUTPUT_UNIT,"(a,e14.6)") " Max Energy : ", EnergyMax
write(OUTPUT_UNIT,"(a,i0)" ) " N Energies : ", NEnergies
endif
end Program TestCommandLineParameterList
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:27:11.487",
"Id": "502243",
"Score": "0",
"body": "I'm sure you get this a lot, but: why Fortran?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:59:22.320",
"Id": "502252",
"Score": "1",
"body": "Several reasons: i) it was/is the language of the trade in my community (theoretical chemistry, and atomic and molecular physics); ii) it is the de-fact standard of HPC, together with C/C++ (which is the only real alternative); iii) there is a massive amount of legacy code, and there were not something similar in C/C++ when I started. Finally, \"Fortran\" is to Fortran2003/2008 as the B language is to C++. Big difference, and none of the original nonsense. It is a very nice language. The only disadvantage is that the global community is small (and shrinking)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:05:38.990",
"Id": "502254",
"Score": "0",
"body": "Also: I actually do not get this question a lot ... Sure, you do not see trains on display at a car dealer. However, this does not mean that trains are car so obsolete that they do not travel on the road anymore. Rather, trains have their own tracks, not immediately visible to the general population, and are still crucial for mass transport. I do not have the statistics on the number of JavaScript programs running at supercomputing centers, but I bet less than either fortran or C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:14:14.630",
"Id": "502255",
"Score": "1",
"body": "I didn't suggest Fortran was obsolete, and I'm well aware of (e.g.) the role of LAPACK. Language zealotry varies based on what crowd you run in. I just wanted to know because the answer matters to any feedback (that I can't give). If it's \"recreational\" or \"industry-standard\" (your case), fine; if it's because \"I'm writing a new web server\" I would have different opinions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:20:04.297",
"Id": "502256",
"Score": "0",
"body": "@Reinderien of course, I would not think of writing a webserver in fortran (or in any other language, for the moment being). I think that knowing C is a must, and I wrote some little thing in C or C++ when needed. I like how they blend naturally with system calls. Overall, if I had to start everything again from scratch and I had the libraries that are available today in C++, I would probably use that. Anything else is not really an option, at the moment. We'll see about Julia."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:25:16.583",
"Id": "502258",
"Score": "0",
"body": "I do acknowledge, however, that being very fluent in one language, and always with the vocabulary in your hand for others more appropriate solutions is a limitation. This year I had to hack the quiz testbanks in our Learning Management System to prepare randomized multiple-choice quizzes, which were not available in the standard. Using fortran2003 I managed to write a generator with postfix math expression evaluations and output in QTI. A pretty decent thing, as a concept. I later passed it to our IT dept who converted it in a JavaScript app online, holding their breath ..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T12:58:38.920",
"Id": "254650",
"Score": "2",
"Tags": [
"console",
"fortran"
],
"Title": "Command-line parameters"
}
|
254650
|
<p>For this problem I originally wrote some VBA code which worked perfectly. I've since been tasked with integrating the results it produces with the spreadsheets data model so thought a PowerQuery would work better for that. I think my M code shows you can't just translate from one language to the next.</p>
<p>If you're interested in the VBA side the initial question is <a href="https://www.mrexcel.com/board/threads/udf-to-separate-date-ranges-where-they-overlap.1149631/" rel="nofollow noreferrer">here</a>.</p>
<p>The logic of the VBA code works in PowerQuery as long as the minimum to maximum date range in the table is only a month or two. In practice the date range will frequently be twenty years or more.</p>
<p>My new code works, which is why I'm asking here rather than on SO, but feel I may have to look at the problem from a completely different angle.</p>
<h2>Detail</h2>
<p>My source table is named <code>RawData</code>:</p>
<p><a href="https://i.stack.imgur.com/g4D5e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g4D5e.png" alt="enter image description here" /></a></p>
<p>And this is the result table:</p>
<p><a href="https://i.stack.imgur.com/ysM6H.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ysM6H.png" alt="enter image description here" /></a></p>
<p>What the result is showing is:</p>
<ul>
<li>Between 1st Jan and 20th Jan a quarterly payment was being made. 30 x 4 = 120 per year.</li>
<li>Between 15th Jan and 17th Jan a minus monthly payment was being made. -5 x 12 = -60 per year.
This value is added to the existing 120 per year so the final table shows 60 for that period.</li>
<li>A one-time payment covering 5th to 10th Jan was made. 6/6 = 1 * 365 = 365.<br />
This is added to the 120 per year so the final table shows 485 for that period.</li>
</ul>
<p>The code for the query is below. I can see there must be a huge bottleneck when merging tables, and by calculating the result per day but I don't know enough about the language to think of another way of getting the result.</p>
<pre><code>let
Source = Excel.CurrentWorkbook(){[Name="RawData"]}[Content],
ChangedType = Table.TransformColumnTypes(Source,{{"Component", type text}, {"Type", type text},
{"Start", type date}, {"End", type date},
{"Amount", type number}, {"Frequency", type text}}),
FormatFrequency = Table.TransformColumns(ChangedType,{{"Frequency", Text.Proper, type text}}),
DailyValue = Table.AddColumn(FormatFrequency, "DayAmount", each if [Frequency]="Quarterly" then ([Amount]*4)/365
else if [Frequency]= "Monthly" then ([Amount]*12)/365
else if [Frequency]="One-Time" then [Amount]/(Duration.Days(Date.From([End])-Date.From([Start]))+1)
else 0),
//Get list of all dates between minimum & maximum date in table.
StartDate = List.Min(DailyValue[Start]),
EndDate = List.Max(DailyValue[End]),
//I am hoping to have multiple components and group the final table by these as well as dates.
//Currently each row in the date list is given the first component value so I can group when summing the columns.
//Ideally I'd like to have the ListDates table contain a component along with each date that represents it.
Comp = List.First(DailyValue[Component]),
ListDates = Table.FromList(List.Dates(StartDate,Number.From(EndDate-StartDate)+1,#duration(1,0,0,0)), Splitter.SplitByNothing(),null,null,ExtraValues.Error),
AddComponent = Table.AddColumn(ListDates, "Component", each Comp),
RenameColumns2 = Table.RenameColumns(AddComponent,{{"Column1","Dates"}}),
ReorderedColumns = Table.ReorderColumns(RenameColumns2,{"Component", "Dates"}),
//Merge the two tables based on the component and identify which rows from the first table will be relevant to each date in the second.
MergeTables = Table.NestedJoin(ReorderedColumns, {"Component"}, DailyValue, {"Component"}, "DataTable", JoinKind.LeftOuter),
ExpandTable = Table.ExpandTableColumn(MergeTables, "DataTable", {"Start", "End", "DayAmount"}, {"Start", "End", "DayAmount"}),
AddAmountToDate = Table.AddColumn(ExpandTable, "Daily", each if [Dates]>=[Start] and [Dates]<=[End] then [DayAmount] else null),
//Tidy the table, sum any daily values that fall on the same day and multiply by 365 to get annual value.
RemoveNulls = Table.SelectRows(AddAmountToDate, each [Daily] <> null),
RemoveColumns = Table.RemoveColumns(RemoveNulls,{"Start", "End", "Daily"}),
SumValues = Table.Group(RemoveColumns, {"Component", "Dates"}, {{"Total", each List.Sum([DayAmount]), type number}}),
MakeAnnual = Table.TransformColumns(SumValues, {{"Total", each _ * 365, type number}}),
//Identify where annual value changes and record start/end dates.
AddIndex = Table.AddIndexColumn(MakeAnnual, "Index", 0, 1),
IsStart = Table.AddColumn(AddIndex, "Start", each if [Index] = 0 then [Dates]
else if [Total]<>AddIndex[Total]{[Index]-1} then [Dates]
else null),
IsEnd = Table.AddColumn(IsStart, "End", each if [Index] = List.Max(IsStart[Index]) then [Dates]
else if [Total]<>IsStart[Total]{[Index]+1} then [Dates]
else null),
RemoveEmptyRows = Table.SelectRows(IsEnd, each [Start] <> null or [End] <> null),
RemovedIndex = Table.RemoveColumns(RemoveEmptyRows,{"Index"}),
NewIndex = Table.AddIndexColumn(RemovedIndex, "Index", 0, 1),
FinalEnd = Table.AddColumn(NewIndex, "Final End", each if [Start] <> null and [End] <> null then [End]
else if [End] = null then NewIndex[End]{[Index]+1}
else null),
RemoveNullFinal = Table.SelectRows(FinalEnd, each ([Final End] <> null)),
TidyUp = Table.SelectColumns(RemoveNullFinal,{"Component", "Start", "Final End", "Total"}),
RenameColumn = Table.RenameColumns(TidyUp,{{"Final End", "End"}})
in
RenameColumn
</code></pre>
<p>Any help would be greatly appreciated in getting this to work at a useable speed. The <a href="/questions/tagged/beginner" class="post-tag" title="show questions tagged 'beginner'" rel="tag">beginner</a> tag relates to <a href="/questions/tagged/power-query" class="post-tag" title="show questions tagged 'power-query'" rel="tag">power-query</a> rather than <a href="/questions/tagged/excel" class="post-tag" title="show questions tagged 'excel'" rel="tag">excel</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T14:13:06.873",
"Id": "254653",
"Score": "0",
"Tags": [
"performance",
"beginner",
"excel",
"time-limit-exceeded"
],
"Title": "Calculating total payment value between date periods with different pay frequencies"
}
|
254653
|
<p>This checks if a given username is valid, before doing any database lookups.</p>
<p>(I know it's possibly better to use regular expressions, but I wanted to be able to give specific errors.)</p>
<p>I'm curious if there is a cleaner way to represent the set of valid characters.</p>
<pre><code>bool check_username_valid(const string& str, string &out_error) {
static const struct LUT {
bool a[256]{};
LUT() {
for (int x = 'a'; x <= 'Z'; x++) a[x] = true;
for (int x = 'A'; x <= 'Z'; x++) a[x] = true;
for (int x = '0'; x <= '9'; x++) a[x] = true;
a['_'] = true;
}
inline bool operator [] (char x) const { return a[int(((unsigned char)(x)))]; }
} allow;
if (str.length() < MinUsernameLen) { out_error = "Username Too Short"; return false; }
if (str.length() > MaxUsernameLen) { out_error = "Username Too Long"; return false; }
for (char c : str)
if (!allow[c]) {
out_error = "Invalid Character in Username";
return false;
}
return true;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:57:01.550",
"Id": "502250",
"Score": "0",
"body": "I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information"
}
] |
[
{
"body": "<p>Instead of the loop, we can use <code>std::all_of()</code> (or <code>std::any_of()</code> with the opposite condition). That can make the code clearer, because it signals intent at the beginning, and we don't need to unpick control flow as we do with <code>for</code>/<code>return</code>. With C++20, we are able to pass a <em>range</em> object such as <code>std::string</code> as argument instead of an iterator pair (as we do in C++17).</p>\n<p>And we have <code>std::isalnum()</code>, which is likely implemented as a lookup table like this (with the caveat that we need to be careful about signed <code>char</code>). It's more portable (the code we have will be wrong if there are non-alphabetic characters between <code>A</code> and <code>Z</code>, as there are on EBCDIC systems, for example) and easier to get right (witness the typo - <code>Z</code> instead of <code>z</code> - that means on ASCII-like systems we allow no lower-case letters).</p>\n<p>We could change the interface to just return the error string, with a null pointer indicating success, to avoid the "out" parameter.</p>\n<pre><code>#include <algorithm>\n#include <cctype>\n#include <string>\n \n// return a null pointer if valid, else a pointer to the error message\nconst char *check_username_valid(const std::string& str)\n{\n if (str.length() < MinUsernameLen) { return "Username Too Short"; }\n if (str.length() > MaxUsernameLen) { return "Username Too Long"; }\n auto const char_permitted\n = [](unsigned char c){ return c == '_' || std::isalnum(c); };\n\n if (std::all_of(str.begin(), str.end(), char_permitted)) {\n return nullptr;\n }\n\n return "Invalid Character in Username";\n}\n</code></pre>\n<p>If we'll be adding more permitted username characters, we might want to use the lookup-table approach - but we don't need a new type, and this <code>static const</code> can be built at compilation time:</p>\n<pre><code>#include <array>\n#include <climits>\n\nbool legal_username_char(unsigned char c)\n{\n static auto const table\n = []{\n std::array<bool,UCHAR_MAX+1> a;\n for (unsigned char i = 0; i++ < UCHAR_MAX; ) {\n a[i] = std::isalnum(i);\n }\n // additional non-alnum chars allowed\n a['_'] = true;\n return a;\n }();\n return table[c];\n}\n</code></pre>\n<p>That idiom is an <em>immediately-invoked lambda</em>, and it's very handy for creating complex constants like this. Note also the use of <code>UCHAR_MAX</code> rather than making assumptions about the size of the type.</p>\n<p>Minor: no need for cast to <code>int</code> when indexing (<code>a[int(((unsigned char)(x)))]</code>). An unsigned char is perfectly fine as array index.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:15:57.340",
"Id": "502236",
"Score": "0",
"body": "The problem with `isalnum` is that we may want to allow other characters which are allowed; e.g. a dot or hyphen or underscore, and then we end up with a long if statement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:20:08.643",
"Id": "502239",
"Score": "1",
"body": "Yes - though we can certainly use `std::isalnum()` to populate the lookup table instead of the fragile tests we have now, so we could have the benefit of both. It might end up being extracted as a reusable function - I'll perhaps update to suggest that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:23:25.773",
"Id": "502241",
"Score": "0",
"body": "That's a good idea, using isalnum to initialize... But what's the benefit of using a fake loop like `all_of` instead of just a vanilla for loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:30:40.850",
"Id": "502245",
"Score": "0",
"body": "How is `std::all_of()` \"fake\"? Its advantage is small here, but I think it does read slightly easier - the purpose is clear at the beginning of the expression, rather than only becoming clear once you're inside the loop. So a slight improvement in comprehension. It becomes clearer still in C++20 we we can pass the whole string as a *range* object. Plus, it's a reminder that the Standard Library provides lots of useful stuff!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T13:00:30.037",
"Id": "502429",
"Score": "0",
"body": "Thank you for this, I really like using a lambda to initialize the static lookup table. Thanks also for the insight regarding non ASCII encoding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T13:03:19.053",
"Id": "502431",
"Score": "0",
"body": "This is very opinionated, but in my view `all_of` encapsulates a 1-2 line for loop and thus doesn't make significant changes in readability or performance, but it tends to gravitate the style slightly towards something reminiscent of python or another scripting language, detracting from the procedural nature of the code. From a style point of view, I personally don't like it as I feel it adds little of value. Furthermore, given the choice between a completely standalone section of code vs one that makes an external function call, I have a very slight preference toward the standalone code."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T17:02:09.270",
"Id": "254658",
"ParentId": "254656",
"Score": "7"
}
},
{
"body": "<p>Everything Toby said.</p>\n<p>The only extra thing I want to mention is using <code>out</code> parameters is a bit archaic. You can easily return multiple values from a function.</p>\n<pre><code>std::pair<bool, std::string> check_username_valid(std::string const& str)\n{\n // STUFF\n return {false, "Bad Value"};\n // OR\n return {true, ""};\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T21:09:52.210",
"Id": "502273",
"Score": "0",
"body": "That could be the cleaner way to avoid the out parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T21:19:07.357",
"Id": "502274",
"Score": "0",
"body": "@TobySpeight Different, sure. More versatile, as the error-message may be dynamic? Also true. But cleaner? Debatable at best."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T21:26:05.227",
"Id": "502276",
"Score": "0",
"body": "Debatable, true; that's why I wrote \"could be\" rather than \"is\". :-) Definitely a technique to have in one's C++ toolbox, and upvoted for that alone."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:56:31.070",
"Id": "254662",
"ParentId": "254656",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "254658",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T16:07:23.400",
"Id": "254656",
"Score": "7",
"Tags": [
"c++",
"validation"
],
"Title": "Simple username validation"
}
|
254656
|
<p>I am trying to implement a Java version sub-string extractor with "start keyword" and "end keyword" and the extracted result is from (but excluded) the given start keyword to (but excluded) end keyword. The output sub-string follows the rules as below.</p>
<ul>
<li>The leading/trailing spaces in output sub-string is removed.</li>
<li>If the given start keyword is an empty string, it means that the anchor is at the start of the input string. Otherwise, the first occurrence of the given start keyword is an start anchor. If there is no any occurrence of the given start keyword, the output is an empty string.</li>
<li>If the given end keyword is an empty string, it means that the anchor is at the end of the input string. Otherwise, the first occurrence of the given end keyword is an end anchor. If there is no any occurrence of the given end keyword, the output is an empty string.</li>
<li>If the location of start anchor is after than the location of end anchor, or a part of the first occurrence of the given start keyword and a part of the first occurrence of the given end keyword are overlapped, the output is an empty string.</li>
</ul>
<p>The example input and output is listed as below.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">Input String</th>
<th style="text-align: center;">Start Keyword</th>
<th style="text-align: center;">End Keyword</th>
<th style="text-align: center;">Output</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">"dependencies"</td>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation"</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">"is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">"dependencies"</td>
<td style="text-align: center;">"is a class-based, object-oriented programming language that is designed to have as few implementation"</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"dependencies"</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">"as possible"</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"dependencies"</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"ABC"</td>
<td style="text-align: center;">""</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">""</td>
<td style="text-align: center;">"XYZ"</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"ABC"</td>
<td style="text-align: center;">"XYZ"</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
</tbody>
</table>
</div>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation is as below.</p>
<pre><code>private static String GetTargetString(String input, String startKeyword, String endKeyword)
{
if (!input.isEmpty() && input.indexOf(startKeyword) < 0) return "";
if (!input.isEmpty() && input.indexOf(endKeyword) < 0) return "";
int startIndex = startKeyword.isEmpty()
? 0
: input.indexOf(startKeyword) + startKeyword.length();
int endIndex = endKeyword.isEmpty()
? input.length()
: input.indexOf(endKeyword);
if (startIndex < 0 || endIndex < 0 || startIndex >= endIndex) return "";
return input.substring(startIndex, endIndex).trim();
}
</code></pre>
<p><strong>Test cases</strong></p>
<pre><code>String testString1 = "Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible";
System.out.println(GetTargetString(testString1, "", ""));
System.out.println(GetTargetString(testString1, "", "dependencies"));
System.out.println(GetTargetString(testString1, "Java", ""));
System.out.println(GetTargetString(testString1, "Java", "dependencies"));
System.out.println(GetTargetString(testString1, "dependencies", ""));
System.out.println(GetTargetString(testString1, "", "Java"));
System.out.println(GetTargetString(testString1, "dependencies", "Java"));
System.out.println(GetTargetString(testString1, "ABC", ""));
System.out.println(GetTargetString(testString1, "", "XYZ"));
System.out.println(GetTargetString(testString1, "ABC", "XYZ"));
System.out.println(GetTargetString(testString1, "Java", "Java"));
</code></pre>
<p>The output of the above test cases.</p>
<pre><code>Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible
Java is a class-based, object-oriented programming language that is designed to have as few implementation
is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible
is a class-based, object-oriented programming language that is designed to have as few implementation
as possible
</code></pre>
<p><a href="http://tpcg.io/dksuHStY" rel="nofollow noreferrer">Coding Ground Link</a></p>
<p>If there is any possible improvement, please let me know.</p>
|
[] |
[
{
"body": "<h1>Holes</h1>\n<p><code>GetTargetString("Where the start is before here.", "start", "here");</code> will return <code>""</code>, which seems wrong! Expected result would be <code>"is before"</code>.</p>\n<ul>\n<li>Should <code>"Where"</code> be a match for the ending keyword <code>"here"</code>? They are not the same word, so it doesn't seem to be really a <strong>keyword</strong> based extraction function.</li>\n<li>Perhaps you should look for the first ending keyword <strong>after</strong> the start, using <code>input.indexOf(endKeyword, startIndex)</code>? Or,</li>\n<li>Perhaps you want the last keyword? Ie, <code>input.lastIndexOf(endKeyword)</code></li>\n</ul>\n<h1>Code Review</h1>\n<h2>Naming</h2>\n<p>In Java, class names generally begin with an uppercase letter, and have mixed case for the rest of the name. This makes <code>GetTargetString</code> look like a class name instead of a method name.</p>\n<h2>Repeated Work</h2>\n<p><code>input.indexOf(startKeyword)</code> and <code>input.indexOf(endKeyword)</code> are called more than once. This is inefficient especially if the <code>input</code> is long and the word being searched for is short, or substrings of the needle occur often in the haystack.</p>\n<h2>Unnecessary Condition</h2>\n<p>The <code>endIndex < 0</code> test is unnecessary. Since you have tested <code>startIndex < 0</code>, when you test <code>startIndex >= endIndex</code>, you will know that <code>startIndex >= 0</code> so <code>startIndex >= endIndex</code> will always be true if <code>endIndex < 0</code>. That condition may safely be omitted.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T23:54:16.780",
"Id": "254673",
"ParentId": "254665",
"Score": "3"
}
},
{
"body": "<p>Just one point additionally to AJNeufeld's great post:</p>\n<p>You can avoid the duplicate <code>indexOf()</code> calls by simply removing the first two lines and checking <code>startIndex < startKeyword.length()</code> instead of <code>startIndex < 0</code> later on.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T22:39:21.593",
"Id": "254723",
"ParentId": "254665",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254673",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T20:23:50.173",
"Id": "254665",
"Score": "4",
"Tags": [
"java",
"strings"
],
"Title": "A Sub-string Extractor Implementation with Specific Keywords in Java"
}
|
254665
|
<p>I wrote some template function, which helps me with reading input from terminal, doing error handling, validating input.</p>
<p>The full code with template specialisation for strings looks like this:</p>
<pre><code>template <typename T>
T getInput(const std::string& prompt, std::istream& istream, std::ostream& ostream,
std::function<bool(T)> isValid = nullptr) {
T input;
while(true) {
ostream << prompt << "\n>> ";
if((istream >> input) && (!isValid || isValid(input)))
break;
if(istream)
continue;
istream.clear();
istream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
ostream << "Reading input failed, please try again!\n";
}
istream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return input;
}
template <>
inline std::string getInput<std::string>(const std::string& prompt, std::istream& istream, std::ostream& ostream,
std::function<bool(std::string)> isValid) {
std::string textInput;
while(true) {
ostream << prompt << "\n>> ";
if(std::getline(istream, textInput) && (!isValid || isValid(textInput)))
break;
if(istream)
continue;
ostream << "You probably entered EOF or exceeded the maximum text input size, please try again!\n";
istream.clear();
}
return textInput;
}
</code></pre>
<p>Some usage might look like this:</p>
<pre><code>getInput<double>("Enter positve number?", istream, ostream, [](const double input) {
bool correctInput = (input >= 0);
if(!correctInput)
ostream << "Number can only be greater than 0.\n";
return correctInput;
});
</code></pre>
<p>So the function works like this in a nutshell:</p>
<ul>
<li>Print Question</li>
<li>Read Input from command line</li>
<li>If not sucessfull (cin fails), print some generic error message and repeat</li>
<li>If sucessfull, call lambda validation function (if existent)</li>
<li>If input is valid return it, otherwise the lambda will print some specific error message and repeat</li>
</ul>
<p>So what I thought I need to test:</p>
<ul>
<li>Reading numbers without lambda function works and fails when expected (cin fails or not)</li>
<li>Reading numbers with lambda function works and fails when exspected (input valid or not)</li>
<li>The same just with strings (specialisation)</li>
</ul>
<p>So in sum 8 TestCases which I structured into two Scenarios: Read numeric input, read non-numeric input.</p>
<p>The whole Code looks like this (uses Catch2 as Unit Test Framework):</p>
<pre><code>using Catch::Matchers::Contains;
using Catch::Matchers::Matches;
SCENARIO("Read numeric input from command line") {
GIVEN("Some input and output stream") {
std::istringstream iss {};
std::ostringstream oss {};
WHEN("calling getInput<int> without valid function entering some non-numeric value") {
iss.str("42");
int input = getInput<int>("Some Question", iss, oss);
THEN("message is printed once and input returned") {
REQUIRE_THAT(oss.str(), Contains("Some Question"));
REQUIRE(input == 42);
}
}
WHEN("calling getInput<int> without valid function entering some non-numeric value") {
iss.str("String\n42");
int input = getInput<int>("Some Question", iss, oss);
THEN("error message is printed and question is repeated") {
REQUIRE_THAT(
oss.str(),
Matches("[\\s\\S]*Some Question[\\s\\S]*please try again[\\s\\S]*Some Question[\\s\\S]*"));
}
}
WHEN("calling getInput<int> with valid function entering some valid numeric input") {
iss.str("42");
int input = getInput<int>("Some Question", iss, oss, [](int value) { return value > 0; });
THEN("message is printed once and input returned") {
REQUIRE_THAT(oss.str(), Contains("Some Question"));
REQUIRE(input == 42);
}
}
WHEN("calling getInput<int> with valid function entering some invalid numeric input") {
iss.str("-20\n20");
int input = getInput<int>("Some Question", iss, oss, [](int value) { return value > 0; });
THEN("the question is repeated") {
REQUIRE_THAT(oss.str(), Matches("[\\s\\S]*Some Question[\\s\\S]*Some Question[\\s\\S]*"));
}
}
}
}
SCENARIO("Read text input from command line") {
GIVEN("Some input and output stream") {
std::istringstream iss {};
std::ostringstream oss {};
WHEN("calling getInput<std::string> without valid function entering some text") {
iss.str("Some input");
std::string input = getInput<std::string>("Some Question", iss, oss);
THEN("message is printed once and input returned") {
REQUIRE_THAT(oss.str(), Contains("Some Question"));
REQUIRE(input == "Some input");
}
}
WHEN("calling getInput<int> without valid function entering some non-numeric value") {
iss.str("String\nString");
iss.setstate(std::ios::failbit);
std::string input = getInput<std::string>("Some Question", iss, oss);
THEN("error message is printed and question is repeated") {
REQUIRE_THAT(
oss.str(),
Matches("[\\s\\S]*Some Question[\\s\\S]*please try again[\\s\\S]*Some Question[\\s\\S]*"));
}
}
WHEN("calling getInput<int> with valid function entering some valid text input") {
iss.str("Some input");
std::string input = getInput<std::string>("Some Question", iss, oss,
[](std::string value) { return value.length() >= 3; });
THEN("message is printed once and input returned") {
REQUIRE_THAT(oss.str(), Contains("Some Question"));
REQUIRE(input == "Some input");
}
}
WHEN("calling getInput<int> with valid function entering some invalid text input") {
iss.str("a\nabc");
std::string input = getInput<std::string>("Some Question", iss, oss,
[](std::string value) { return value.length() >= 3; });
THEN("the question is repeated") {
REQUIRE_THAT(oss.str(), Matches("[\\s\\S]*Some Question[\\s\\S]*Some Question[\\s\\S]*"));
}
}
}
}
</code></pre>
<p>My ideas how to test it:</p>
<ul>
<li>Mock input and output by using stringstreams</li>
<li>In success cases check that input is correctly (obviously) and that question was in fact asked (Not to sure if one would do that ... but I thought this is something I expect from the method, so why not test it)</li>
<li>In failure cases, check if question was asked twice (to test whether the user is asked again for input) and possibly check if some error message is printed if it's expected (-> cin fails)</li>
</ul>
<p>In general I'm happy for any suggestion. But just to list some things / questions in particular, where I would love to get feedback:</p>
<ul>
<li>Are my Scenarios / test cases good chosen, i.e. is the structure good</li>
<li>Can my wording be improved. I don't mean specific language errors here, but rather if the content is good. So for example that I need fake streams here doesn't seems so relevant. Mainly because I just need them to make the function testable. Without tests, I wouldn't need them. But in this case, there would be nothing else that I need in the given part (usually for classes you would need at least the object with some properties set)</li>
<li>Is the code in the right place, for example I wondered whether the <code>iss.str()</code> part shouldn't be in the "GIVEN" rather as I usually configure mocks there. But the concrete values for mocks depend here on my THEN, which makes it clearer to me to put them inside the THEN.</li>
<li>Are my Asserts any good? I had particular problems to test my failure cases as in these case, the function enters the while loop. So I always had to mock the stream, so it would fail first and then pass, which seemed a little bit weird to me. Furthermore it wasn't to easy to assert that behaviour then.</li>
</ul>
<p>As said, if you see other improvements please show me them as well :)</p>
<p>Thanks for your valuable feedback!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T20:29:07.780",
"Id": "254666",
"Score": "2",
"Tags": [
"c++",
"unit-testing"
],
"Title": "Unit Test template function with terminal input"
}
|
254666
|
<p>Hello guys could you help me please how to render this code as OOP?</p>
<p>I want to improve this code and follow the OOP anyone could help me, please</p>
<p>thank you in advance</p>
<p>this is class Expression</p>
<pre><code>class Expression {
public int type;
public int value;
public Expression leftOp;
public Expression rightOp;
public Expression(int type, int value, Expression leftOp, Expression rightOp) {
this.type = type;
this.value = value;
this.leftOp = leftOp;
this.rightOp = rightOp;
}
}
class Arith {
/** Constantes pour representer les types */
public static final int TYPE_NUMBER = 1;
public static final int TYPE_SUM = 2;
public static final int TYPE_PROD = 3;
public static void main(String[] args) {
Expression term = new Expression(TYPE_SUM, 0, new Expression(TYPE_NUMBER, 3, null, null), new Expression(
TYPE_PROD, 0, new Expression(TYPE_NUMBER, 2, null, null), new Expression(TYPE_NUMBER, 5, null, null)));
System.out.println(evaluate(term));
}
/** Evalue recursivement the expression */
public static int evaluate(Expression term) {
switch (term.type) {
case TYPE_NUMBER:
return term.value;
case TYPE_SUM:
return evaluate(term.leftOp) + evaluate(term.rightOp);
case TYPE_PROD:
return evaluate(term.leftOp) * evaluate(term.rightOp);
default:
return 0;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T02:03:47.360",
"Id": "502294",
"Score": "0",
"body": "Can you explain what this does?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T08:09:03.947",
"Id": "502314",
"Score": "0",
"body": "Hi @Reinderien thank you for yiour feedback,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T08:10:43.223",
"Id": "502315",
"Score": "0",
"body": "the code construct the expression 3 + 2 * 5 and display the result in the terminal the value 13"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T10:28:09.283",
"Id": "502324",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>The basic structure isn't bad, but is more structured programming in the C or PASCAL tradition than OOP.</p>\n<h2>OOP discussion</h2>\n<p>You currently have three types of expressions that need different evaluation behaviour, but use only one class <code>Expression</code>. You implement this differing behaviour in your main class, using a <code>switch</code> on a type code.</p>\n<p>Instead, make <code>Expression</code> an interface (or a super class if you aren't comfortable yet with interfaces) with an <code>evaluate()</code> method, and three classes implementing that interface: <code>NumberExpression</code>, <code>SumExpression</code>, and <code>ProductExpression</code>, each with its own way of doing the <code>evaluate()</code> method, with its own fields, and its own constructor (using only the parameters necessary to that type of expression).</p>\n<p>Then, there's no need for a type code any more. The Java OOP system does the switch for you. The evaluation of an expression happens where it should happen, in the expression's own class, and you can eliminate the main <code>evaluate()</code> method. And it's totally easy to create additional expression types like difference, quotient or power. You just add another class.</p>\n<p>The main idea of OOP is that an object's behaviour should be implemented in the corresponding class, especially if the behaviour depends on something you'd call a type.</p>\n<h2>Minor points</h2>\n<p>The type code you are currently using (if it weren't made obsolete by the OOP refactoring) should not be a list of integer constants, but become an <code>enum</code>.</p>\n<p>Avoid <code>public</code> fields, make them <code>private</code>, and if really needed, create getter and setter methods. Fields represent some internal state of an object, and nobody outside should manipulate that state, or even have any assumptions on the inner workings of a class. Communication should only happen by calling public methods. (Fields can be viewed as private sticky notes of some clerk, they're not meant to be seen or modified by anybody else, and even asking this clerk about one of these notes seems like bad habit.)</p>\n<p>If you have distinct cases how to create instances of a class, create multiple constructors. Your single <code>Expression</code> constructor is a "one-size-fits-all" one. When creating a constant number, you still have to supply two irrelevant <code>Expression</code>s (given as <code>null</code> in your example), and when creating a sum or a product, you are forced to provide an equally irrelevant <code>value</code> parameter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T10:01:55.600",
"Id": "254693",
"ParentId": "254668",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T21:57:50.937",
"Id": "254668",
"Score": "0",
"Tags": [
"java"
],
"Title": "JAVA OOP concept issue"
}
|
254668
|
<h1>Context</h1>
<p>Further to <a href="https://codereview.stackexchange.com/questions/253841/c-rate-controller">this question</a> there was some discussion regarding "circular buffer" vs "time_slice" approach to rate control.</p>
<p>So I worked up this simple multi-threaded client / server simulation as a testing harness.</p>
<ol>
<li>Usual coding style feedback please</li>
<li>Does this allow us to answer the question of "is timeslice good enough or do we need circular buffer". - could easily substitute the circular buffer rate_controller from answer in above question for comparison</li>
</ol>
<p>My proposed answer is: If there are signifcant clients (> 50?) then statistics smooth things out to the point where you can't tell the difference.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <chrono>
#include <iostream>
#include <mutex>
#include <random>
#include <thread>
namespace os {
class server {
public:
void req(char ch) {
std::lock_guard<std::mutex> lg(mut);
std::cout << ch << std::flush; // visual representation of making a server request
}
private:
std::mutex mut; // only one shared server instace, must ensure thread-safe access
};
class rate_controller {
using clk_t = std::chrono::system_clock;
public:
rate_controller(unsigned limit, long time_slice_ms, long rnd_offset_ms)
: n_(limit), time_slice_ms_(time_slice_ms), rnd_offset_ms_(rnd_offset_ms) {}
bool check() {
auto duration_since_epoch = clk_t::now().time_since_epoch();
long curr_time_slice =
(rnd_offset_ms_ +
std::chrono::duration_cast<std::chrono::milliseconds>(duration_since_epoch).count()) /
time_slice_ms_; // intentional integer division
if (curr_time_slice != last_time_slice_) {
last_time_slice_ = curr_time_slice;
count_ = 0;
}
++count_;
return (count_ <= n_);
}
private:
unsigned n_;
long time_slice_ms_;
long rnd_offset_ms_;
long last_time_slice_ = 0;
unsigned count_ = 0;
;
};
class client {
public:
explicit client(server& s, char ch) : s_(s), ch_(ch) {}
void run() {
using std::chrono::milliseconds;
using std::this_thread::sleep_for;
for (int i = 0; i < 100; ++i) {
if (in_burst) {
sleep_for(milliseconds(in_burst_delay_dist(reng)));
if (burst_prob_dist(reng) < 10) in_burst = false;
} else {
sleep_for(milliseconds(out_of_burst_delay_dist(reng)));
if (burst_prob_dist(reng) < 20) in_burst = true;
}
// wait until our rate controller permits this request. / 20 => 5% "accuracy".
while (!rc.check()) sleep_for(milliseconds(time_slice_ms / 20));
s_.req(ch_);
}
}
private:
std::mt19937 reng{std::random_device{}()};
std::uniform_int_distribution<int> in_burst_delay_dist{1, 1000};
std::uniform_int_distribution<int> out_of_burst_delay_dist{1, 50};
std::uniform_int_distribution<int> burst_prob_dist{1, 100};
const long time_slice_ms = 200;
rate_controller rc{1, time_slice_ms, std::uniform_int_distribution<long>{0, time_slice_ms}(reng)};
server& s_;
char ch_;
bool in_burst = false;
};
struct worker {
explicit worker(server& s, char ch) : c(s, ch), t([this]() { this->c.run(); }) {}
client c;
std::thread t;
};
} // namespace os
int main() {
constexpr int max_workers = 10 + 26 + 26;
// compile time construction of some one character thread indentifiers
// rather than a messy literal array initiliaser list
constexpr std::array<char, max_workers> thread_ids = []() {
auto cs = decltype(thread_ids){};
int i = 0;
for (int c = '0'; c <= '9'; ++c) cs[i++] = c;
for (int c = 'A'; c <= 'Z'; ++c) cs[i++] = c;
for (int c = 'a'; c <= 'z'; ++c) cs[i++] = c;
return cs;
}();
using os::server, os::worker;
server serv;
std::vector<worker> workers;
workers.reserve(max_workers);
for (int i = 0; i < max_workers; ++i) workers.emplace_back(serv, thread_ids[i]);
for (auto& w: workers) w.t.join();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T01:48:05.420",
"Id": "502292",
"Score": "1",
"body": "Haven't checked your code but from what I understood, it is clearly preferable to use time slice approach. There is no need to be perfectly accurate with the type of task you need to perform - so circular buffer is an overkill. Also, in case you desire better accuracy you can increase resolution of a time slice and keep track of slices accounting the last millisecond and use their average to compute the rate. It is a kind of merge between circular buffer and simple time slice that is both accurate doesn't take too much resources."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T08:26:33.590",
"Id": "502318",
"Score": "0",
"body": "@ALX23z Yes, exactly, that was my understanding too."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T22:42:51.347",
"Id": "254670",
"Score": "0",
"Tags": [
"c++",
"multithreading"
],
"Title": "Multi-threaded client/server/rate_controller testing harness"
}
|
254670
|
<p>I need a queue in C for an embedded application in which I cannot allocate memory dynamically.</p>
<p>I avoided using <code>void*</code> for the queue elements (which is not convenient lifecycle-wise) by having the user provide their underlying array.</p>
<p><code>user_code.c</code>:</p>
<pre><code>#include "generic_queue.c"
typedef struct custom_t
{
/* whatever */
} custom_t;
custom_t underlying_array[5];
queue_t queue;
queue_init(&queue, underlying_array, 5, sizeof(custom_t));
/* now use queue to do stuff */
queue_destroy(&queue);
</code></pre>
<p><code>generic_queue.h</code>:</p>
<pre><code>#ifndef INCLUDE_GUARD_GENERIC_QUEUE_H
#define INCLUDE_GUARD_GENERIC_QUEUE_H
#include <stddef.h>
#include <stdbool.h>
#include <pthread.h>
typedef struct queue_t
{
void* array;
size_t capacity;
size_t sizeof_element;
size_t in;
size_t out;
pthread_mutex_t mutex;
} queue_t;
/* return true on success */
bool queue_init(queue_t* queue, void* array, size_t capacity, size_t sizeof_element);
void queue_destroy(queue_t* queue);
bool queue_front(queue_t * queue, void *dest);
bool queue_back(queue_t * queue, void *dest);
bool queue_push(queue_t *queue, void const *src);
bool queue_pop(queue_t *queue, void *dest);
/* assert on failure */
size_t queue_size(queue_t * queue);
size_t queue_capacity(queue_t * queue);
bool queue_empty(queue_t * queue);
bool queue_full(queue_t * queue);
#endif /* INCLUDE_GUARD_GENERIC_QUEUE_H */
</code></pre>
<p><code>genric_queue.c</code>:</p>
<pre><code>#include "generic_queue.h"
#include <stddef.h>
#include <stdbool.h>
#include <string.h> /* memcpy */
#include <assert.h>
#include <pthread.h>
bool queue_init(queue_t* queue, void* array, size_t capacity, size_t sizeof_element)
{
bool success;
if ((queue == NULL) || (array == NULL) || (capacity < 2) || (sizeof_element == 0))
{
success = false;
}
else
{
pthread_mutex_init(&queue->mutex, NULL);
pthread_mutex_lock(&queue->mutex);
queue->array = array;
queue->capacity = capacity;
queue->sizeof_element = sizeof_element;
queue->in = 0;
queue->out = 0;
success = true;
pthread_mutex_unlock(&queue->mutex);
}
return success;
}
void queue_destroy(queue_t* queue)
{
pthread_mutex_destroy(&queue->mutex);
queue->array = NULL;
queue->capacity = 0;
queue->sizeof_element = 0;
queue->in = 0;
queue->out = 0;
}
static void* index_to_address(queue_t const * queue, size_t index)
{
void* address;
assert(queue != NULL);
/* No mutex here: this is an internal utility function */
address = ((unsigned char*)queue->array) + (index * queue->sizeof_element);
return address;
}
static bool queue_empty_internal(queue_t * queue, bool lock_mutex)
{
bool empty;
assert(queue != NULL);
if (lock_mutex) { pthread_mutex_lock(&queue->mutex); }
empty = (queue->in == queue->out);
if (lock_mutex) { pthread_mutex_unlock(&queue->mutex); }
return empty;
}
bool queue_empty(queue_t * queue)
{
return queue_empty_internal(queue, true);
}
/* When used internally, mutex might be already locked, so an additional "private" `lock_mutex` argument is needed */
static bool queue_front_internal(queue_t * queue, void *dest, bool lock_mutex)
{
bool success;
void *src;
if ((queue == NULL) || (queue_empty_internal(queue, lock_mutex)) || (dest == NULL))
{
success = false;
}
else
{
if (lock_mutex) { pthread_mutex_lock(&queue->mutex); }
src = index_to_address(queue, queue->out);
memcpy(dest, src, queue->sizeof_element);
success = true;
if (lock_mutex) { pthread_mutex_unlock(&queue->mutex); }
}
return success;
}
bool queue_front(queue_t * queue, void *dest)
{
return queue_front_internal(queue, dest, true);
}
bool queue_back(queue_t * queue, void *dest)
{
bool success;
size_t index;
void *src;
if ((queue == NULL) || (queue_empty(queue)) || (dest == NULL))
{
success = false;
}
else
{
pthread_mutex_lock(&queue->mutex);
index = (queue->in == 0) ? queue->capacity - 1 : queue->in - 1;
src = index_to_address(queue, index);
memcpy(dest, src, queue->sizeof_element);
success = true;
pthread_mutex_unlock(&queue->mutex);
}
return success;
}
bool queue_push(queue_t *queue, void const *src)
{
bool success;
void *dest;
if ((queue == NULL) || (queue_full(queue)) || (src == NULL))
{
success = false;
}
else
{
pthread_mutex_lock(&queue->mutex);
dest = index_to_address(queue, queue->in);
memcpy(dest, src, queue->sizeof_element);
queue->in = (queue->in + 1) % queue->capacity;
success = true;
pthread_mutex_unlock(&queue->mutex);
}
return success;
}
bool queue_pop(queue_t *queue, void *dest)
{
bool success;
if ((queue == NULL) || (queue_empty(queue)))
{
success = false;
}
else
{
pthread_mutex_lock(&queue->mutex);
if (dest != NULL)
{
queue_front_internal(queue, dest, false);
}
queue->out = (queue->out + 1) % queue->capacity;
success = true;
pthread_mutex_unlock(&queue->mutex);
}
return success;
}
size_t queue_size(queue_t * queue)
{
size_t size;
assert(queue != NULL);
pthread_mutex_lock(&queue->mutex);
if (queue->out <= queue->in)
{
size = queue->in - queue->out;
}
else
{
size = queue->in + queue->capacity - queue->out;
}
pthread_mutex_unlock(&queue->mutex);
return size;
}
size_t queue_capacity(queue_t * queue)
{
size_t capacity;
assert(queue != NULL);
pthread_mutex_lock(&queue->mutex);
capacity = queue->capacity - 1;
pthread_mutex_unlock(&queue->mutex);
return capacity;
}
bool queue_full(queue_t * queue)
{
bool full;
assert(queue != NULL);
pthread_mutex_lock(&queue->mutex);
full = (((queue->in + 1) % queue->capacity) == queue->out);
pthread_mutex_unlock(&queue->mutex);
return full;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T00:31:59.703",
"Id": "502289",
"Score": "0",
"body": "Sorry, but VTC. This question is not about a code review, but a design review. It likely belong to SO. That said, there are quite a few design flaws here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T01:58:52.183",
"Id": "502293",
"Score": "0",
"body": "I think if the full implementations were shown this could be brought on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T02:54:18.147",
"Id": "502296",
"Score": "0",
"body": "@vnp implementation added."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T04:05:31.000",
"Id": "502386",
"Score": "0",
"body": "@vnp Refactored. I think now it is less of a design review and more of a code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T08:32:31.787",
"Id": "503151",
"Score": "0",
"body": "What's your target system that does support pthreads but doesn't allow heap allocation? Doesn't sound like any existing system out there. Pthread = POSIX threads, POSIX = Portable (hosted) Operating System Interface. There exist no hosted OS that doesn't allow heap allocation. So what you really need is to review the requirement spec that lead you to write this code, before anything else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T13:17:03.933",
"Id": "503179",
"Score": "1",
"body": "@Lundin the limitation comes from coding standards for safety critical applications, not the target system itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T13:27:55.897",
"Id": "503182",
"Score": "0",
"body": "@Sparkler Okay... Now as it turns out, coding standards for safety-critical applications happens to be one of my areas of expertise. The majority of the libs you use here are outright banned from safety critical applications. Pthreads are also very unlikely to be allowed. This code overall doesn't look particularly MISRA-C compliant. And generic programming is a complete no-go in safety-critical systems, they need to be 100% deterministic. So overall you need consider if this code should actually be used for safety-critical applications or just for some manner of PC."
}
] |
[
{
"body": "<p>Your code looks quite nice. I especially like that you have a very consistent API with clear names that follow the conventions of the C++ STL, and the pointer to the queue always as the first parameter. That said, there are some possible improvements.</p>\n<h1>Naming things</h1>\n<p>I would use <code>queue_init()</code> and <code>queue_exit()</code> here. Alternatively, use <code>queue_create()</code> and <code>queue_destroy()</code>, however I would use those names only if those actually allocated/freed a <code>queue_t</code>.</p>\n<p>Instead of <code>sizeof_element</code> I would write write <code>element_size</code>, or perhaps just <code>size</code>, as the latter is already used in a similar way in standard C functions like <a href=\"https://en.cppreference.com/w/c/algorithm/qsort\" rel=\"nofollow noreferrer\"><code>qsort()</code></a>.</p>\n<p>I would also use <code>head</code> and <code>tail</code> instead of <code>in</code> and <code>out</code>.</p>\n<h1>Be consistent using <code>if</code> or <code>assert()</code></h1>\n<p>Some functions use an <code>if</code>-statement to check if parameters are valid, others just use <code>assert()</code>. Be consistent and always use the same method for a given parameter, like <code>queue</code>. And also make sure that if one function checks it, all of them. For example, <code>queue_destroy()</code> fails to check whether <code>queue</code> is <code>NULL</code>.</p>\n<p>I advice you to use <code>assert()</code> for catching programming errors, and <code>if</code>-statements to catch runtime errors. I would consider <code>queue</code> being <code>NULL</code> a programming error. However, trying to insert into a full queue would be a runtime error, since what we put into a queue is most likely something we did not know up front when writing the program. The exception would be <code>queue_destroy()</code>, where I would use an <code>if</code>-statement to check for <code>NULL</code>, as this matches what <code>free()</code> does.</p>\n<p>Did you consider checking the return value of <code>pthread_mutex_init()</code> and <code>pthread_mutex_lock()</code>? It so happens that in your code, you can avoid checking that, since you are not using recursive mutexes, but if you didn't know that, you should have either written <code>if</code>-statements to check whether these functions succeeded, or have read their manual pages to check whether they could fail.</p>\n<h1>Handle corner cases if possible</h1>\n<p>While it seems rather silly, there is no reason not to allow a queue of size 0 or 1, and elements of size 0. Handling corner cases correctly makes your code more robust.</p>\n<p>Related to this:</p>\n<h1>Allow the whole queue to be used</h1>\n<p>You allow one less element in the queue than the capacity you pass to <code>queue_init()</code>. In fact:</p>\n<pre><code>int array[10];\nqueue_t queue;\nqueue_init(&queue, array, 10, sizeof(int));\nint capacity = queue_capacity(queue); // will be 9!\n</code></pre>\n<p>Most likely you did this to work around the ambiguity when <code>in == out</code>. However, you can work around this by not having two indices into the array, but rather one offset and one count of the number of elements in the queue.</p>\n<h1>Use <code>const</code> whereever it is possible</h1>\n<p>You should mark parameters as <code>const</code> whenever it is possible to do so. For example, <code>queue_empty()</code> does not modify the queue at all, so the parameter <code>queue</code> should be a <code>const queue_t *</code>.</p>\n<h1>Avoid locking the mutex unnecessarily</h1>\n<p>There is no need to lock the mutex in <code>queue_capacity()</code>, as the capacity should never change between <code>queue_init()</code> and <code>queue_destroy()</code>.</p>\n<h1>Make a clear distinction between locked and unlocked functions</h1>\n<p>Instead of having a <code>queue_empty_internal()</code> that takes a parameter whether to lock the mutex or not, I would write a <code>queue_empty_unlocked()</code> that never locks, and then make sure <code>queue_empty()</code> takes the lock itself before calling <code>queue_empty_unlocked()</code>. I would make it so that all user visible API functions take the lock, and all internal functions not take locks.</p>\n<h1>Consider returning a pointer instead of copying an element</h1>\n<p>Instead of <code>queue_front()</code> returning a <code>bool</code> and copying the contents to <code>dest</code>, I would rather have it return a pointer to the front element, or return <code>NULL</code> if the queue is empty. This is especially useful if the elements are very large, or if you want to modify an element that is in the queue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T23:00:58.790",
"Id": "503229",
"Score": "0",
"body": "\"use head and tail instead of in and out\" --> \"in\" and \"out\" is quite clear. With \"head/tail\" food goes in near head come out near tail or was it the head of the line is the eldest in the queue and next to come out and stuff goes in the tail or ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T02:43:56.713",
"Id": "503238",
"Score": "0",
"body": "I had to remove the const because of the mutex"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T22:29:22.833",
"Id": "255115",
"ParentId": "254671",
"Score": "2"
}
},
{
"body": "<p>Not much to add to the good code and the good review of <a href=\"https://codereview.stackexchange.com/a/255115/29485\">@G. Sliepen</a></p>\n<p><strong>No error checking of <code>pthread_mutex...()</code> calls</strong></p>\n<p>I'd expect return values checked.</p>\n<p><strong>Consider an <code>apply()</code> function</strong></p>\n<p>Consider a function that applies a function to each queue element. Maybe ending early if an error detected.</p>\n<pre><code>bool queue_apply(queue_t * queue, int (*apply)(void *state, void *ellement), void * state);\n</code></pre>\n<p>Useful for printing and others tasks.</p>\n<p><strong>Some functional documentation in the <code>*.h</code></strong></p>\n<p>Consider a user should get an idea of code use just by looking at the .h file. Example: It is unclear what the below do. I recommend at least a one line descripting for each function and an over description for the set.</p>\n<pre><code>bool queue_front(queue_t * queue, void *dest);\nbool queue_back(queue_t * queue, void *dest);\n</code></pre>\n<p><strong>Alternative style</strong></p>\n<p>Consider this style <a href=\"https://en.wikipedia.org/wiki/C2x#Features\" rel=\"nofollow noreferrer\"> order of parameters in function declarations should be arranged such that the size of an array appears before the array</a></p>\n<pre><code>// bool queue_init(queue_t* queue, void* array, size_t capacity, size_t sizeof_element);\nbool queue_init(queue_t* queue, size_t capacity, void* array, size_t sizeof_element);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T22:57:48.747",
"Id": "255118",
"ParentId": "254671",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "255115",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T22:45:22.887",
"Id": "254671",
"Score": "4",
"Tags": [
"c",
"thread-safety",
"queue",
"embedded",
"variant-type"
],
"Title": "Type agnostic, statically allocated, thread-safe queue in C"
}
|
254671
|
<p>I am trying to emulate Java 8's <a href="https://www.baeldung.com/java-predicate-chain" rel="nofollow noreferrer">predicate chaining</a> in JavaScript.</p>
<p>So far it works, but is there a more efficient way to write this? Furthermore, I had to create <code>get</code> and <code>run</code> methods to return the predicate so that is can be passed into a <code>filter</code> function.</p>
<p><strong>Update:</strong> I added an <code>_unwrap</code> method to unwrap the internal predicate function so that you can pass a <code>Predicate</code> to another <code>Predicate</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const records = [
{ name: 'Andrew' , age: 21, position: 'Developer' },
{ name: 'Bill' , age: 26, position: 'Developer' },
{ name: 'Chris' , age: 45, position: 'Manager' },
{ name: 'Dave' , age: 30, position: 'Developer' },
{ name: 'Eric' , age: 32, position: 'Manager' }
];
class Predicate {
constructor(predicateFn) {
this.predicateFn = this._unwrap(predicateFn);
}
/* @private */ _unwrap(predicateFn) {
return predicateFn instanceof Predicate ? predicateFn.get() : predicateFn;
}
and(predicateFn) {
return new Predicate((item) => this.predicateFn(item) && this._unwrap(predicateFn)(item));
}
or(predicateFn) {
return new Predicate((item) => this.predicateFn(item) || this._unwrap(predicateFn)(item));
}
not() {
return new Predicate((item) => !this.predicateFn(item));
}
get() {
return this.predicateFn;
}
run(arr) {
return arr.filter(this.predicateFn);
}
}
const display = ({ name, age, position }) => `${name} (${age}) [${position}]`;
const ageOver21AndDeveloper = new Predicate(({ age }) => age > 21)
.and(({ position }) => position === 'Developer');
console.log(ageOver21AndDeveloper.run(records).map(display).join(', '));
const billOrManager = new Predicate(({ name }) => name === 'Bill')
.or(({ position }) => position === 'Manager');
console.log(billOrManager.run(records).map(display).join(', '));
const notUnder30 = new Predicate(({ age }) => age < 30).not();
console.log(notUnder30.run(records).map(display).join(', '));
// Pass predicate object to another predicate.
console.log(billOrManager.or(ageOver21AndDeveloper).run(records).map(display).join(', '));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { top: 0; max-height: 100% !important; }</code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>I believe you could retain the same level of flexibility without managing extra objects by using higher order functions. This also has the advantage of treating the predicates as functions and nothing more.</p>\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 records = [\n { name: 'Andrew' , age: 21, position: 'Developer' },\n { name: 'Bill' , age: 26, position: 'Developer' },\n { name: 'Chris' , age: 45, position: 'Manager' },\n { name: 'Dave' , age: 30, position: 'Developer' },\n { name: 'Eric' , age: 32, position: 'Manager' }\n];\n\nconst display = ({ name, age, position }) =>\n `${name} (${age}) [${position}]`;\n\nconst not = condition => (...args) => !condition(...args);\n\nconst and = (...conditions) => (...args) =>\n conditions.reduce(\n (a,b)=>a&&b(...args),true\n )\n\nconst or = (...conditions) => (...args) =>\n conditions.reduce(\n (a,b)=>a||b(...args),false\n )\n\nconst ageOver21 = ({age}) => age > 21\nconst isDeveloper = ({position}) => position === 'Developer';\nconst ageOver21AndIsDeveloper = and(ageOver21,isDeveloper);\n\nconsole.log(records.filter(ageOver21AndIsDeveloper).map(display).join(', '));\n\nconst billOrManager = or(\n ({name}) => name === 'Bill',\n ({position}) => position === 'Manager'\n)\n\nconsole.log(records.filter(billOrManager).map(display).join(', '));\n\nconst notUnder30 = not(({ age }) => age < 30)\n\nconsole.log(records.filter(notUnder30).map(display).join(', '));\n\nconsole.log(\n records.filter(\n or(billOrManager,ageOver21AndIsDeveloper)\n )\n .map(display).join(', ')\n);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T03:34:46.883",
"Id": "254680",
"ParentId": "254675",
"Score": "1"
}
},
{
"body": "<p>You could avoid the unwrap logic by emulating a callable object. This is done by creating a function and attaching members to it. Your predicate class will then boil down to this small chunk of code:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const predicate = fn => (\n Object.assign((...args) => fn(...args), {\n and: otherFn => predicate(value => fn(value) && otherFn(value)),\n or: otherFn => predicate(value => fn(value) || otherFn(value)),\n not: () => predicate(value => !fn(value)),\n run: arr => arr.filter(fn),\n })\n);\n</code></pre>\n<p>In this example, I'm first taking the passed-in function, copying it with <code>(...args) => fn(...args)</code> (this is done so we don't modify the original parameter), then assigning a bunch of functions to it with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"nofollow noreferrer\">Object.assign()</a>.</p>\n<p><strong>Full Example</strong></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const records = [\n { name: 'Andrew' , age: 21, position: 'Developer' },\n { name: 'Bill' , age: 26, position: 'Developer' },\n { name: 'Chris' , age: 45, position: 'Manager' },\n { name: 'Dave' , age: 30, position: 'Developer' },\n { name: 'Eric' , age: 32, position: 'Manager' }\n];\n\nconst predicate = fn => (\n Object.assign((...args) => fn(...args), {\n and: otherFn => predicate(value => fn(value) && otherFn(value)),\n or: otherFn => predicate(value => fn(value) || otherFn(value)),\n not: () => predicate(value => !fn(value)),\n run: arr => arr.filter(fn),\n })\n);\n\nconst display = ({ name, age, position }) => `${name} (${age}) [${position}]`;\n\nconst ageOver21AndDeveloper = predicate(({ age }) => age > 21)\n .and(({ position }) => position === 'Developer');\n\nconsole.log(ageOver21AndDeveloper.run(records).map(display).join(', '));\n\nconst billOrManager = predicate(({ name }) => name === 'Bill')\n .or(({ position }) => position === 'Manager');\n\n// In this example we're letting billOrManager get called directly instead of using the .run() function\nconsole.log(records.filter(billOrManager).map(display).join(', '));\n\nconst notUnder30 = predicate(({ age }) => age < 30).not();\n\nconsole.log(notUnder30.run(records).map(display).join(', '));\n\n// Pass predicate object to another predicate.\nconsole.log(billOrManager.or(ageOver21AndDeveloper).run(records).map(display).join(', '));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T04:28:30.457",
"Id": "254779",
"ParentId": "254675",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T00:48:07.123",
"Id": "254675",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Emulate Java 8 predicate chaining in JavaScript"
}
|
254675
|
<blockquote>
<p>The four adjacent digits in the 1000-digit number that have the
greatest product are 9 × 9 × 8 × 9 = 5832.</p>
<p>73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450</p>
<p>Find the thirteen adjacent digits in the 1000-digit number that have
the greatest product. What is the value of this product?</p>
</blockquote>
<p>This is my solution to the problem above.</p>
<pre><code>> def largest_product_series(n, series):
> series = str(series)
> largest = 0
> for i in range(0,1000-n):
> temp = np.prod([int(series[j]) for j in range(i,n+i)])
> largest = max(temp, largest)
> return largest
</code></pre>
<p>I am having a hard time figuring out what is wrong with my code. It works just fine with n = 4. But somehow it didn't output the correct answer when n = 13.</p>
<p>Here's the link to the problem. <a href="https://projecteuler.net/problem=8" rel="nofollow noreferrer">Euler 8</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T02:50:45.687",
"Id": "502295",
"Score": "5",
"body": "Since that's a bug, shouldn't this question go on stackoverflow? Anyway, consider that the product of 13 digits could be larger than 2 billion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T03:31:04.853",
"Id": "502297",
"Score": "1",
"body": "Are you sure it doesn’t work? It gives the number 23514624000 which I’m reading is the correct answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T13:37:52.703",
"Id": "502333",
"Score": "1",
"body": "Is the solution passing the tests on the website?"
}
] |
[
{
"body": "<p>I think your current code is working- it seems like it’s getting the same answer as other people who say they solved it (i.e. 23514624000). So I think it belongs here.</p>\n<p>Right now, if you wanted to use this for any string of digits and any length of consecutive numbers, it would be <span class=\"math-container\">\\$O(n^2)\\$</span> time complexity because you would have to multiply at most (length-of-series / 2) * (length-of-series / 2) numbers. Something you could use to fix that is a deque from the collections module. You could use it to know what to divide and what to multiply to get the current product, and you could also use it to track how many zeros are in the current sequence of consecutive numbers. If you do this then you only need to multiply or divide at most (length-of-series * 2) - 1 numbers, so it’s <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import collections\n\ndef find_max_prod(n, series):\n \n if len(series) < n:\n return 0\n \n current_nums = collections.deque(maxlen=n)\n zero_count = 0\n max_prod = 1\n my_iter = iter(series)\n \n for _ in range(n):\n next_n = int(next(my_iter))\n max_prod *= next_n\n current_nums.append(next_n)\n if next_n == 0:\n zero_count += 1\n\n current_prod = max_prod if max_prod > 0 else 1\n \n for str_n in my_iter:\n n_out = current_nums.popleft()\n n_in = int(str_n)\n current_nums.append(n_in)\n if n_in == 0:\n zero_count += 1\n if n_out == 0:\n zero_count -= 1\n else:\n current_prod //= n_out\n if n_in != 0:\n current_prod *= n_in\n if current_prod > max_prod and zero_count == 0:\n max_prod = current_prod\n \n return max_prod\n</code></pre>\n<p>or with Toby Speight‘s suggestion:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import collections\n\ndef max_of_substr(n, substr):\n current_nums = collections.deque(maxlen=n)\n my_iter = iter(substr)\n max_prod = 1\n \n for _ in range(n):\n next_n = int(next(my_iter))\n max_prod *= next_n\n current_nums.append(next_n)\n \n current_prod = max_prod\n\n for str_n in my_iter:\n n_out = current_nums.popleft()\n n_in = int(str_n)\n current_nums.append(n_in)\n current_prod //= n_out\n current_prod *= n_in\n if current_prod > max_prod:\n max_prod = current_prod\n \n return max_prod\n\ndef find_max_prod(n, series):\n max_substr_generator = (\n max_of_substr(n, substr)\n for substr in series.split('0')\n if len(substr) >= n\n )\n return max(max_substr_generator, default=0)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T14:40:20.253",
"Id": "502339",
"Score": "2",
"body": "You can avoid counting zeros if instead you split the string on every `0` (and discard too-short substrings). Then just test each of those substrings in turn."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T06:11:21.687",
"Id": "254687",
"ParentId": "254678",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T02:40:34.440",
"Id": "254678",
"Score": "1",
"Tags": [
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler 8 - Largest product in a series"
}
|
254678
|
<p>I have implemented an exhaustive depth-first grid search that searches for all possible words in the 8 connected regions. Is there any way I can make this faster or memory efficient than it is now?</p>
<p>I feel like passing a copy of the <code>seen</code> set in <code>dfs(xx, yy, seen.copy(), word + grid[x][y])</code> is an overhead that can possibly be avoided.</p>
<p>Or is my algorithm completely wrong and I should use something else?</p>
<p>This is not a code site challenge, I am just trying to implement this out of curiosity.</p>
<p>My first question on code review so let me know if there is something that I can add to make this better.</p>
<p>Also can this be made more "pythonic"?</p>
<pre><code>def possible_directions(x, y):
"""
Returns at most 8 connected co-ordinates for given `x` and `y`
"""
for xx in range(-1, 2):
for yy in range(-1, 2):
if not xx and not yy:
continue
if 0 <= x + xx < len(grid) and 0 <= y + yy < len(grid[x]):
yield x + xx, y + yy
def dfs(x, y, seen, word = ''):
"""
Recursive Generator that performs a dfs on the word grid
seen = set of seen co-ordinates, set of tuples
word = word to yield at each recursive call
"""
if (x, y) in seen:
return
yield word + grid[x][y]
seen.add((x, y))
for xx, yy in possible_directions(x, y):
yield from dfs(xx, yy, seen.copy(), word + grid[x][y])
grid = [['c', 'f', 'u', 'c'], ['e', 'a', 't', 'e'], ['b', 'h', 'p', 'y'], ['o', 'n', 'e', 'p']] # word grid, can be any size, n x n
for x in range(len(grid)):
for y in range(len(grid[x])):
for i in dfs(x, y, set()):
print(i)
</code></pre>
|
[] |
[
{
"body": "<p>This is fairly tight; I don't think there's much more performance to pull out without dropping into C. That said:</p>\n<h2><code>possible_directions</code></h2>\n<p>First, I would rename this to <code>neighbors</code> or <code>successors</code>; it's not really about direction but about the nodes in the graph that come next or are adjacent to your current node.</p>\n<p>Second, you can reduce the number of branches and arithmetic operations a little:</p>\n<pre><code>for xx in range(max(0, x - 1), min(x + 1, len(grid)):\n for yy in range(max(0, y - 1), min(y + 1, len(grid[x])):\n if xx == x and yy = y: continue\n yield xx, yy\n</code></pre>\n<p>Third, you can prevent many no-op calls of <code>dfs</code> by doing your <code>seen</code> check in this function rather than in the <code>dfs</code> base case. That is, pass <code>seen</code> to this function and modify your <code>yield</code> line to something like</p>\n<pre><code>if (xx, yy) not in seen: yield xx, yy\n</code></pre>\n<h2><code>dfs</code></h2>\n<p>You compute <code>word + grid[x][y]</code> many times (once + once per neighbor). You should memoize this before yielding it (Python may already perform this optimization for you but I doubt it).</p>\n<p>I don't think a <code>set</code> of <code>tuple</code>s is the best implementation for <code>seen</code>. You can't really avoid the copy of <code>seen</code> that I can see, and the lookups are not as fast as they could be. You already implicitly require that every row is the same length (<code>0 <= y + yy < len(grid[x])</code>, not <code>0 <= y + yy < len(grid[x + xx])</code>) and that seems like a sensible restriction in any case. I suggest a bit array of some sort (e.g. <a href=\"https://pypi.org/project/bitarray/\" rel=\"nofollow noreferrer\">bitarray</a>, which I've never used but seems to fit the bill), which will allow fast setting, checking, and copying of <code>seen</code> (instead of <code>seen[x][y]</code>, check and set <code>seen[y * len(grid) + x]</code>).</p>\n<p>Best practice here would probably be to have a wrapper function that does not take a <code>seen</code> or <code>word</code> argument, but initializes them for a call to your recursive helper, something like</p>\n<pre><code>def dfs(x, y):\n return dfs_recursive(x, y, set(), '')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T14:19:43.517",
"Id": "502524",
"Score": "0",
"body": "thank you for the response, appreciate the suggestion, if I dont get any other answers that are better than yours I will grant the bounty to you (12 hours until it lets me to)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:08:00.790",
"Id": "502638",
"Score": "0",
"body": "I am giving you the bounty since you gave a detailed breakdown of my code and also introduced me to `bitarray` but apologies for accepting a different answer as that explains a detail you missed with the `seen` set"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:20:33.910",
"Id": "502648",
"Score": "1",
"body": "Thanks @python_user - I also upvoted the answer you accepted because they noticed the way to avoid copying `seen`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T05:14:16.433",
"Id": "254781",
"ParentId": "254679",
"Score": "4"
}
},
{
"body": "<ul>\n<li>Pre-compute your offset tuples for <code>possible_directions</code></li>\n<li>Use type hints</li>\n<li>Use strings instead of character lists for immutable data</li>\n</ul>\n<p>Those aside, you should really consider avoiding printing every single line of output if possible. The printing alone, at this scale, will have a time impact.</p>\n<p>Suggested:</p>\n<pre><code>from typing import Set, Tuple, Iterable\n\nCoords = Tuple[int, int]\n\nOFFSETS: Tuple[Coords] = tuple(\n (xx, yy)\n for xx in range(-1, 2)\n for yy in range(-1, 2)\n if xx != 0 or yy != 0\n)\n\n\ndef possible_directions(x: int, y: int) -> Iterable[Coords]:\n """\n Returns at most 8 connected co-ordinates for given `x` and `y`\n """\n for xx, yy in OFFSETS:\n if 0 <= x + xx < len(grid) and 0 <= y + yy < len(grid[x]):\n yield x + xx, y + yy\n\n\ndef dfs(x: int, y: int, seen: Set[Coords], word: str = ''):\n """\n Recursive Generator that performs a dfs on the word grid\n seen = set of seen co-ordinates, set of tuples\n word = word to yield at each recursive call\n """\n if (x, y) in seen:\n return\n yield word + grid[x][y]\n seen.add((x, y))\n for xx, yy in possible_directions(x, y):\n yield from dfs(xx, yy, seen.copy(), word + grid[x][y])\n\n\ngrid = (\n 'cfuc',\n 'eate',\n 'bhpy',\n 'onep'\n) # word grid, can be any size, n x n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:13:04.930",
"Id": "502644",
"Score": "1",
"body": "I really appreciate your suggestions regarding type hints and precomputing offsets :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T23:07:10.540",
"Id": "254809",
"ParentId": "254679",
"Score": "3"
}
},
{
"body": "<p>It is not necessary to make a copy of <code>seen</code> when making a recursive call. Change <code>seen</code> before the recursive calls and then undo the change afterward.</p>\n<pre><code>def dfs(x, y, seen, word = ''):\n """\n Recursive Generator that performs a dfs on the word grid\n seen = set of seen co-ordinates, set of tuples\n word = word to yield at each recursive call\n """\n if (x, y) in seen:\n return\n yield word + grid[x][y]\n seen.add((x, y))\n for xx, yy in possible_directions(x, y):\n yield from dfs(xx, yy, seen, word + grid[x][y])\n seen.remove((x,y))\n</code></pre>\n<p>I wonder if it would be more efficient to take advantage of the symmetry of the square letter grid. If <code>dfs()</code> yielded lists of <code>x,y</code> tuples, you would only need to do dfs searches starting from (0,0), (0,1), and (1,1). Solutions for all the other starting points would be rotations or reflections.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:10:27.900",
"Id": "502639",
"Score": "0",
"body": "thanks for that, that seems like a simple yet effective change, I am accepting this as an answer but the answer by @ruds explains a bit more and hence I have awarded the bounty to them, apologies :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T01:54:05.227",
"Id": "254815",
"ParentId": "254679",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254815",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T03:27:05.110",
"Id": "254679",
"Score": "2",
"Tags": [
"python",
"performance",
"recursion",
"memory-optimization"
],
"Title": "DFS-based exhaustive word grid search"
}
|
254679
|
<p>I have some logic on my JSX for an element in a grid, if element is selected, then add to redux, if element is not selected then remove from redux...</p>
<p>is working ok, but I sense a bad smell...</p>
<pre><code><GridSelector
items={items}
onChange={(categoryId, isSelected) => {
favorites[categoryId] = isSelected;
const favsArraya = Object.values(onboarding.favoriteCategories);
let index;
if(isSelected){
if (favsArraya.indexOf(categoryId) === -1){
//doesnt exist, add it
favsArraya.push(categoryId)
}
}else{
if (favsArraya.indexOf(categoryId) !== -1){
// exists, delete it
index = favsArraya.indexOf(categoryId);
favsArraya.splice(index, 1);
}
}
dispatchData({ [DATA_KEY.FAVORITE_CATEGORIES]: favsArraya})
}}
/>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T19:31:39.207",
"Id": "502364",
"Score": "0",
"body": "I [changed the title](https://codereview.stackexchange.com/posts/254685/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
}
] |
[
{
"body": "<p>First of all, there's way too much going on here for an inline function. Let's seperate that out. Also, the splicing can be replaced with the more expressive filter.</p>\n<pre><code>const addIfMissing = (array, item) =>\n array.includes(item) ? array : array.concat([item]);\n\nconst without = (array, exclude) =>\n array.filter(x=> x!==exclude);\n\nconst onGridSelectorChange = (categoryId, isSelected) => {\n favorites[categoryId] = isSelected;\n const categoryIds = Object.values(onboarding.favoriteCategories);\n const newCategoryIds = isSelected ?\n addIfMissing(categoryIds,categoryId) :\n without(categoryIds,categoryId);\n\n dispatchData({ [DATA_KEY.FAVORITE_CATEGORIES]: newCategoryIds})\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T23:13:58.247",
"Id": "502380",
"Score": "0",
"body": "thanks a lot, what is the name of that kind of inline function writing? \nfunctional programming? reactive programming?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T23:32:36.887",
"Id": "502381",
"Score": "0",
"body": "the inline function is a JS arrow function. It's useful for functional programming, but does not necessarily imply \"pure\" functional code"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T07:02:54.973",
"Id": "254688",
"ParentId": "254685",
"Score": "3"
}
},
{
"body": "<p>Why is <code>index</code> declared at the top of the <code>onChange</code> handler? It is only used within the <code>else</code> block once. Thus it could be declared there using <code>const</code>.</p>\n<pre><code>const index = favsArraya.indexOf(categoryId);\nfavsArraya.splice(index, 1);\n</code></pre>\n<p>Not only does this eliminate an extra empty declaration, using <code>const</code> is a good habit because it can help avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<p>And that variable can be eliminated since it is only used once:</p>\n<pre><code>favsArraya.splice(favsArraya.indexOf(categoryId), 1);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T19:26:23.970",
"Id": "502361",
"Score": "0",
"body": "I don't believe the conditionals can be combined. Consider the case where `isSelected=false` and `categoryId` does not exist within `favsArraya`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T19:28:44.000",
"Id": "502363",
"Score": "1",
"body": "Okay that makes sense- thanks for clarifying."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T18:59:38.220",
"Id": "254709",
"ParentId": "254685",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254688",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T05:33:35.493",
"Id": "254685",
"Score": "2",
"Tags": [
"array",
"react.js",
"jsx",
"scope"
],
"Title": "Display element in a grid and conditionally add to redux or remove if not selected"
}
|
254685
|
<p><strong>STR2INCHES</strong> is an Excel VBA Function that will convert string text for Imperial length measurements to a decimal number of Inches.</p>
<p>It handles both English and Spanish words, abbreviations and symbols for yards, feet and inches.
Dashes are treated like they are spaces, and so it just does not care where dashes are used or not, except a dash on the far left side is considered as a negative number.
Negative numbers can be denoted with either a dash on the far left side or enclosing the entire string inside parentheses ().</p>
<p><strong>IMPTEXT</strong> is an Excel VBA Function that will convert string text of Imperial lengths (see above) or a decimal number of inches to formatted text of Feet and Inches.<br></p>
<ul>
<li><p><strong>Divisor</strong> is the 2nd parameter, its optional defaulting to 8 for 8ths of an inch. Measures are rounded to this divisor. Typical numbers would be 8 or 16, however, 2 and 4 or perhaps 10, 100 or 1000, could be possibilities, all are acceptable.<br></p>
</li>
<li><p><strong>appxInd</strong> is the 3rd parameter, it's optional defaulting to True; when True it will display a single tilde ~ when rounding is less than the actual value displayed, and a double tilde when rounding is greater than the actual value displayed. False will not display this approximation indicator.</p>
</li>
</ul>
<p><strong>CODE</strong></p>
<pre><code>Option Explicit
Function STR2INCHES(ByVal measurement As Variant) As Variant
'STR2INCHES converts Imperial feet and inch measurement text to decimal inches.
'A dash on the left or left and right parentheses are used for negative values.
'Any cammas are ignored, so don't worry about them if they are present.
'Inches denoted by double-quotes or Inches, or Inch, or In.
'Feet denoted by single-quote or Feet, or Foot, or Ft.
'Periods on the end are ignored.
'Not case-sensitive.
'Returns a decimal value for converted inches.
'Return is Variant and so it is compatable with different variable type.
'Return #VALUE! when conversion error occurs.
Dim negVal As Boolean
Dim i, unitPos As Long
On Error GoTo STR2INCHESerr
'Remove all commas
measurement = WorksheetFunction.Substitute(measurement, ",", "")
'Remove trailing periods and trim
measurement = Trim(LCase(measurement))
Do While Right(measurement, 1) = "."
measurement = Trim(Left(measurement, Len(measurement) - 1))
Loop
'check if negative value. e.g. left dash or ()
If Left(measurement, 1) = "-" Then
negVal = True
measurement = Mid(measurement, 2, 9999)
Else
If Left(measurement, 1) = "(" Then
If Right(measurement, 1) = ")" Then
negVal = True
measurement = Trim(Mid(measurement, 2, Len(measurement) - 2))
End If
End If
End If
'convert yards text to Ÿ
measurement = WorksheetFunction.Substitute(measurement, "yardas", "Ÿ") 'Spanish
measurement = WorksheetFunction.Substitute(measurement, "yarda", "Ÿ")
measurement = WorksheetFunction.Substitute(measurement, "yards", "Ÿ") 'English
measurement = WorksheetFunction.Substitute(measurement, "yard", "Ÿ")
measurement = WorksheetFunction.Substitute(measurement, "yds.", "Ÿ")
measurement = WorksheetFunction.Substitute(measurement, "yds", "Ÿ")
measurement = WorksheetFunction.Substitute(measurement, "yd.", "Ÿ")
measurement = WorksheetFunction.Substitute(measurement, "yd", "Ÿ")
Do While InStr(measurement, " Ÿ") > 0
measurement = WorksheetFunction.Substitute(measurement, " Ÿ", "Ÿ")
Loop
'convert feet text to single-quote '
measurement = WorksheetFunction.Substitute(measurement, "feet", "'") 'English
measurement = WorksheetFunction.Substitute(measurement, "foot", "'")
measurement = WorksheetFunction.Substitute(measurement, "ft.", "'")
measurement = WorksheetFunction.Substitute(measurement, "ft", "'")
measurement = WorksheetFunction.Substitute(measurement, "pies", "'") 'Spanish
measurement = WorksheetFunction.Substitute(measurement, "píes", "'")
measurement = WorksheetFunction.Substitute(measurement, "piés", "'")
measurement = WorksheetFunction.Substitute(measurement, "pie", "'")
measurement = WorksheetFunction.Substitute(measurement, "pié", "'")
Do While InStr(measurement, " '") > 0
measurement = WorksheetFunction.Substitute(measurement, " '", "'")
Loop
'convert inch text to double-quotes "
measurement = WorksheetFunction.Substitute(measurement, "inches", """") 'English
measurement = WorksheetFunction.Substitute(measurement, "inch", """")
measurement = WorksheetFunction.Substitute(measurement, "in.", """")
measurement = WorksheetFunction.Substitute(measurement, "in", """")
measurement = WorksheetFunction.Substitute(measurement, "pulgadas", """") 'Spanish
measurement = WorksheetFunction.Substitute(measurement, "pulgada", """")
Do While InStr(measurement, " """) > 0
measurement = WorksheetFunction.Substitute(measurement, " """, """")
Loop
'get rid of any dash
measurement = WorksheetFunction.Substitute(measurement, "-", " ")
'ensure measurement symbols are followed by a blank
measurement = Trim(WorksheetFunction.Substitute(measurement, """", """ "))
measurement = Trim(WorksheetFunction.Substitute(measurement, "'", "' "))
measurement = Trim(WorksheetFunction.Substitute(measurement, "Ÿ", "Ÿ "))
'convert double blanks to single blanks
Do While InStr(measurement, " ") > 0
measurement = WorksheetFunction.Substitute(measurement, " ", " ")
Loop
'Default to Inches if nothing else is found
measurement = Trim(measurement)
If Right(measurement, 1) <> """" Then
If Right(measurement, 1) <> "'" Then
If Right(measurement, 1) <> "Ÿ" Then
measurement = measurement & """"
End If
End If
End If
'measurement now in standard format, so convert it to inches
' e.g. 2Ÿ 1' 3.25" or 2Ÿ 1' 3 1/4" or 15 1/4" or 15.25"
'evaluate converts fractions and decimal text to decimal
STR2INCHES = getValue(measurement, "Ÿ") * 36 'Yards
STR2INCHES = STR2INCHES + getValue(measurement, "'") * 12 'Feet
STR2INCHES = STR2INCHES + getValue(measurement, """") 'Inches
If negVal Then STR2INCHES = -STR2INCHES 'Flip to negative applicable
Exit Function
STR2INCHESerr:
STR2INCHES = CVErr(xlErrValue) 'return #VALUE! error
On Error GoTo 0
End Function
Function getValue(ByVal measurement As Variant, ByVal unitDelim As Variant) As Variant
'this will find and return a whole number, decimal numbers and whole numbers with a fraction
'it starts with finding the unitDelim and working backwards
Dim unitPos, i As Long
On Error GoTo getValueErr
unitPos = InStr(measurement, unitDelim)
If unitPos > 0 Then
i = InStrRev(measurement, " ", unitPos) - 1
'search backwards for any character not related to numbers and blanks
Do Until i <= 0
If IsNumeric(Mid(measurement, i, 1)) Or Mid(measurement, i, 1) = "." Or Mid(measurement, i, 1) = " " Then
i = i - 1
Else
Exit Do
End If
DoEvents
Loop
i = i + 1
If i <= 0 Then i = 1
getValue = Evaluate(Mid(measurement, i, unitPos - i))
End If
Exit Function
getValueErr:
getValue = CVErr(xlErrValue) 'return #VALUE! error
On Error GoTo 0
End Function
Function IMPTEXT(ByVal measurement As Variant, Optional ByVal divisor As Variant = 8, Optional ByVal appxInd As Boolean = True) As String
'IMPTEXT will format a decimal number of inches to text using Imperial Yards, Feet and Inch measurements
'will round round inches value to nearest divisor (default is 8ths),
'then returns a formatted text string of feet inches and fractional inches.
'Important: rounding up or down is reversed for negative numbers.
'Return #VALUE! when conversion error occurs.
'Optional divisor:
' Default is 8ths, however you may optionally round to whole numbers(1), halfs(2), quarters(4), tenths(10), sixteenths(16), (32)...
'Optional appxInd (default is True):
' approximation symbols are reverse order for negative numbers.
' Will optionally add single-tilde approximation symbol if rounded value displayed is less than actual size.
' Will optionally add double-tilde approximation symbol if rounded value displayed is more than actual size.
Dim feet, inches, inch, rInt, rGcd As Long
Dim inchDecimal, rNum, appx As Double
Dim inchPos As Boolean
On Error GoTo IMPTEXTerr
divisor = Round(divisor, 0) 'to ensure whole numbers
inches = STR2INCHES(measurement) 'convert to decimal if needed
If inches < 0 Then
inchPos = True
inches = Abs(inches)
End If
feet = Int(inches / 12)
inch = Int(inches - feet * 12)
inchDecimal = inches - feet * 12 - inch
rNum = inchDecimal * divisor
rInt = Round(rNum, 0)
appx = rNum - rInt
If feet > 0 Then IMPTEXT = feet & "' "
IMPTEXT = IMPTEXT & inch
If rInt > 0 Then
If inch > 0 Then
IMPTEXT = IMPTEXT & "-"
Else
IMPTEXT = IMPTEXT & " "
End If
rGcd = WorksheetFunction.Gcd(rInt, divisor)
IMPTEXT = IMPTEXT & rInt / rGcd & "/" & divisor / rGcd
End If
IMPTEXT = Trim(IMPTEXT) & """"
IMPTEXT = Trim(IMPTEXT)
If inchPos Then
IMPTEXT = "(" & IMPTEXT & ")"
End If
If appxInd Then
If appx < 0 Then
IMPTEXT = "~" & IMPTEXT 'approx is slightly less than shown
ElseIf appx > 0 Then
IMPTEXT = ChrW(&H2248) & " " & IMPTEXT 'approx is slighly greater than shown
End If
End If
Exit Function
IMPTEXTerr:
IMPTEXT = CVErr(xlErrValue) 'return #VALUE! error
On Error GoTo 0
End Function
</code></pre>
<hr />
<p>IMPORTANT NOTE: THE CODE ABOVE WORKS, BUT I MODIFIED A BETTER VERSION AND POSTED IT AT THE BOTTOM AS A COMMENT IN THIS POSTING. PLEASE USE THE CODE BELOW NOT THIS CODE ABOVE.</p>
<p>It's very robust code that handles every reasonable variation of decimal and fractional values with Spanish and English notations of Yards, Feet and Inches. Let me know if you have any suggestions; I always welcome kind feedback.</p>
<hr />
<p>An example use is:</p>
<pre><code>=str2inches(A1)
</code></pre>
<p>STR2INCHES(A1) offers more flexibility than other code that I have personally seen and tested. It's also bilingual and so it handles yards (yardas), feet (píes), inches (pulgadas), symbols, and measurement abbreviations.
It does not assume any particular sequence of certain measures, it will use the first measure found of each type.
It handles fractions and decimals and is forgiving with no spaces, single and double spaces. e.g. 5.25In vs. 5-1/4" vs. 5 1/4 Inches vs. 5 1/4pulgadas would all return 5.25</p>
<p>It also formats to a standard format of Feet and Inches.<br>
=IMPTEXT(A1, 16, FALSE)</p>
<p>The first parameter is expecting Inches, but it will convert to inches using STR2INCHES automatically if needed.</p>
<p>It always rounds to the nearest divisor (in the example above it would round to 16ths; rounding to 8ths is the default.</p>
<p>It defaults to displaying a single tilde ~ if rounding displays a value that is less than the actual value, and displays a double tilde when the displayed value is greater than the actual value.</p>
<p>It handles negative numbers fine, it displays them using parenthesis ().</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:55:20.677",
"Id": "502305",
"Score": "0",
"body": "These look like they are to be used as User Defined Functions called from worksheet formulas. You should strive to use VBA-only code. Punching through the barrier from VBA to Excel to access worksheet functions (i.e. `WorksheetFunction.Substitute()`) is SLOW. What is wrong with VBA's `Replace()` function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:56:16.463",
"Id": "502306",
"Score": "0",
"body": "FYI VBA has `Replace()` which does the same thing as `WorksheetFunction.Substitute` and is a little faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:59:56.030",
"Id": "502307",
"Score": "1",
"body": "@TimWilliams `Replace()` is a LOT faster. Every call through the VBA-to-Excel divide is extremely expensive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T19:04:40.453",
"Id": "502308",
"Score": "0",
"body": "`Dim feet, inches, inch, rInt, rGcd As Long` Do you realize that ONLY `rGcd` is a Long here? All the other variables declared with this statement are Variants. You seem to use this style of coding a lot... and it does not result in what you think it does. Every single variable included in a `Dim` statement must be typed INDIVIDUALLY. When a type is omitted for a given variable, it defaults to Variant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T19:12:29.860",
"Id": "502309",
"Score": "0",
"body": "@ExcelHero - I saw `Replace` as about 3x faster in a quick test."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T19:15:42.287",
"Id": "502310",
"Score": "0",
"body": "@TimWilliams Yep, that's a lot. Does that ratio hold as the strings (both the Find string and the Replace string) get longer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T19:26:53.480",
"Id": "502311",
"Score": "0",
"body": "@ExcelHero - testing more it's about a 6x difference, and both methods are slower with larger strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T21:35:29.240",
"Id": "502373",
"Score": "0",
"body": "I'd also suggest explicitly declaring your functions and subs as either `Public` or `Private`. I'm not certain if all of the routines in your code are intended to be visible publicly and/or available as UDFs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T18:31:54.480",
"Id": "510666",
"Score": "0",
"body": "I really appreciate the feedback. For some reason the Replace was acting odd with my use of Ÿ. I reinstalled Excel and the problem went away, so thanks for the push there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T18:34:21.530",
"Id": "510668",
"Score": "0",
"body": "@fionasdad I did not know multiple variable names would be Variant and only the last one has the actual type; I'm thankful to know this, thank you for recognizing this and pointing it out."
}
] |
[
{
"body": "<p>This pattern shows up multiple times:</p>\n<pre class=\"lang-vb prettyprint-override\"><code> 'convert yards text to Ÿ\n measurement = WorksheetFunction.Substitute(measurement, "yardas", "Ÿ") 'Spanish\n measurement = WorksheetFunction.Substitute(measurement, "yarda", "Ÿ")\n measurement = WorksheetFunction.Substitute(measurement, "yards", "Ÿ") 'English\n measurement = WorksheetFunction.Substitute(measurement, "yard", "Ÿ")\n measurement = WorksheetFunction.Substitute(measurement, "yds.", "Ÿ")\n measurement = WorksheetFunction.Substitute(measurement, "yds", "Ÿ")\n measurement = WorksheetFunction.Substitute(measurement, "yd.", "Ÿ")\n measurement = WorksheetFunction.Substitute(measurement, "yd", "Ÿ")\n Do While InStr(measurement, " Ÿ") > 0\n measurement = WorksheetFunction.Substitute(measurement, " Ÿ", "Ÿ")\n Loop\n</code></pre>\n<p>and is a good candidate for refactoring into a standalone helper function:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Function NormalizeUnits(ByVal txt As String, oldUnits, newUnit As String) As String\n Dim u\n For Each u In oldUnits\n txt = Replace(txt, u, newUnit)\n Next u\n Do While InStr(txt, " " & newUnit) > 0\n txt = Replace(txt, " " & newUnit, newUnit)\n Loop\n NormalizeUnits = txt\nEnd Function\n</code></pre>\n<p>Example call:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Const YARDS As String = "yardas|yarda|yards|yard|yds.|yds|yd.|yd"\n'...\n'...\nmeasurement = NormalizeUnits(measurement, Split(YARDS, "|"), "Ÿ")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T18:37:24.703",
"Id": "510670",
"Score": "0",
"body": "Tim, I like your improvement. It will tidy the code up, thanks for taking the time and writing it up. I will repost a reply with the cleaner code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T19:11:21.980",
"Id": "254691",
"ParentId": "254690",
"Score": "8"
}
},
{
"body": "<p>I updated my code based on the suggestions provided and also modified the code to allow multiple uses of the same unit of measure (it will just add the values).</p>\n<p>Thank you to everyone for the kind suggestions. This code is better for it.</p>\n<pre><code>Option Explicit\n \nPublic Function STR2INCHES(ByVal measurement As Variant) As Variant\n 'STR2INCHES converts Imperial feet and inch measurement text to decimal inches.\n 'A dash on the left or left and right parentheses are used for negative values.\n 'Any commas are ignored, so don't worry about them if they are present.\n 'Inches denoted by double-quotes or Inches, or Inch, or In.\n 'Feet denoted by single-quote or Feet, or Foot, or Ft.\n 'Periods on the end are ignored.\n 'Not case-sensitive.\n 'Returns a decimal value for converted inches.\n 'Return is Variant and so it is compatible with different variable type.\n 'Return #VALUE! when conversion error occurs.\n \n Dim negVal As Boolean\n Dim i As Long\n Dim unitPos As Long\n Const YARDS As String = "yardas|yarda|yards|yard|yds.|yds|yd.|yd" 'English and Spanish YARD terms\n Const FEET As String = "feet|foot|ft.|ft|pies|píes|piés|pie|pié" 'English and Spanish FEET terms\n Const INCHES As String = "inches|inch|in.|in|pulgadas|pulgada" 'English and Spanish INCH terms\n \n On Error GoTo STR2INCHESerr\n \n 'Remove all commas\n measurement = Replace(measurement, ",", "")\n \n 'Remove trailing periods and trim\n measurement = Trim(LCase(measurement))\n Do While Right(measurement, 1) = "."\n measurement = Trim(Left(measurement, Len(measurement) - 1))\n Loop\n \n 'check if negative value. e.g. left dash or ()\n If Left(measurement, 1) = "-" Then\n negVal = True\n measurement = Mid(measurement, 2, 9999)\n Else\n If Left(measurement, 1) = "(" Then\n If Right(measurement, 1) = ")" Then\n negVal = True\n measurement = Trim(Mid(measurement, 2, Len(measurement) - 2))\n End If\n End If\n End If\n \n measurement = NormalizeUnits(measurement, Split(YARDS, "|"), "Ÿ") 'convert yards text to Ÿ\n measurement = NormalizeUnits(measurement, Split(FEET, "|"), "'") 'convert feet text to single-quote '\n measurement = NormalizeUnits(measurement, Split(INCHES, "|"), """") 'convert inch text to double-quotes "\n measurement = Replace(measurement, "-", " ") 'get rid of any dash\n \n 'ensure measurement symbols are followed by a blank\n measurement = Trim(Replace(measurement, """", """ "))\n measurement = Trim(Replace(measurement, "'", "' "))\n measurement = Trim(Replace(measurement, "Ÿ", "Ÿ "))\n \n 'convert double blanks to single blanks\n Do While InStr(measurement, " ") > 0\n measurement = Replace(measurement, " ", " ")\n Loop\n \n 'Default to Inches if nothing else is found\n measurement = Trim(measurement)\n If Right(measurement, 1) <> """" Then\n If Right(measurement, 1) <> "'" Then\n If Right(measurement, 1) <> "Ÿ" Then\n measurement = measurement & """"\n End If\n End If\n End If\n \n 'measurement now in standard format, so convert it to inches\n ' e.g. 2Ÿ 1' 3.25" or 2Ÿ 1' 3 1/4" or 15 1/4" or 15.25"\n 'evaluate converts fractions and decimal text to decimal\n \n STR2INCHES = GetValue(measurement, "Ÿ") * 36 'Yards\n STR2INCHES = STR2INCHES + GetValue(measurement, "'") * 12 'Feet\n STR2INCHES = STR2INCHES + GetValue(measurement, """") 'Inches\n \n If negVal Then STR2INCHES = -STR2INCHES 'Flip to negative applicable\n Exit Function\n \nSTR2INCHESerr:\n STR2INCHES = CVErr(xlErrValue) 'return #VALUE! error\n On Error GoTo 0\nEnd Function\n \nPrivate Function GetValue(ByVal measurement As Variant, ByVal unitDelim As Variant) As Variant\n 'this will find and return a whole number, decimal numbers and whole numbers with a fraction\n 'it starts with finding the unitDelim and working backwards\n 'it will also add multiple representations of the same unit. e.g. 2Yds 3Yards would return 5 Yards\n \n Dim unitPos As Long\n Dim i As Long\n On Error GoTo getValueErr\n \n unitPos = InStr(measurement, unitDelim)\n Do While unitPos > 0\n i = InStrRev(measurement, " ", unitPos) - 1\n 'search backwards for any character not related to numbers and blanks\n Do Until i <= 0\n If IsNumeric(Mid(measurement, i, 1)) Or Mid(measurement, i, 1) = "." Or Mid(measurement, i, 1) = " " Then\n i = i - 1\n Else\n Exit Do\n End If\n DoEvents\n Loop\n i = i + 1\n If i <= 0 Then i = 1\n GetValue = GetValue + Evaluate(Mid(measurement, i, unitPos - i))\n unitPos = InStr(unitPos + 1, measurement, unitDelim)\n Loop\n Exit Function\n \ngetValueErr:\n GetValue = CVErr(xlErrValue) 'return #VALUE! error\n On Error GoTo 0\nEnd Function\n \nPublic Function IMPTEXT(ByVal measurement As Variant, Optional ByVal divisor As Variant = 8, Optional ByVal appxInd As Boolean = True) As String\n 'IMPTEXT will format a decimal number of inches to text using Imperial Yards, Feet and Inch measurements\n 'will round inches value to nearest divisor (default is 8ths),\n 'then returns a formatted text string of feet inches and fractional inches.\n 'Important: rounding up or down is reversed for negative numbers.\n 'Return #VALUE! when conversion error occurs.\n 'Optional divisor:\n ' Default is 8ths, however you may optionally round to whole numbers(1), halfs(2), quarters(4), tenths(10), sixteenths(16), (32)...\n 'Optional appxInd (default is True):\n ' approximation symbols are reverse order for negative numbers.\n ' Will optionally add single-tilde approximation symbol if rounded value displayed is less than actual size.\n ' Will optionally add double-tilde approximation symbol if rounded value displayed is more than actual size.\n \n Dim inchPos As Boolean\n Dim inches As Double\n Dim inchDecimal As Double\n Dim inch As Long\n Dim feet As Long\n Dim rInt As Long\n Dim rGcd As Long\n Dim rNum As Double\n Dim appx As Double\n \n On Error GoTo IMPTEXTerr\n \n divisor = Round(divisor, 0) 'to ensure whole numbers\n \n inches = STR2INCHES(measurement) 'convert to decimal if needed\n If inches < 0 Then\n inchPos = True\n inches = Abs(inches)\n End If\n feet = Int(inches / 12)\n inch = Int(inches - feet * 12)\n inchDecimal = inches - feet * 12 - inch\n rNum = inchDecimal * divisor\n rInt = Round(rNum, 0)\n appx = rNum - rInt\n \n If feet > 0 Then IMPTEXT = feet & "' "\n IMPTEXT = IMPTEXT & inch\n If rInt > 0 Then\n If inch > 0 Then\n IMPTEXT = IMPTEXT & "-"\n Else\n IMPTEXT = IMPTEXT & " "\n End If\n rGcd = WorksheetFunction.Gcd(rInt, divisor)\n IMPTEXT = IMPTEXT & rInt / rGcd & "/" & divisor / rGcd\n End If\n \n IMPTEXT = Trim(IMPTEXT) & """"\n \n IMPTEXT = Trim(IMPTEXT)\n If inchPos Then\n IMPTEXT = "(" & IMPTEXT & ")"\n End If\n \n If appxInd Then\n If appx < 0 Then\n IMPTEXT = "~" & IMPTEXT 'approx is slightly less than shown\n ElseIf appx > 0 Then\n IMPTEXT = ChrW(&H2248) & " " & IMPTEXT 'approx is slightly greater than shown\n End If\n End If\n Exit Function\n \nIMPTEXTerr:\n IMPTEXT = CVErr(xlErrValue) 'return #VALUE! error\n On Error GoTo 0\nEnd Function\n \nPrivate Function NormalizeUnits(ByVal txt As String, oldUnits, newUnit As String) As String\n 'Converts various oldUnits within txt into a single standard newUnit\n \n Dim oldUnit As Variant\n For Each oldUnit In oldUnits\n txt = Replace(txt, oldUnit, newUnit)\n Next oldUnit\n Do While InStr(txt, " " & newUnit) > 0\n txt = Replace(txt, " " & newUnit, newUnit) 'remove leading spaces\n Loop\n NormalizeUnits = txt\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T21:21:15.393",
"Id": "510701",
"Score": "1",
"body": "I created this code to be very robust, it can handle most any reasonable imperial measurement variation of yards, feet, inches and fractions that you can throw at it. it also handles Spanish and English words. If someone finds an error please let me know so i can try to debug the code. I believe this to be tested working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-02T06:48:10.107",
"Id": "510724",
"Score": "0",
"body": "If you want further suggestions on the new code, I recommend you post it as a new question, with a link to this one. OTOH, if you just want bug reports and not reviews, then you've done the right thing. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-01T20:21:41.583",
"Id": "258982",
"ParentId": "254690",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "258982",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-13T18:27:00.557",
"Id": "254690",
"Score": "4",
"Tags": [
"excel",
"vba",
"strings"
],
"Title": "Excel VBA Code for Imperial Length Measure Conversion and Formatting Yards Feet and Inches for English and Spanish"
}
|
254690
|
<p>I have a string containing several items listed in the following notation:</p>
<pre><code>myString = '[A][B][C]'
</code></pre>
<p>And I would like to parse that to a python list of several strings:</p>
<pre><code>['A', 'B', 'C']
</code></pre>
<p>I know this can be solved with:</p>
<pre><code>myString = myString.lstrip('[')
myString = myString.rstrip(']')
myList = myString.split('][')
</code></pre>
<p>I'd just like to know if there is an even more pythonic way of doing it.
Compare <a href="https://stackoverflow.com/a/1653143/10983441">https://stackoverflow.com/a/1653143/10983441</a> where the most elegant way in the end was to use pyparsing with nestedExpr.</p>
|
[] |
[
{
"body": "<p>A Regex based solution</p>\n<pre><code>>>> my_string_one\n'[A][B][C]'\n>>> re.split(r"\\[([A-Z])\\]", my_string_one)[1:-1:2]\n['A', 'B', 'C']\n>>> my_string_two\n'[A][B][C][D][E]'\n>>> re.split(r"\\[([A-Z])\\]", my_string_two)[1:-1:2]\n['A', 'B', 'C', 'D', 'E']\n</code></pre>\n<p>You can use <code>re.split</code> with the expression <code>\\[([A-Z])\\</code> having a capture group for the uppercase letters. This is under the assumption that your strings always follow this pattern otherwise you may not get what you expect.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T13:10:48.083",
"Id": "254701",
"ParentId": "254694",
"Score": "4"
}
},
{
"body": "<p>If you have a regular pattern that describes what you want to do with a string, using a regular expression (regex) is usually a good idea. In addition to using <code>re.split</code>, as shown in <a href=\"https://codereview.stackexchange.com/a/254701/98493\">another answer</a> by <a href=\"https://codereview.stackexchange.com/users/233379/python-user\">@python_user</a>, you can also use <code>re.findall</code>, which has the advantage that you don't have to manually deal with the opening and closing delimiters:</p>\n<pre><code>import re\nre.findall('\\[(.)\\]', '[A][B][C]')\n# ['A', 'B', 'C']\n</code></pre>\n<p>This finds all single characters (<code>.</code>), which are surrounded by square parenthesis (<code>\\[...\\]</code>) and selects only the character itself (<code>(.)</code>).</p>\n<p>If you want to allow more than one character between the parenthesis, you need to use a <a href=\"https://stackoverflow.com/a/766377/4042267\">non-greedy version of <code>*</code>, the <code>*?</code></a>:</p>\n<pre><code>re.findall('\\[(.*)\\]', '[][a][a2][+%]')\n# ['][a][a2][+%']\n\nre.findall('\\[(.*?)\\]', '[][a][a2][+%]')\n# ['', 'a', 'a2', '+%']\n</code></pre>\n<hr />\n<p>Regarding your code itself, Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends using <code>lower_case</code> instead of <code>pascalCase</code> for variables and functions.</p>\n<p>You could also chain your calls together without sacrificing too much readability (even gaining some, arguably):</p>\n<pre><code>my_list = my_string.lstrip('[').rstrip(']').split('][')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T14:12:18.207",
"Id": "502337",
"Score": "1",
"body": "seeing this answer makes me want to up my regex game :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T21:33:48.600",
"Id": "502372",
"Score": "0",
"body": "normal strip can be used instead of rstrip and lstrip: `my_list = my_string.strip(\"][\").split(\"][\")`, but string slicing could be used instead: `my_list = my_string[1:-1].split(\"][\")`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T14:09:25.200",
"Id": "254703",
"ParentId": "254694",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "254703",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T10:15:22.940",
"Id": "254694",
"Score": "3",
"Tags": [
"python",
"parsing"
],
"Title": "Python: Parse string of bracketed list items into list of strings"
}
|
254694
|
<p>This is my first neural net, previously I had it with just one hidden layer.
I have now given it an adjustable number of hidden layers. It all works perfectly (asin I dont get nans and infs). I have specifically avoided the use of pointers since I am still very new to coding and want to keep things as simple as possible, for now.
So I just want to know how likely it is that this code will cause me problems(I will add exception handling) or if anyone can spot any inefficiency's.
The formula I am for using backpropogation is as follows:</p>
<p>del == Gradient vector of, a(x) == preactivation function, h(x) == activation function, W == weights, B== bias, (-logf(x)y) == loss function valu,
e(y) == one hot vector (all 0's and one 1),
F(x) == output vector after activation (using softmax as i have 3 output neurons)</p>
<p>Compute output Gradient -> del a(L+1)(x)-logf(x)y <= -(e(y) - F(x))</p>
<p>for k from L+1 to 1</p>
<p>Compute hidden layer parameter gradients(weights gradients)</p>
<p>del W(k)-logf(x)y <= (del a(k)(x)-logf(x)y) h(k-1)(x)</p>
<p>del B(k)-logf(x)y <= del a(k)(x)-logf(x)y</p>
<p>Compute gradients of hidden layer below</p>
<p>del h(k-1)(x)- logf(x)y <= W(k) * (del a(k)(x)-logf(x)y)</p>
<p>del a(k-1)-logf(x)y <= (del h(k-1)(x)-logf(x)y) "dot" (activation derivitave(a(k-1)(x))</p>
<p>Using empirical risk minimization:</p>
<p>Delta = -del W-logf(x)y - (lamba*regularizer). //I have used L1</p>
<p>parameter = parameter + alpha*delta.</p>
<p>if this is not enough code and its okay to post more, please let me know, this is my first time posting here and Im wary of having too much to read.
this is the code:</p>
<pre><code> void backprop(Net& net, std::vector<double>& target)
{//note to reader- The weights for each neuron is stored in the previous
//neuron as a vector
// and the biases for each neuron is stored in the neuron itself as a
//double.
// net.hiddenneurons is a two dimensional vector containing each layer
//of hidden neurons
double PD{};
for (size_t opd = 0; opd < net.outputneurons.size(); opd++)
{
net.outputneurons[opd].preactvalpd = -(target[opd] -net.outputneurons[opd].actval);
PD = net.outputneurons[opd].preactvalpd * -1;
net.outputneurons[opd].bias = net.outputneurons[opd].bias + (net.alpha * PD);
PD = 0;
}
for (size_t hs = net.hiddenneurons.size()-1; hs > -1; hs--)
{
int layerup = hs + 1;
for (size_t current = 0; current < net.hiddenneurons[hs].size(); current++)
{
if (hs == net.hiddenneurons.size() - 1)
{
for (size_t wpd = 0; wpd < net.hiddenneurons[hs]
[current].weights.size(); wpd++)
{
PD = net.outputneurons[wpd].preactvalpd *
net.hiddenneurons[hs][current].actval;
PD = PD * -1;
net.hiddenneurons[hs][current].weights[wpd] =
net.hiddenneurons[hs][current].weights[wpd] + (net.alpha
* (PD - (net.lambda *
regularizer(net.hiddenneurons[hs]
[current].weights[wpd]))));//is this even correct
//use of regularizer?
PD = 0;
//I have combined finding the partial derivative of the
//weights with updating the
//weights, PD is the partial derivative.
//I have done the same for biases.
}
for (size_t op = 0; op < net.outputneurons.size(); op++)
{
PD += net.hiddenneurons[hs][current].weights[op] *
net.outputneurons[op].preactvalpd;
}
net.hiddenneurons[hs][current].actvalPD = PD;
PD = 0;
}
else
{
for (size_t wpd = 0; wpd < net.hiddenneurons[hs]
[current].weights.size(); wpd++)
{
PD = net.hiddenneurons[layerup][wpd].preactvalpd *
net.hiddenneurons[hs[current].actval;
PD = PD * -1;
net.hiddenneurons[hs][current].weights[wpd] =
net.hiddenneurons[hs][current].weights[wpd] + (net.alpha
* (PD - (net.lambda *
regularizer(net.hiddenneurons[hs]
[current].weights[wpd]))));
PD = 0;
}
for (size_t op = 0; op < net.hiddenneurons[layerup].size();
op++)
{
PD += net.hiddenneurons[hs][current].weights[op] *
net.hiddenneurons[layerup][op].preactvalpd;
}
net.hiddenneurons[hs][current].actvalPD = PD;
PD = 0;
}
net.hiddenneurons[hs][current].preactvalpd =
net.hiddenneurons[hs][current].actvalPD *
tanhderiv(net.hiddenneurons[hs][current].preactval);
net.hiddenneurons[hs][current].bias =
net.hiddenneurons[hs][current].bias + (net.alpha *
net.hiddenneurons[hs][current].preactvalpd);
}
}
for (size_t iw = 0; iw < net.inneurons.size(); iw++)
{
for (size_t hpad = 0; hpad < net.inneurons[iw].weights.size();
hpad++)
{
PD = net.hiddenneurons[0][hpad].preactvalpd *
net.inneurons[iw].val;
PD = PD * -1;
net.inneurons[iw].weights[hpad] =
net.inneurons[iw].weights[hpad] + (net.alpha * (PD -
(net.lambda *
regularizer(net.inneurons[iw].weights[hpad]))));
PD = 0;
}
}
std::cout << "backprop done" << '\n';
}
</code></pre>
<p>Rest of code:</p>
<pre><code>double randomt(int x, int y)
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(x, y);
return dist(mt);
}
class InputN
{
public:
double val{};
std::vector <double> weights{};
};
class HiddenN
{
public:
double preactval{};
double actval{};
double actvalPD{};
double preactvalpd{};
std::vector <double> weights{};
double bias{};
};
class OutputN
{
public:
double preactval{};
double actval{};
double preactvalpd{};
double bias{};
};
class Net
{
public:
std::vector <InputN> inneurons{};
std::vector <std::vector <HiddenN>> hiddenneurons{};
std::vector <OutputN> outputneurons{};
double lambda{ 0.015 };
double alpha{ 0.015 };
};
void feedforward(Net& net)
{
double sum{};
int prevlayer{};
for (size_t Hsize = 0; Hsize < net.hiddenneurons.size(); Hsize++)
{
//std::cout << "in first loop" << '\n';
prevlayer = Hsize - 1;
for (size_t Hel = 0; Hel < net.hiddenneurons[Hsize].size(); Hel++)
{
//std::cout << "in second loop" << '\n';
if (Hsize == 0)
{
//std::cout << "in first if" << '\n';
for (size_t Isize = 0; Isize < net.inneurons.size(); Isize++)
{
//std::cout << "in fourth loop" << '\n';
sum += (net.inneurons[Isize].val *
net.inneurons[Isize].weights[Hel]);
}
net.hiddenneurons[Hsize][Hel].preactval =
net.hiddenneurons[Hsize][Hel].bias + sum;
net.hiddenneurons[Hsize][Hel].actval = tanh(sum);
sum = 0;
//std::cout << "first if done" << '\n';
}
else
{
//std::cout << "in else" << '\n';
for (size_t prs = 0; prs <
net.hiddenneurons[prevlayer].size(); prs++)
{
//std::cout << "in fourth loop" << '\n';
sum += net.hiddenneurons[prevlayer][prs].actval *
net.hiddenneurons[prevlayer][prs].weights[Hel];
}
//std::cout << "fourth loop done" << '\n';
net.hiddenneurons[Hsize][Hel].preactval =
net.hiddenneurons[Hsize][Hel].bias + sum;
net.hiddenneurons[Hsize][Hel].actval = tanh(sum);
//std::cout << "else done" << '\n';
sum = 0;
}
}
}
//std::cout << "first loop done " << '\n';
int lasthid = net.hiddenneurons.size() - 1;
for (size_t Osize = 0; Osize < net.outputneurons.size(); Osize++)
{
for (size_t Hsize = 0; Hsize < net.hiddenneurons[lasthid].size();
Hsize++)
{
sum += (net.hiddenneurons[lasthid][Hsize].actval *
net.hiddenneurons[lasthid][Hsize].weights[Osize]);
}
net.outputneurons[Osize].preactval = net.outputneurons[Osize].bias +
sum;
}
}
void softmax(Net& net)
{
double sum{};
for (size_t Osize = 0; Osize < net.outputneurons.size(); Osize++)
{
sum += exp(net.outputneurons[Osize].preactval);
}
for (size_t Osize = 0; Osize < net.outputneurons.size(); Osize++)
{
net.outputneurons[Osize].actval =
exp(net.outputneurons[Osize].preactval) / sum;
}
}
double regularizer(double weight)
{
double absval{};
if (weight < 0) absval = weight - weight - weight;
else if (weight > 0 || weight == 0) absval = weight;
else;
if (absval > 0) return 1;
else if (absval < 0) return -1;
else if (absval == 0) return 0;
else return 2;
// I will add a exception handler for when this function returns 2
}
void lossfunc(Net& net, std::vector <double> target)
{
int pos{ -1 };
double val{};
for (size_t t = 0; t < target.size(); t++)
{
pos += 1;
if (target[t] > 0)
{
break;
}
}
for (size_t s = 0; net.outputneurons.size(); s++)
{
val = -log(net.outputneurons[pos].actval);
}
}
int main()
{
std::vector <double> invals{ };
std::vector <double> target{ };
Net net;
InputN Ineuron;
HiddenN Hneuron;
OutputN Oneuron;
int IN = 4;
int HIDLAYERS = 1;
int HID = 8;
int OUT = 3;
for (int i = 0; i < IN; i++)
{
net.inneurons.push_back(Ineuron);
for (int m = 0; m < HID; m++)
{
net.inneurons.back().weights.push_back(randomt(0, 1));
}
}
//std::cout << "first loop done" << '\n';
for (int s = 0; s < HIDLAYERS; s++)
{
net.hiddenneurons.push_back(std::vector <HiddenN>());
if (s == HIDLAYERS - 1)
{
for (int i = 0; i < HID; i++)
{
net.hiddenneurons[s].push_back(Hneuron);
for (int m = 0; m < OUT; m++)
{
net.hiddenneurons[s].back().weights.push_back(randomt(0,
1));
}
net.hiddenneurons[s].back().bias = randomt(0, 1);
}
}
else
{
for (int i = 0; i < HID; i++)
{
net.hiddenneurons[s].push_back(Hneuron);
for (int m = 0; m < HID; m++)
{
net.hiddenneurons[s].back().weights.push_back(randomt(0,
1));
}
net.hiddenneurons[s].back().bias = randomt(0, 1);
}
}
}
//std::cout << "second loop done" << '\n';
for (int i = 0; i < OUT; i++)
{
net.outputneurons.push_back(Oneuron);
net.outputneurons.back().bias = randomt(0, 1);
}
//std::cout << "third loop done" << '\n';
int count{};
std::ifstream fileread("N.txt");
for (int epoch = 0; epoch < 500; epoch++)
{
count = 0;
fileread.clear(); fileread.seekg(0, std::ios::beg);
while (fileread.is_open())
{
std::cout << '\n' << "epoch: " << epoch << '\n';
std::string fileline{};
fileread >> fileline;
if (fileline == "in:")
{
std::string input{};
double nums{};
std::getline(fileread, input);
std::stringstream ss(input);
while (ss >> nums)
{
invals.push_back(nums);
}
}
if (fileline == "out:")
{
std::string output{};
double num{};
std::getline(fileread, output);
std::stringstream ss(output);
while (ss >> num)
{
target.push_back(num);
}
}
count += 1;
if (count == 2)
{
for (size_t inv = 0; inv < invals.size(); inv++)
{
net.inneurons[inv].val = invals[inv];
}
//std::cout << "calling feedforward" << '\n';
feedforward(net);
//std::cout << "ff done" << '\n';
softmax(net);
printvals("output", net);//this is just to print weights and
//biases
std::cout << "target: " << '\n';
for (auto element : target) std::cout << element << " / ";
std::cout << '\n';
backprop(net, target);
invals.clear();
target.clear();
count = 0;
}
if (fileread.eof()) break;
}
}
//std::cout << "fourth loop done" << '\n';
return 1;
}
</code></pre>
<p>I know there is probably quite a lot of inefficiency's in the code, while i dont expect anyone to point all if it out. It would be much apreciated to just point out the biggest problems, I am still learning and any criticism is more than welcome.
The input file looks as follows: Example-
in: 0.45 0.62 0.78 0.94
out: 0.0 0.0 1.0
This comes from a function i wrote that basically just adds a 4 random numbers into a vector, sums those 4 numbers and if sum is below 1 output is 1.0 0.0 0.0, if sum is between 1 and 2 output is 0.0 1.0 0.0 and otherwise 0.0 0.0 1.0.</p>
<p>Just a note to anyone wondering, this is a personal project. I am not in university or school, I am self learning :). so this is not homework or something.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T13:20:52.767",
"Id": "502331",
"Score": "1",
"body": "Welcome to the Code Review Community. Questions can contain up to 64K characters and this question is no where close to that. The longer the code is the better we can review it. You might want to make sure that the code is indented in the question the way it is on your computer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T05:23:26.573",
"Id": "502389",
"Score": "0",
"body": "The info is much apreciated! I copied all the code exactly from my compiler and just added 4 spaces to every line. It all looks the same when i cross reference. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:23:27.743",
"Id": "502419",
"Score": "1",
"body": "Just FYI, once you have an answer you should not update the question. You can start a follow up question with any new code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:46:20.733",
"Id": "502426",
"Score": "0",
"body": "awesome, I will keep that in mind :) thank you :)"
}
] |
[
{
"body": "<p>Despite the possibility, that you're going to provide us the full code soon, some hints at first glance:</p>\n<ol>\n<li>Your routine backprop() is too large. I'm not an absolute supporter of always small smart methods/function-bodies, but in your case, sub methods should be considered for better readability.</li>\n<li>Your variable PD has a too 'global' context/scope within your routine, but that's not necessary. Whenever possible, locals should be declared near their actual usage scope. Don't care about performance here if that was your intention! All modern compilers will do their job here perfectly.</li>\n<li>Try to use a quite consistent naming always (as does apply on case sensitivity consistency)! For simple running variables, that's often not a problematic issue but as soon as more context is actually required, a helpful clean naming can save you hours in understanding your own code several months later... :) Especially as a personal preference, I like the distinction between members and locals/parameters.</li>\n<li>With a view on performance: Vectors of vectors can slow down your algorithm in doubt if not used with care (see cache behavior). If that's going to play a more important role here for you, try to profile that early within the development state of your application to be sure, you're using robust 'fundamental' data structures.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T05:27:04.470",
"Id": "502390",
"Score": "1",
"body": "I see, okay I will work on adjusting the backprop code! once I am done, I will add it to the code in question, I will then comment that I have adjusted and if you are available to check it out, hopefully it will be much better :) Much appreciated!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:45:04.797",
"Id": "502425",
"Score": "0",
"body": "Updated :), the net still works in that it doesnt spit out NANS, but it still is not really learning.(the softmax output vals dont move away from around 0.55 0.46 0.02 )."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T20:03:23.227",
"Id": "254714",
"ParentId": "254696",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254714",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T10:42:30.240",
"Id": "254696",
"Score": "1",
"Tags": [
"c++",
"neural-network"
],
"Title": "Neural net backprop code quality"
}
|
254696
|
<p>I'm writing an application with two basic class types:</p>
<ol>
<li>DocumentObject</li>
<li>Property (of document object).</li>
</ol>
<p><code>Property</code> instances are attributes of the <code>DocumentObject</code> class and The <code>Property</code> class has several simple attributes of its own (value, unit, etc.) and some methods.</p>
<p>In trying to make the scripting as user friendly as possible, I would like
<code>objectName.propertyName</code>
to return the value attribute of the Property instance, not the Property instance itself. Of course, it is possible to write <code>objectName.propertyName.value</code> but most of the time, the user will be interacting with the value, not the Property instance.</p>
<p>It seems it should be possible to implement this behaviour using modified <code>__getattr__</code> and <code>__setattr__</code> methods in <code>DocumentObject</code> like in the following example:</p>
<p><strong>Input</strong></p>
<pre><code>class Property():
def __init__(self, name, value, unit='mm'):
self._name = name
self.value = value
self._unit = unit
self._isVisible = True
@property
def name(self):
return self._name
@property
def unit(self):
return self._unit
@property
def isVisible(self):
return self._isVisible
@isVisible.setter
def isVisible(self, value):
self._isVisible = bool(value)
class DocumentObject():
def __init__(self, properties):
object.__setattr__(self, 'properties', dict())
self.properties = properties
def __getattr__(self, name):
if "properties" in vars(self):
if name in self.properties:
return self.properties[name].value
else: raise AttributeError
else: raise AttributeError
def __setattr__(self, key, value):
if key in self.properties:
self.properties[key].value = value
else:
object.__setattr__(self, key, value)
brick = DocumentObject({'length': Property('length',10), 'width': Property('width',5)})
print(brick.properties["length"].name)
print(brick.length)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>length
10
</code></pre>
<p><strong>Questions:</strong></p>
<ol>
<li>Is is good practice to do this?</li>
<li>Are there likely to be some negative consequences of this decision?</li>
<li>Is there a more elegant solution that I have missed?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T16:30:46.810",
"Id": "502352",
"Score": "0",
"body": "Is a property's unit intended to be constant? For example, the length attributes name should always be the constant `\"length\"`; is the length attributes unit a fixed unit (such as `mm`), or can it be changed by the user (ie, `brick.property[\"length\"].units = \"feet\"`)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T09:18:23.933",
"Id": "502408",
"Score": "0",
"body": "```unit``` will probably be constant. But another attribute of Property would be ```isVisible``` which would be a boolean settable by the user. I would implement this using a @property descriptors for isVisible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T09:26:42.757",
"Id": "502409",
"Score": "0",
"body": "I've now implemented this change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T17:30:13.583",
"Id": "502449",
"Score": "0",
"body": "Good first question! It's fine that you've shown an implemented change, but keep in mind that we discourage editing your question once an answer appears."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T17:41:54.693",
"Id": "502452",
"Score": "0",
"body": "Thanks, I'll bear that in mind!"
}
] |
[
{
"body": "<ul>\n<li>Do not write trivial getters/setters; this is not Java/C++/etc. It's more Pythonic to simply have everything public under most circumstances. Private-ness is not enforced anyway and is more of a suggestion.</li>\n<li>Consider using <code>@dataclass</code></li>\n<li>You can drop empty parens after your class definition</li>\n<li>Under what circumstances would it be possible for <code>properties</code> to be missing from <code>DocumentObject</code>? I'm not sure why you check for this. Won't it always be in <code>vars</code>?</li>\n<li>Use type hints.</li>\n<li>Use snake_case, not camelCase for variables</li>\n<li>Do not allow arbitrary <code>__setattr__</code> on your <code>DocumentObject</code> other than to registered properties</li>\n<li>Do not accept a dict with redundant keys; just accept an iterable of properties</li>\n<li>IMO it's less surprising to have the document's actual <code>properties</code> dict override any request to a property named "properties" than the other way around</li>\n</ul>\n<p>Suggested:</p>\n<pre><code>from dataclasses import dataclass\nfrom typing import Dict, Iterable, Union\n\n\n@dataclass\nclass Property:\n name: str\n value: float # ?? or maybe Any\n unit: str = 'mm'\n is_visible: bool = True\n\n\nPropDict = Dict[str, Property]\n\n\nclass DocumentObject:\n def __init__(self, properties: Iterable[Property]):\n self.properties: PropDict = {p.name: p for p in properties}\n self.__setattr__ = self._setattr\n\n def __getattr__(self, name: str) -> Union[PropDict, float]:\n if name == 'properties':\n return self.properties\n return self.properties[name].value\n\n def _setattr(self, key: str, value: float):\n self.properties[key].value = value\n\n\nbrick = DocumentObject((\n Property('length', 10),\n Property('width', 5),\n))\nprint(brick.properties['length'].name)\nprint(brick.length)\nbrick.width = 7\nprint(brick.width)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T17:49:40.457",
"Id": "254758",
"ParentId": "254697",
"Score": "3"
}
},
{
"body": "<blockquote>\n<p>Are there likely to be some negative consequences of this decision?</p>\n</blockquote>\n<p>Absolutely.</p>\n<ol>\n<li>Calling <code>help(DocumentObject)</code> will not tell you what <code>Property</code> attributes exist in your class.</li>\n<li>An IDE won't have any information for autocomplete. Eg) Typing <code>brick.</code> and pressing the <code><TAB></code> key won't offer <code>length</code> and <code>width</code> as possible completions.</li>\n<li>Callers can add, remove and change elements of <code>brick.properties</code>.</li>\n</ol>\n<p>We can get around all of this by defining your own data descriptors.</p>\n<h1>Reworked Code</h1>\n<h2>Data descriptor</h2>\n<p>First, let's create a data descriptor: a class with a <code>__get__</code> and <code>__set__</code> methods. This will allow us to defined a <code>Property</code> on the the <code>DocumentObject</code> class, and control the way things are read from or written to instances of <code>DocumentObject</code> class instances through those properties.</p>\n<p>The name, default value and units of the property can be stored in the property descriptor, since they are read-only values.</p>\n<p>We'll also create a <code>Property.Instance</code> class to hold the data in an instance of the the property in the <code>DocumentObject</code>. Instances of the <code>Property.Instance</code> will have the read-write attributes of <code>value</code>, and <code>visible</code>, as well as a link to the property descriptor for the read-only values.</p>\n<p><code>__slots__</code> is used to prevent additional fields from being set on a property.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Property:\n\n __slots__ = ('name', 'default', 'units', '__doc__',)\n\n def __init__(self, default, units, doc):\n self.default = default\n self.units = units\n self.__doc__ = doc\n\n def __set_name__(self, owner, name):\n self.name = name\n\n def __get__(self, instance, owner=None):\n if instance is None:\n return self\n \n prop = instance._get_property(self.name)\n return prop.value\n\n def __set__(self, instance, value):\n prop = instance._get_property(self.name)\n prop.value = value\n\n class Instance:\n\n __slots__ = ('value', '_visible', '_property')\n\n def __init__(self, prop):\n self._property = prop\n self.value = prop.default\n self._visible = True\n\n @property\n def name(self):\n return self._property.name\n\n @property\n def units(self):\n return self._property.units\n\n @property\n def visible(self):\n return self._visible\n\n @visible.setter\n def visible(self, value):\n self._visible = bool(value)\n\n def __repr__(self):\n return f"Prop[{self.name} {self.value} {self.units} {self.visible}]"\n\n</code></pre>\n<h2>Properties</h2>\n<p>For each <code>DocumentObject</code>, we'll want a container for all of the properties. The <code>_get_property()</code> method we used, above, exacts a named property instance from the container.</p>\n<p>Since we want this container to be a fixed size, with only the named properties defined on the class, we'll create a named tuple with those property instances.</p>\n<p>To make life easy, we'll create the namedtuple of property instances automatically, when the subclass is defined.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import namedtuple\n\nclass Property:\n ...\n\nclass Properties:\n def __init_subclass__(cls):\n cls._property_list = [attr for attr in vars(cls).values()\n if isinstance(attr, Property)]\n \n names = [prop.name for prop in cls._property_list]\n properties_type = namedtuple(cls.__name__ + "Properties", names)\n cls._properties_type = properties_type\n\n def __init__(self):\n property_list = self.__class__._property_list\n properties_type = self.__class__._properties_type\n properties = [Property.Instance(prop) for prop in property_list]\n self._properties = properties_type._make(properties)\n\n def _get_property(self, name):\n return getattr(self._properties, name)\n\n @property\n def properties(self):\n return self._properties\n\n</code></pre>\n<h2>Creating the DocumentObject</h2>\n<p>Deriving the <code>DocumentObject</code> from the <code>Properties</code> class will automatically call the <code>__init_subclass__</code> of the parent class. At this point, it collects all of the <code>Property</code> descriptors, and constructs the <code>namedtuple</code> type for the property container. During the actual <code>super().__init__()</code>, all of the property instances get created, and stored in an instance of the <code>namedtuple</code> type created for this purpose.</p>\n<pre class=\"lang-py prettyprint-override\"><code>\n...\n\nclass DocumentObject(Properties):\n def __init__(self):\n super().__init__()\n\n length = Property(10, "mm", "length of brick, in mm")\n width = Property(5, "mm", "width of brick, in mm")\n\n\nbrick = DocumentObject()\nprint(brick.properties.length.name)\nprint(brick.length)\n</code></pre>\n<h2>Seatbelts</h2>\n<h3>Autocompletion</h3>\n<p>Typing <code>brick.</code> and pressing TAB can autocomplete with <code>length</code> or <code>width</code> (or properties), because those are now named attributes of the <code>DocumentObject</code> class.</p>\n<p>Typing <code>brick.properties.</code> and pressing TAB will also suggest <code>length</code> and <code>width</code> as autocompletions for the property container.</p>\n<h3>Immutability</h3>\n<p>The caller cannot add or change <code>brick.properties</code> because it is an immutable named tuple.</p>\n<p>Of course, the property instances are not immutable, so the the following are all allowed:</p>\n<ul>\n<li><code>brick.properties.length.visible = False</code></li>\n<li><code>brick.properties.length.value = 20</code></li>\n<li><code>brick.length = 30</code></li>\n</ul>\n<h3>Help</h3>\n<p>Typing <code>help(DocumentObject)</code> now produces:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Help on class DocumentObject in module __main__:\n\nclass DocumentObject(Properties)\n | ...\n |\n | Data descriptors defined here:\n | \n | length\n | length of brick, in mm\n | \n | width\n | width of brick, in mm\n | \n | ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T19:17:01.060",
"Id": "254762",
"ParentId": "254697",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T10:59:46.927",
"Id": "254697",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"object-oriented"
],
"Title": "Modifying __getattr__ to return a nested attribute instead of the named object"
}
|
254697
|
<p>I wrote a simulator that simulates chess games. The game uses probability to determine the player that is most likely to win. though they might be upsets(a low rated player winning the game). I would love insights and suggestions on how to improve on the algorithm, general review is also welcomed.</p>
<p>NOTE: The names and rating were gotten from <code>chess.com</code> application and the code were written in <code>jupyter-notebook</code></p>
<pre><code>"""Chess Game simulator"""
import random
import time
NAMES = ['Jimmy', 'Samie', 'Elani', 'Aron', 'Emir', 'Sven', 'Nelson',
'Antonio', 'Isabel', 'Wally', 'Li', 'Noam', 'Francis', 'Danya',
'Danny', 'Engine']
RATINGS = [600, 900, 400, 700, 1000, 1100,
1300, 1500, 1600, 1800, 2000,
2200, 2300, 2650, 2500, 1000]
class Player:
"""This class holds the player information"""
def __init__(self, name, rating):
self.name = name
self.rating = rating
self.opponent = None
def __repr__(self):
return 'Player({}, {})'.format(self.name, self.rating)
class ChessGame():
def __init__(self, players):
self.players = players
self.tournament_rounds = {1: 'Round 1', 2: 'Round 2', 3: 'Semi-final', 4: 'Final'}
self.game_round = 0
def next_round(self):
"""Go the next round of the tournament"""
self.game_round += 1
try:
print(self.tournament_rounds[self.game_round])
except KeyError:
return
def make_pair(self):
"""Combine two players randomly to play a chess game"""
players = self.players[:]
new_players = []
while players:
player1 = random.choice(players)
players.remove(player1)
player2 = random.choice(players)
players.remove(player2)
player1.opponent = player2
player2.opponent = player1
new_players.append(player1)
self.players = new_players
def game(self):
"""run the simulation"""
if len(self.players) < 2:
print('Exception: Not enough players to play a game')
return
self.next_round()
print('--------------------------------------------')
self.make_pair()
for player in self.players:
print(f'{player.name}({player.rating}) vs {player.opponent.name}({player.opponent.rating})')
time.sleep(3)
print('--------------------------------------------')
self.players = self.score_game()
def score_game(self):
"""Score the game using probabilities"""
winners = []
for player in self.players:
total_rating = player.rating + player.opponent.rating
player_chance = player.rating / total_rating
maximum_range = 1000
player_range = [i for i in range(0, int(player_chance * maximum_range))]
choice = random.randint(0, maximum_range)
if choice in player_range:
print(f'{player.name} wins this round by checkmate')
player.rating += self.game_round * 200
winners.append(player)
else:
print(f'{player.opponent.name} wins this round by checkmate')
player.opponent.rating += self.game_round * 200
winners.append(player.opponent)
return winners
CHESS_PLAYERS = [Player(name, rating) for name, rating in zip(NAMES, RATINGS)]
CHESS_SIM = ChessGame(CHESS_PLAYERS)
CHESS_SIM.game()
print()
CHESS_SIM.game()
print()
CHESS_SIM.game()
print()
CHESS_SIM.game()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T05:57:31.427",
"Id": "502391",
"Score": "5",
"body": "It's unrealistic that there is never a draw, each game is win by someone. That's probably why chess tournaments use the Swiss System for drawing the rounds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T22:14:06.033",
"Id": "502475",
"Score": "1",
"body": "Given that we're talking chess, the rating points you're using are probably based on ELO or glicko rating system (that's what chess.com uses afaik, ELO is used by FIDE). You should look up how those work, because Daniel Naroditsky (a 2600 GM) having a 72% chance to win against a chess beginner with 1000 points is not exactly realistic."
}
] |
[
{
"body": "<h2>Use immutable sequences</h2>\n<p>Turn</p>\n<pre><code>NAMES = ['Jimmy', 'Samie', 'Elani', 'Aron', 'Emir', 'Sven', 'Nelson',\n 'Antonio', 'Isabel', 'Wally', 'Li', 'Noam', 'Francis', 'Danya',\n 'Danny', 'Engine']\n \nRATINGS = [600, 900, 400, 700, 1000, 1100,\n 1300, 1500, 1600, 1800, 2000,\n 2200, 2300, 2650, 2500, 1000]\n</code></pre>\n<p>into tuples instead of lists, because they're constants.</p>\n<h2>Use data classes</h2>\n<pre><code>class Player:\n """This class holds the player information"""\n\n def __init__(self, name, rating):\n self.name = name\n self.rating = rating\n self.opponent = None\n\n def __repr__(self):\n return 'Player({}, {})'.format(self.name, self.rating)\n</code></pre>\n<p>does not need an explicit <code>__init__</code> if you make it a <code>@dataclass</code>:</p>\n<pre><code>@dataclass\nclass Player:\n """This class holds the player information"""\n name: str\n rating: int\n opponent: Optional['Player']\n</code></pre>\n<p>though I don't think that it's appropriate to represent <code>opponent</code> as an attribute of a player. That belongs to the game state.</p>\n<h2>Sequence representation</h2>\n<p>Consider changing</p>\n<pre><code> self.tournament_rounds = {1: 'Round 1', 2: 'Round 2', 3: 'Semi-final', 4: 'Final'}\n</code></pre>\n<p>into a global (or class-static) tuple of strings:</p>\n<pre><code>TOURNAMENT_ROUNDS = ('Round 1', 'Round 2', 'Semi-final', 'Final')\n</code></pre>\n<p>The indices as keys are redundant.</p>\n<h2>Iterators and responsibilities</h2>\n<pre><code>def next_round(self):\n """Go the next round of the tournament"""\n\n self.game_round += 1\n\n try:\n print(self.tournament_rounds[self.game_round])\n except KeyError:\n return\n</code></pre>\n<p>and</p>\n<pre><code> print(f'{player.name} wins this round by checkmate')\n player.rating += self.game_round * 200\n</code></pre>\n<p>seem dicey to me in terms of OOP representation. You'd be better-off having the game class yield a generator of rounds. This will make the game instance reusable.</p>\n<p>Your <code>score_game</code> has the following responsibilities baked in - game simulation, and game presentation. These need to be separated - your <code>score_game</code> should not be printing. Also, <code>score_game</code> is itself not a great name, since it's not just scoring the game - it's actually <em>running</em> the game simulation.</p>\n<h2>Random selection</h2>\n<pre><code> maximum_range = 1000\n player_range = [i for i in range(0, int(player_chance * maximum_range))]\n choice = random.randint(0, maximum_range)\n if choice in player_range:\n</code></pre>\n<p>needs to be re-thought. Currently you're constructing a list, in memory, of every single number from 0 through (up to) 1000 only to do a membership test and then throw the whole thing away. Instead, just generate a random number and compare it to an upper bound.</p>\n<h2>Sleepy code</h2>\n<p>Don't arbitrarily add <code>sleep</code>. If you want to space out your console interface between logical operations, wait for a keypress.</p>\n<h2>Suggested</h2>\n<pre><code>"""Chess Game simulator"""\n\nfrom dataclasses import dataclass\nfrom random import shuffle, randrange\nfrom typing import ClassVar, Tuple, Iterable, Dict\n\n\n@dataclass\nclass Player:\n name: str\n rating: int\n\n def __str__(self):\n return f'{self.name}({self.rating})'\n\n\nCHESS_PLAYERS = [\n Player(name, rating)\n for rating, name in (\n ( 600, 'Jimmy'),\n ( 900, 'Samie'),\n ( 400, 'Elani'),\n ( 700, 'Aron'),\n (1000, 'Emir'),\n (1100, 'Sven'),\n (1300, 'Nelson'),\n (1500, 'Antonio'),\n (1600, 'Isabel'),\n (1800, 'Wally'),\n (2000, 'Li'),\n (2200, 'Noam'),\n (2300, 'Francis'),\n (2650, 'Danya'),\n (2500, 'Danny'),\n (1000, 'Engine'),\n )\n]\n\n\nclass Match:\n def __init__(self, p1: Player, p2: Player):\n self.p1, self.p2 = p1, p2\n total = self.p1.rating + self.p2.rating\n if randrange(total) < self.p1.rating:\n self.winner = self.p1\n else:\n self.winner = self.p2\n\n def __str__(self):\n return f'{self.p1} vs {self.p2}'\n\n @property\n def outcome(self) -> str:\n return f'{self.winner} wins this round by checkmate'\n\n\nclass Round:\n def __init__(self, name: str, matches: Iterable[Match]):\n self.name = name\n self.matches = tuple(matches)\n\n def print(self):\n print(self.name)\n print('-'*45)\n print('\\n'.join(str(match) for match in self.matches))\n print('-'*45)\n print('\\n'.join(match.outcome for match in self.matches))\n\n\nclass ChessGame:\n ROUND_NAMES: ClassVar[Tuple[str]] = ('Round 1', 'Round 2', 'Semi-final', 'Final')\n\n def __init__(self, players: Iterable[Player]):\n self.players: Tuple[Player] = tuple(players)\n\n def __iter__(self) -> Iterable[Round]:\n players = list(self.players)\n\n for i_round, name in enumerate(self.ROUND_NAMES):\n shuffle(players)\n half = len(players)//2\n round = Round(\n name,\n (\n Match(p1, p2)\n for p1, p2 in zip(players[:half], players[half:])\n )\n )\n yield round\n\n for match in round.matches:\n match.winner.rating += (i_round + 1) * 200\n\n players = [match.winner for match in round.matches]\n\n def print_run(self):\n for round in self:\n round.print()\n print()\n\n\ndef main():\n sim = ChessGame(CHESS_PLAYERS)\n sim.print_run()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>The biggest 'gotcha' here is that, whereas the <code>ChessGame</code> is now reusable, player instances (just as in your original code) are mutated, so if you want to do repeated simulations you have to make copies of your player instances.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T21:53:17.077",
"Id": "502375",
"Score": "3",
"body": "I really love the idea of a `dataclass`, great review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T19:04:50.183",
"Id": "254710",
"ParentId": "254699",
"Score": "8"
}
},
{
"body": "<p>In addition to what @Reinderien mentioned, here are a few things I noticed.</p>\n<p>It would be beneficial to store the players and ratings in a more meaningful format</p>\n<pre><code>PLAYERS = [\n Player(name, rating)\n for name, rating in [\n ('Jimmy', 600), ('Samie', 900),\n ('Elani', 400), ('Aron', 700),\n ('Emir', 1000), ('Sven', 1100),\n ('Nelson', 1300), ('Antonio', 1500),\n ('Isabel', 1600), ('Wally', 1800),\n ('Li', 2000), ('Noam', 2200),\n ('Francis', 2300), ('Danya', 2650),\n ('Danny', 2500), ('Engine', 1000)\n ]\n]\n</code></pre>\n<p>The tournament round naming is quite brittle and could be fixed by solving the problem in the reverse order.</p>\n<pre><code>def round_name(self) -> str:\n if len(self.players) == 2:\n return 'Final'\n if len(self.players) == 4:\n return 'Semi-final'\n return f'Round {self.round}'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T19:24:27.253",
"Id": "254712",
"ParentId": "254699",
"Score": "7"
}
},
{
"body": "<p>Your current way of pairing players is <span class=\"math-container\">\\$O(n^2)\\$</span> due to using the remove method. Each remove is <span class=\"math-container\">\\$O(n)\\$</span> since all the values that come after the removed value need to be moved back 1 index position. To make the whole function <span class=\"math-container\">\\$O(n)\\$</span>, you could use random.shuffle instead of random.choice. You could do something like:</p>\n<pre><code>random.shuffle(self.players)\nfor n in range(len(self.players) // 2):\n pair opponent n with opponent n + len(self.players) // 2\ndel self.players[len(self.players) // 2:]\n</code></pre>\n<p>This also would deal with odd numbers of players by leaving out whoever was the last player in self.players after shuffling.</p>\n<p>Also, you could write a method that simulates each game until the tournament is over instead of manually calling CHESS_SIM.game.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T21:56:35.807",
"Id": "502376",
"Score": "0",
"body": "The problem is what if the games are spaced between 2 days interval?. I thought about this, I just figured that explicitly calling a simulation when needed would be fine. I really don't wanna pause a simulation to the exact day of the match."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T22:41:27.140",
"Id": "502379",
"Score": "2",
"body": "You can have your cake and eat it too: an `__iter__` approach such as the one I've shown is both centralized and \"pauseable\" just like any standard Python iterator."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T20:04:29.433",
"Id": "254715",
"ParentId": "254699",
"Score": "4"
}
},
{
"body": "<p>In terms of chess you seem to have missed some things (in addition it would be rare with such a tournament) that will require updates in the logic:</p>\n<ul>\n<li>If the number of players is not a power of two (there is likely to be some no-show) you will fail in make_pair as you will have an odd number of players and select one player and then not have an opponent.</li>\n<li>I would also use pre-tournament ratings for win-chance and do rating updates afterwards; as players don't become stronger by beating a weaker opponent during the tournament.</li>\n<li>The loser normally loses rating correspondingly, and keeping track of rating is important even if they don't play more in that tournament.</li>\n<li>White is more likely to win, so you should adjust win-chance.</li>\n<li>At least the final would often have more than one game (due to color).</li>\n<li>Games can end in a draw (with more complicated rating update); obviously that will require some way to determine the winner - in some cases that would be a blitz chess playoff that doesn't influence rating. Another option would be to have more normal games between the players (as above), and then blitz if even.</li>\n<li>Games in rated tournaments are rarely won by check-mate (even if not draw), thus just write "wins" not "wins by checkmate". In general avoid adding such unnecessary details.</li>\n</ul>\n<p>The simplest solution for many of these items would be to view it as a tennis-tournament instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T18:42:26.393",
"Id": "502453",
"Score": "0",
"body": "Am fairly new to chess, what do you mean by `white is more likely to win`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T22:11:14.347",
"Id": "502474",
"Score": "1",
"body": "In practice white, who starts, is as far as I recall more likely to win when the two players are of equal strength."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T16:00:31.930",
"Id": "254754",
"ParentId": "254699",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254710",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T12:56:04.483",
"Id": "254699",
"Score": "9",
"Tags": [
"python-3.x"
],
"Title": "Chess Tournament Simulator"
}
|
254699
|
<p>I have written a function <code>splitAtPredicate</code> that splits the list at element <code>x</code> satisfying <code>p</code>, dropping <code>x</code> and returning a tuple.</p>
<pre><code>-- | 'splitAtPredicate', applied to a predicate @p@ and a list @xs@,
-- splits the list at element @x@ satisfying @p@, dropping @x@.
splitAtPredicate :: (a -> Bool) -> [a] -> ([a], [a])
splitAtPredicate p = splitAtPredicateAcc p []
where
splitAtPredicateAcc p left right@(x : xs')
| null right = (left, right)
| p x = (left, xs')
| otherwise = splitAtPredicateAcc p (left ++ [x]) xs'
</code></pre>
<p>It works, but I'm new to Haskell, so I'm unsure how idiomatic and performant this is. In addition, I'm not too happy with the name <code>splitAtPredicateAcc</code>. Any suggestions are more than welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T13:53:57.803",
"Id": "502334",
"Score": "1",
"body": "from the description, `splitAtPredicate even [2]` and `splitAtPredicate even []` will both return the same result? also, it should be `right@ ~(x : xs')`. you say it works, but as written now, `splitAtPredicate even []` should cause error AFAICT. have you tested?"
}
] |
[
{
"body": "<p>Welcome to the Haskell community :)</p>\n<p>Haskellers like composition. Your logic is composed of 2 parts:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>splitWhen :: (a -> Bool) -> [a] -> [[a]]\n</code></pre>\n<pre class=\"lang-hs prettyprint-override\"><code>toTuple :: [[a]] -> ([a], [a])\n</code></pre>\n<hr />\n<p>Let's address <code>splitWhen</code> first.</p>\n<p>E.g. <code>splitWhen (== '2') "132342245"</code> should be <code>["13", "33", "", "45"]</code>.</p>\n<p>To illustrate how it works:</p>\n<pre><code>initial state: (unconsumed input: "132332245", aggregator: [""])\nstep 1: (current input: '1', unconsumed input: "32342245", aggregator: ["1"])\nstep 2: (current input: '3', unconsumed input: "2332245", aggregator: ["13"])\nstep 3: (current input: '2', unconsumed input: "332245", aggregator: ["13",""])\nstep 4: (current input: '3', unconsumed input: "32245", aggregator: ["13","3"])\nstep 5: (current input: '3', unconsumed input: "2245", aggregator: ["13","33"])\nstep 5: (current input: '2', unconsumed input: "245", aggregator: ["13","33", ""])\nstep 6: (current input: '2', unconsumed input: "45", aggregator: ["13","33", "", ""])\nstep 7: (current input: '4', unconsumed input: "5", aggregator: ["13","33", "", "4"])\nstep 8: (current input: '5', unconsumed input: "", aggregator: ["13","33", "", "45"])\n</code></pre>\n<p>There are many ways to write this in Haskell, for example if we call the above logic <code>f</code>:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>splitWhen :: (a -> Bool) -> [a] -> [[a]]\nsplitWhen p xs = f xs [] -- the initial aggregator\n where f [] agg = [agg]\n f (y : ys) agg = if p y\n then agg : f ys [] -- we are ignoring the element here\n else f ys (agg ++ [y]) -- put y into the aggregator\n</code></pre>\n<ul>\n<li><p>Notice the pattern match <code>(y : ys)</code>, they are the current input and unconsumed input.</p>\n</li>\n<li><p>Notice the recursive function call of <code>f</code>.</p>\n</li>\n</ul>\n<hr />\n<p><code>toTuple</code> is trivial:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>toTuple :: [[a]] -> ([a], [a])\ntoTuple [] = ([], [])\ntoTuple [xs] = (xs, [])\ntoTuple (xs:ys:_) = (xs, ys)\n</code></pre>\n<hr />\n<p>Finally the exiting part - function composition:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>splitAtPredicate :: (a -> Bool) -> [a] -> ([a], [a])\nsplitAtPredicate p = toTuple . splitWhen p\n</code></pre>\n<p>or if you are not yet comfortable with the pointfree style</p>\n<pre class=\"lang-hs prettyprint-override\"><code>splitAtPredicate :: (a -> Bool) -> [a] -> ([a], [a])\nsplitAtPredicate p xs = toTuple . splitWhen p xs\n</code></pre>\n<p>Because Haskell's lazy nature, <code>splitAtPredicate</code> will stop when it finds the second element that satisfies the predicate, as we have enough data to construct the pair.</p>\n<p>To put everything together:</p>\n<pre class=\"lang-hs prettyprint-override\"><code>splitWhen :: (a -> Bool) -> [a] -> [[a]]\nsplitWhen p xs = f xs [] -- the initial aggregator\n where f [] agg = [agg]\n f (y : ys) agg = if p y\n then agg : f ys [] -- we are ignoring the element here\n else f ys (agg ++ [y]) -- put y into the aggregator\n\ntoTuple :: [[a]] -> ([a], [a])\ntoTuple [] = ([], [])\ntoTuple [xs] = (xs, [])\ntoTuple (xs:ys:_) = (xs, ys)\n\nsplitAtPredicate :: (a -> Bool) -> [a] -> ([a], [a])\nsplitAtPredicate p = toTuple . splitWhen p\n</code></pre>\n<p>Hope that helps :) And again welcome to the Haskell world.</p>\n<p>If you haven't done it already, checkout <a href=\"https://hoogle.haskell.org\" rel=\"nofollow noreferrer\">https://hoogle.haskell.org</a> , you'll love it :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T07:15:56.330",
"Id": "254984",
"ParentId": "254700",
"Score": "1"
}
},
{
"body": "<p>Replace accumulators by post-processing when possible.</p>\n<pre><code>splitAtPredicate :: (a -> Bool) -> [a] -> ([a], [a])\nsplitAtPredicate p [] = ([], [])\nsplitAtPredicate p (x:xs)\n | p x = ([], xs)\n | otherwise = let (left, right) = splitAtPredicate p xs in (x:left, right)\n</code></pre>\n<p>Use existing library functions.</p>\n<pre><code>splitAtPredicate p xs = let (left, right) = break p xs in (left, drop 1 right)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T12:05:05.890",
"Id": "254993",
"ParentId": "254700",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254984",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T13:05:51.957",
"Id": "254700",
"Score": "1",
"Tags": [
"haskell",
"linked-list"
],
"Title": "Splitting a list by predicate"
}
|
254700
|
<p>Hello I've created to do app with some additional functionality. <br></p>
<p>Since I am new in JS I would love some feedback if you guys could point out some obvious mistakes/good practices/better solutions or implementations I will be grateful.<br></p>
<p>HTML</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style/main.css" />
<title>To do app</title>
</head>
<body>
<div class="container">
<div class="banner">
<h2>Welcome</h2>
<div class="timestamp">
<div class="timestamp__time">12:20</div>
<div class="timestamp__date">Tuesday, 5 January</div>
</div>
</div>
<div class="sidebar">
<h3>Your lists</h3>
<div class="lists">
<div class="list active">
<svg class="list__icon">
<use xlink:href="img/icons/sprite.svg#icon-bookmark"></use>
</svg>
<input class="list__title" value="Important" readonly />
<div class="list__options">
<div class="option"></div>
<div class="option"></div>
</div>
</div>
<div class="list">
<svg class="list__icon">
<use xlink:href="img/icons/sprite.svg#icon-light-bulb"></use>
</svg>
<input class="list__title" value="Ideas" readonly />
<div class="list__options">
<div class="option"></div>
<div class="option"></div>
</div>
</div>
<div class="list">
<svg class="list__icon">
<use xlink:href="img/icons/sprite.svg#icon-shopping-basket"></use>
</svg>
<input class="list__title" value="Groceries" readonly />
<div class="list__options">
<div class="option"></div>
<div class="option"></div>
</div>
</div>
</div>
<div class="add-list-container">
<div class="add-list">
<img src="img/plus.svg" alt="plus sign" />
<p>New list</p>
</div>
</div>
</div>
<main class="main-section">
<div class="main">
<div class="todo show" id="Important">
<div class="item">
<div class="item__wrapper">
<div class="item__check item__check--done">
<img src="img/checkmark.svg" alt="checkmark" />
</div>
<input class="item__title item__title--done" value="Walk the dog" readonly />
</div>
<div class="item__options hide">
<img src="img/pen.svg" alt="pen" class="item-rename" />
<img src="img/trash.svg" alt="trash" class="item-delete" />
</div>
</div>
<div class="item">
<div class="item__wrapper">
<div class="item__check">
<img src="img/checkmark.svg" alt="checkmark" />
</div>
<input class="item__title" value="Finish essay" readonly />
</div>
<div class="item__options hide">
<img src="img/pen.svg" alt="pen" class="item-rename" />
<img src="img/trash.svg" alt="trash" class="item-delete" />
</div>
</div>
</div>
<div class="todo" id="Ideas">
<div class="item">
<div class="item__wrapper">
<div class="item__check">
<img src="img/checkmark.svg" alt="checkmark" />
</div>
<input class="item__title" value="Weight loss tracker" readonly />
</div>
<div class="item__options hide">
<img src="img/pen.svg" alt="pen" class="item-rename" />
<img src="img/trash.svg" alt="trash" class="item-delete" />
</div>
</div>
<div class="item">
<div class="item__wrapper">
<div class="item__check">
<img src="img/checkmark.svg" alt="checkmark" />
</div>
<input class="item__title" value="Meal planning" readonly />
</div>
<div class="item__options hide">
<img src="img/pen.svg" alt="pen" class="item-rename" />
<img src="img/trash.svg" alt="trash" class="item-delete" />
</div>
</div>
</div>
<div class="todo" id="Groceries">
<div class="item">
<div class="item__wrapper">
<div class="item__check">
<img src="img/checkmark.svg" alt="checkmark" />
</div>
<input class="item__title" value="Milk" readonly />
</div>
<div class="item__options hide">
<img src="img/pen.svg" alt="pen" class="item-rename" />
<img src="img/trash.svg" alt="trash" class="item-delete" />
</div>
</div>
<div class="item">
<div class="item__wrapper">
<div class="item__check">
<img src="img/checkmark.svg" alt="checkmark" />
</div>
<input class="item__title" value="Broccoli" readonly />
</div>
<div class="item__options hide">
<img src="img/pen.svg" alt="pen" class="item-rename" />
<img src="img/trash.svg" alt="trash" class="item-delete" />
</div>
</div>
</div>
</div>
<div class="add-item">
<img src="img/plus.svg" alt="plus sign" />
<p>New item</p>
</div>
</main>
</div>
<script src="script.js"></script>
</body>
</html>
</code></pre>
<p>CSS (generated by SAS)</p>
<pre class="lang-css prettyprint-override"><code>@import url("https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600&display=swap");
*,
*::after,
*::before {
margin: 0;
padding: 0;
text-decoration: none;
-webkit-box-sizing: border-box;
box-sizing: border-box;
font-family: 'Quicksand', sans-serif;
}
html {
font-size: 62.5%;
}
body {
height: 100vh;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.container {
display: -ms-grid;
display: grid;
width: 100%;
height: 100%;
grid-template-areas: 'banner banner banner'
'sidebar main main'
'sidebar main main';
-ms-grid-columns: 35rem 1fr 1fr;
grid-template-columns: 35rem 1fr 1fr;
-ms-grid-rows: 23rem 1fr 1fr;
grid-template-rows: 23rem 1fr 1fr;
}
.container .main-section {
-ms-grid-row: 2;
-ms-grid-row-span: 2;
-ms-grid-column: 2;
-ms-grid-column-span: 2;
grid-area: main;
}
.banner {
background-image: url(../img/banner.svg);
background-repeat: no-repeat;
background-size: cover;
background-position: bottom;
-ms-grid-row: 1;
-ms-grid-column: 1;
-ms-grid-column-span: 3;
grid-area: banner;
color: #fff;
padding: 3rem 5rem;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
}
.banner .timestamp__time {
font-size: 7rem;
font-weight: 300;
}
.banner .timestamp__date {
font-weight: 500;
font-size: 2rem;
}
.banner h2 {
font-size: 3rem;
font-weight: 600;
}
.sidebar {
background-color: #f5f5f5;
-ms-grid-row: 2;
-ms-grid-row-span: 2;
-ms-grid-column: 1;
grid-area: sidebar;
}
.sidebar h3 {
margin-bottom: 4rem;
margin-top: 5rem;
font-size: 2.5rem;
font-weight: 600;
padding: 0 5rem;
}
.sidebar .list {
display: -ms-grid;
display: grid;
-ms-grid-columns: (1fr)[3];
grid-template-columns: repeat(3, 1fr);
padding: 2rem 5rem;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
position: relative;
}
.sidebar .list__icon {
width: 2.2rem;
height: 2.2rem;
fill: currentColor;
}
.sidebar .list:hover {
background-color: #fff;
cursor: pointer;
}
.sidebar .list__title {
font-size: 2rem;
margin-left: 0.5rem;
background: none;
border: none;
color: #000;
outline: none;
display: inline-block;
cursor: pointer;
}
.sidebar .list .icon-modal {
border-radius: 3px;
padding: 3rem;
margin-left: 5rem;
position: absolute;
background-color: #fff;
bottom: 100%;
width: 100%;
}
.sidebar .list .icon-modal > * {
margin: 0.7rem;
fill: black;
cursor: pointer;
}
.sidebar .list .icon-modal::after {
position: absolute;
content: '';
left: 0;
top: 100%;
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 15px solid #fff;
}
.sidebar .list__options {
position: relative;
padding: 0.5rem;
}
.sidebar .list__options .list-modal {
position: absolute;
background-color: white;
color: black;
bottom: 100%;
left: 50%;
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
width: 10rem;
font-weight: 600;
font-size: 1.2rem;
margin-bottom: 1rem;
}
.sidebar .list__options .list-modal p {
padding: 0.5rem 1rem;
}
.sidebar .list__options .list-modal p:hover {
cursor: pointer;
background-color: #ff3366;
color: #fff;
}
.sidebar .list .icon-modal-close {
width: 2rem;
height: 2rem;
position: absolute;
top: 5px;
right: 5px;
}
.sidebar .list .option {
background-color: black;
width: 0.6rem;
border-radius: 50%;
height: 0.6rem;
}
.sidebar .list .option:first-child {
margin-bottom: 0.6rem;
}
.sidebar .add-list-container {
padding: 2rem 5rem;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
font-size: 2rem;
}
.sidebar .add-list-container .add-list {
cursor: pointer;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-ms-flex-item-align: start;
align-self: flex-start;
}
.sidebar .add-list-container .add-list img {
width: 3rem;
}
.todo {
font-size: 5rem;
display: none;
}
.item {
padding: 3rem 5rem;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-shadow: 0 2px 2px -2px gray;
box-shadow: 0 2px 2px -2px gray;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: justify;
-ms-flex-pack: justify;
justify-content: space-between;
}
.item__wrapper {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
}
.item__check {
width: 2.5rem;
height: 2.5rem;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
border-radius: 50%;
border: 1px solid black;
cursor: pointer;
}
.item__check--done {
background-color: #40d628;
border: none;
}
.item__check img {
width: 1.5rem;
height: 1.5rem;
}
.item__title {
font-size: 2rem;
margin-left: 1rem;
background: none;
border: none;
color: #000;
outline: none;
display: inline-block;
}
.item__title--done {
text-decoration: line-through;
}
.item__options {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
.item__options img {
cursor: pointer;
width: 2.5rem;
height: 2.5rem;
}
.item__options img:not(:first-child) {
margin-left: 2rem;
}
.add-item {
padding: 3rem 5rem;
-webkit-box-shadow: 0 2px 2px -2px gray;
box-shadow: 0 2px 2px -2px gray;
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
font-size: 2rem;
cursor: pointer;
}
.add-item img {
width: 3rem;
}
.active {
background-color: #ff3366;
color: #fff;
}
.active .list__title {
color: white !important;
cursor: auto;
}
.active .list__icon {
fill: currentColor;
}
.active:hover {
background-color: #ff3366 !important;
cursor: auto !important;
}
.active .option {
background-color: white !important;
}
.show {
display: block;
}
.hide {
display: none !important;
}
/*# sourceMappingURL=main.css.map */
</code></pre>
<p>JS</p>
<pre class="lang-javascript prettyprint-override"><code>'use strict';
// #######################################
// DATE & TIME
const timeBox = document.querySelector('.timestamp__time');
const dateBox = document.querySelector('.timestamp__date');
let now, hours, minutes;
const clock = () => {
now = new Date();
hours = now.getHours();
minutes = now.getMinutes();
hours < 10 ? (hours = `0${hours}`) : hours;
minutes < 10 ? (minutes = `0${minutes}`) : minutes;
timeBox.textContent = `${hours}:${minutes}`;
};
setInterval(clock, 1000);
const setDate = () => {
now = new Date();
let weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let months = ['January', 'February', 'March', 'April', 'May', 'Juny', 'July', 'August', 'September', 'October', 'November', 'December'];
// now.getDay() - returns 0-6
let weekDay = weekDays[now.getDay()];
let day = now.getDate();
let month = months[now.getMonth()];
dateBox.textContent = `${weekDay}, ${day} ${month}`;
};
setDate();
// #######################################
// SWITCHING BETWEEN LISTS
const listsContainer = document.querySelector('.lists');
let lists = document.querySelectorAll('.list');
let activeList = lists[0];
// Add eventListener to lists
const setUpListsListeners = () => {
lists = document.querySelectorAll('.list');
for (let i = 0; i < lists.length; i++) {
lists[i].addEventListener('click', () => {
if (!lists[i]) return;
if (!lists[i].classList.contains('active')) switchList(lists[i]); // listener only for non active lists
});
}
};
// call to setUp 3 primary lists
setUpListsListeners();
const switchList = (list) => {
if (typeof activeList !== 'undefined') {
// for more than 1 list
// 'turn off' active list
activeList.classList.toggle('active');
document.querySelector(`#${activeList.children[1].value}`).classList.toggle('show');
}
// switch list by 'turning on' list from param
activeList = list;
activeList.classList.toggle('active');
document.querySelector(`#${activeList.children[1].value}`).classList.toggle('show'); // display to'do items for this list
};
// #######################################
// MODAL
// parent in this case is a list in which we click settings - prevents opening multiple modals
let optionsParent;
const openModal = (parent) => {
// create 3 different elements for each event - icon change, rename, delete
const modal = document.createElement('div');
modal.className = 'list-modal';
const rename = document.createElement('p');
rename.className = 'rename';
rename.textContent = 'Rename';
modal.appendChild(rename);
const changeIcon = document.createElement('p');
changeIcon.className = 'change-icon';
changeIcon.textContent = 'Change icon';
modal.appendChild(changeIcon);
const deleteList = document.createElement('p');
deleteList.className = 'delete';
deleteList.textContent = 'Delete';
modal.appendChild(deleteList);
parent.appendChild(modal);
optionsParent = parent;
activateModalButtons();
};
const closeModal = (parent) => {
const modal = document.querySelector('.list-modal');
if (!modal) return;
parent.removeChild(modal);
optionsParent = false;
};
// function that checks if we click in either option circular icon or it's container
// if it's already opened and we click outside it - closeModal()
// if yes then openModal()
window.addEventListener('click', function (e) {
if (optionsParent) closeModal(optionsParent);
if (e.target.classList.contains('list__options')) openModal(e.target);
if (e.target.classList.contains('option')) openModal(e.target);
});
// #######################################
// MODAL - RENAME, CHANGE ICON & DELETE
const activateModalButtons = () => {
const renameBtn = document.querySelector('.rename');
const deleteBtn = document.querySelector('.delete');
const changeIconBtn = document.querySelector('.change-icon');
const currentList = activeList.children[1];
renameBtn.addEventListener('click', () => {
renameList(currentList);
});
deleteBtn.addEventListener('click', (e) => {
e.stopPropagation();
// remove lists on which we click delete button
listsContainer.removeChild(activeList);
document.querySelector(`#${activeList.children[1].value}`).classList.add('hide');
lists = document.querySelectorAll('.list');
// activate first list
activeList = lists[0];
if (!activeList) return; // return when there is no more lists
activeList.classList.toggle('active');
document.querySelector(`#${activeList.children[1].value}`).classList.toggle('show');
// refresh listeners for lists
setUpListsListeners();
});
changeIconBtn.addEventListener('click', (e) => {
e.stopPropagation();
openIconModal(activeList);
});
};
// icon change
const openIconModal = (parent) => {
const iconModal = document.createElement('div');
iconModal.className = 'icon-modal';
iconModal.innerHTML = `
<svg class="list__icon" id="icon-shopping-basket">
<use xlink:href="img/icons/sprite.svg#icon-shopping-basket"></use>
</svg>
<svg class="list__icon" id="icon-bookmark">
<use xlink:href="img/icons/sprite.svg#icon-bookmark"></use>
</svg>
<svg class="list__icon" id="icon-beamed-note">
<use xlink:href="img/icons/sprite.svg#icon-beamed-note"></use>
</svg>
<svg class="list__icon" id="icon-bowl">
<use xlink:href="img/icons/sprite.svg#icon-bowl"></use>
</svg>
<svg class="list__icon" id="icon-clipboard">
<use xlink:href="img/icons/sprite.svg#icon-clipboard"></use>
</svg>
<svg class="list__icon" id="icon-credit-card">
<use xlink:href="img/icons/sprite.svg#icon-credit-card"></use>
</svg>
<svg class="list__icon" id="icon-globe">
<use xlink:href="img/icons/sprite.svg#icon-globe"></use>
</svg>
<svg class="list__icon" id="icon-heart">
<use xlink:href="img/icons/sprite.svg#icon-heart"></use>
</svg>
<svg class="list__icon" id="icon-home">
<use xlink:href="img/icons/sprite.svg#icon-home"></use>
</svg>
<svg class="list__icon" id="icon-hour-glass">
<use xlink:href="img/icons/sprite.svg#icon-hour-glass"></use>
</svg>
<svg class="list__icon" id="icon-laptop">
<use xlink:href="img/icons/sprite.svg#icon-laptop"></use>
</svg>
<svg class="list__icon" id="icon-light-bulb">
<use xlink:href="img/icons/sprite.svg#icon-light-bulb"></use>
</svg>
<svg class="list__icon" id="icon-location-pin">
<use xlink:href="img/icons/sprite.svg#icon-location-pin"></use>
</svg>
<svg class="list__icon" id="icon-thumbs-up">
<use xlink:href="img/icons/sprite.svg#icon-thumbs-up"></use>
</svg>
<svg class="list__icon" id="icon-suitcase">
<use xlink:href="img/icons/sprite.svg#icon-suitcase"></use>
</svg>
<svg class="list__icon" id="icon-mail">
<use xlink:href="img/icons/sprite.svg#icon-mail"></use>
</svg>
<img src="img/close.svg" class="icon-modal-close">
`;
parent.appendChild(iconModal);
const iconModalCloseBtn = document.querySelector('.icon-modal-close');
let isModal = true;
iconModalCloseBtn.addEventListener('click', (e) => {
e.stopPropagation();
isModal = false;
parent.removeChild(iconModal);
});
window.addEventListener('click', () => {
if (isModal) {
parent.removeChild(iconModal);
isModal = false;
}
});
const listIcons = document.querySelectorAll('.list__icon');
for (const icon of listIcons) {
icon.addEventListener('click', () => {
activeList.children[0].children[0].setAttributeNS('http://www.w3.org/1999/xlink', 'href', `img/icons/sprite.svg#${icon.id}`);
});
}
};
const renameList = (currentList) => {
// place cursor in list name (focus input)
currentList.readOnly = false;
setCaretPosition(currentList, currentList.value.length);
// rename it on either enter key or blur
const tmpName = currentList.value;
currentList.addEventListener('blur', () => {
if (!document.querySelector(`#${tmpName}`)) return; // prevent executing both events
currentList.readOnly = true;
document.querySelector(`#${tmpName}`).id = currentList.value;
});
currentList.addEventListener('keyup', () => {
if (event.keyCode === 13) {
if (!document.querySelector(`#${tmpName}`)) return;
currentList.readOnly = true;
document.querySelector(`#${tmpName}`).id = currentList.value;
}
});
};
// #######################################
// ADD NEW LIST
const addListBtn = document.querySelector('.add-list');
const main = document.querySelector('.main');
let newListsNumber = 1;
addListBtn.addEventListener('click', () => {
// create new list
const newList = document.createElement('div');
newList.className = 'list';
newList.innerHTML = `
<svg class="list__icon">
<use xlink:href="img/icons/sprite.svg#icon-clipboard"></use>
</svg>
<input class="list__title" value="New-${newListsNumber}" readonly />
<div class="list__options">
<div class="option"></div>
<div class="option"></div>
</div>`;
listsContainer.appendChild(newList);
// create new item for current list
const newTodo = document.createElement('div');
newTodo.className = 'todo';
newTodo.id = newList.children[1].value;
main.appendChild(newTodo);
setUpListsListeners();
renameList(newList.children[1]);
newListsNumber++;
});
// #######################################
// ITEMS - DISPLAY TRASH AND RENAME ICON ON HOVER
let currentItem;
const setUpItems = () => {
const items = document.querySelectorAll('.item');
for (const item of items) {
item.addEventListener('mouseover', () => {
item.children[1].classList.remove('hide');
currentItem = item;
});
item.addEventListener('mouseout', () => {
item.children[1].classList.add('hide');
});
}
// RENAME BUTTONS
const renameItemButtons = document.querySelectorAll('.item-rename');
for (const renameBtn of renameItemButtons) {
renameBtn.addEventListener('click', () => {
const itemName = currentItem.children[0].children[1];
if (itemName.classList.contains('item__title--done')) return;
renameItem(itemName);
});
}
// DELETE BUTTONS
const deleteItemButtons = document.querySelectorAll('.item-delete');
for (const deleteBtn of deleteItemButtons) {
deleteBtn.addEventListener('click', () => {
currentItem.remove();
});
}
};
// #######################################
// MARK AS DONE
// for default items
const checkBoxes = document.querySelectorAll('.item__check');
for (const checkBox of checkBoxes) {
checkBox.addEventListener('click', () => {
checkBox.classList.toggle('item__check--done');
currentItem.children[0].children[1].classList.toggle('item__title--done');
});
}
// for new items
const markAsDoneAddListener = () => {
currentItem.children[0].children[0].classList.toggle('item__check--done');
currentItem.children[0].children[1].classList.toggle('item__title--done');
};
setUpItems();
// #######################################
// ADD ITEM
const addItemBtn = document.querySelector('.add-item');
addItemBtn.addEventListener('click', () => {
const itemParent = document.querySelector(`#${activeList.children[1].value}`);
const newItem = document.createElement('div');
newItem.className = 'item';
newItem.innerHTML = `
<div class="item__wrapper">
<div class="item__check" onClick="markAsDoneAddListener()">
<img src="img/checkmark.svg" alt="checkmark" />
</div>
<input class="item__title" value="New item" readonly />
</div>
<div class="item__options hide">
<img src="img/pen.svg" alt="pen" class="item-rename"/>
<img src="img/trash.svg" alt="trash" class="item-delete" />
</div>`;
itemParent.appendChild(newItem);
setUpItems();
renameItem(newItem.children[0].children[1]);
});
// #######################################
// RENAME ITEM
const renameItem = (itemName) => {
// place cursor in list name (focus input)
itemName.readOnly = false;
setCaretPosition(itemName, itemName.value.length);
// rename it on either enter key or blur
const tmpName = itemName.value;
itemName.addEventListener('blur', () => {
if (!document.querySelector(`#${tmpName}`)) return; // prevent executing both events
itemName.readOnly = true;
document.querySelector(`#${tmpName}`).id = itemName.value;
});
itemName.addEventListener('keyup', () => {
if (event.keyCode === 13) {
if (!document.querySelector(`#${tmpName}`)) return;
itemName.readOnly = true;
document.querySelector(`#${tmpName}`).id = itemName.value;
}
});
};
// #######################################
// SET CURSOR INSIDE INPUT
function setCaretPosition(ctrl, pos) {
// Modern browsers
if (ctrl.setSelectionRange) {
ctrl.focus();
ctrl.setSelectionRange(pos, pos);
// IE8 and below
} else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T22:06:36.777",
"Id": "502473",
"Score": "0",
"body": "Hello. I made a pretty long answer that might be helpful for You. Take a look :)"
}
] |
[
{
"body": "<p>HTML:</p>\n<ul>\n<li>Your <code>input</code> elements do not have associated labels</li>\n<li>Use semantic html elements. Why do You use <code>img</code> instead of a regular html <code>button</code> ?</li>\n</ul>\n<p>CSS:</p>\n<ul>\n<li>Avoid styling by tags. Use classes instead</li>\n<li>Avoid using <code>!important</code>. Read about CSS specificity</li>\n<li>I'd personally create a separate CSS file with the colors</li>\n<li>I'm pretty sure You do not need all of those prefixes</li>\n</ul>\n<p>JS:</p>\n<ul>\n<li>Some of Your <code>let</code>'s might be changed to <code>const</code>'s</li>\n<li><code>// Add eventListener to lists</code>. Code below this comment could be improved. You are adding an event listener to all of the list items. Read about event delegation. It will allow You to add the listener to one item only when it's clicked :)</li>\n<li>I would try to handle adding the list items in a different way. Maybe using <code>insterAdjacentHTML</code> and <code>template strings</code>. Read about that</li>\n<li><code>if (e.target.classList.contains('list__options')) openModal(e.target);</code> Use curly braces in <code>if/else</code> statements</li>\n<li><code>renameBtn.addEventListener('click', () => { renameList(currentList); });</code> This could be an one liner</li>\n<li><code>if (!activeList) return; // return when there is no more lists</code> This code is self explanatory. There is no need to add such a comment</li>\n<li>There is no need to add <code>()</code> around one argument in arrow syntax</li>\n<li>Sometimes You use regular function and sometimes arrow function.</li>\n<li>Avoid using <code>var</code>. We have better alternatives nowadays</li>\n<li>Adding and removing the list items could be improved using ES6 methods. I'd add new items onClick by pushing data to some kind of an items array. Based on that array I'd use <code>.map</code> method to loop over that array and render proper items on the page. Removing could be handled using <code>event delegation</code> and <code>.filter</code> method</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T12:05:31.730",
"Id": "502513",
"Score": "0",
"body": "thanks for the feedback and your time"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T22:02:41.553",
"Id": "254766",
"ParentId": "254702",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254766",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T13:53:23.943",
"Id": "254702",
"Score": "1",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Vanilla JS Complex TO DO List application"
}
|
254702
|
<p>Thanks to ASP.NET Core dependency injection, there's no need to follow the Singleton pattern; any class will do.</p>
<p>What I want to do is to have a class that will store a value that'll be used by another methods inside the app. A specific class is in charge of updating this value. What I'm concerned is the problem of a thread reading the value while the specific class updates it, given that I haven't done enough concurrency to feel confident.</p>
<p>So I came up with this. Is it correct for what I want it to do?</p>
<pre class="lang-csharp prettyprint-override"><code>public class DynamicValueStore
{
private readonly object _lock_obj;
private string _value;
public string Value
{
get
{
lock (_lock_obj)
{
return _value;
}
}
}
public DynamicValueStore()
{
_lock_obj = new object();
_value = string.Empty;
}
public void UpdateValue(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentNullException(nameof(value));
}
lock (_lock_obj)
{
_value = value;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T06:26:44.770",
"Id": "502392",
"Score": "0",
"body": "Reference type assignments are atomic in C#. So locks are unnecessary.\nhttps://stackoverflow.com/questions/5209623/is-a-reference-assignment-threadsafe"
}
] |
[
{
"body": "<p>That will lock it down for sure. If you know you will have more reads then writes, which is common, you should look at the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?redirectedfrom=MSDN&view=net-5.0\" rel=\"nofollow noreferrer\">ReaderWriterLockSlim</a> class. What you have will only allow one read and one write and they all queue up in line waiting their turn. The ReaderWriterLockSlim class will still only allow one write at a time but allow multiple reads at a time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T16:34:18.017",
"Id": "502353",
"Score": "0",
"body": "So the idea is to replace the `lock` with a `ReaderWriterLockSlim` object and use that to lock my reads and writes? Because yes, I'll have a lot more reads than writes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T16:43:45.713",
"Id": "502354",
"Score": "0",
"body": "Yes readerlockslim would replace the lock. If you look at document you can see how to use it. There are lots of examples of its use online"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T16:25:21.743",
"Id": "254706",
"ParentId": "254705",
"Score": "4"
}
},
{
"body": "<p>I followed CharlesNRice's suggestion and here's a version of the code that behaves better when there are more reads than writes:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>public class DynamicValueStore : IDisposable\n{\n private readonly ReaderWriterLockSlim _lock_obj;\n \n private string _value;\n private bool _already_disposed;\n\n public string Authvalue\n {\n get \n {\n _lock_obj.EnterReadLock();\n try\n {\n return _value;\n }\n finally\n {\n _lock_obj.ExitReadLock();\n }\n }\n }\n\n public DynamicValueStore()\n {\n _lock_obj = new ReaderWriterLockSlim();\n _value = string.Empty;\n }\n\n public void UpdateValue(string value)\n {\n if (string.IsNullOrWhiteSpace(value))\n {\n throw new ArgumentNullException(nameof(value));\n }\n _lock_obj.EnterWriteLock();\n try\n {\n _value = value;\n }\n finally\n {\n _lock_obj.ExitWriteLock();\n }\n }\n\n protected virtual void Dispose(bool disposeManagedObjects)\n {\n if (!_already_disposed)\n {\n if (disposeManagedObjects)\n {\n _lock_obj.Dispose();\n }\n _already_disposed = true;\n }\n }\n\n public void Dispose()\n {\n Dispose(disposeManagedObjects: true);\n GC.SuppressFinalize(this);\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T16:52:44.220",
"Id": "254708",
"ParentId": "254705",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254706",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T16:11:21.930",
"Id": "254705",
"Score": "2",
"Tags": [
"c#",
"thread-safety",
"singleton",
"asp.net-core"
],
"Title": "ASP.NET Core singleton with a thread-safe property that can be changed"
}
|
254705
|
<p>I made a simple Hangman game in Python:</p>
<pre><code>import random
class Hangman:
def __init__(self):
self.words = ["bike", "monkey", "planet"]
self.random_word = random.choice(self.words)
self.lenght = len(self.random_word)
self.no_of_try = int(self.lenght) + 3
self.empty_word = ["_"] * self.lenght
@staticmethod
def user_input():
print("Enter a guess: ")
user_input = input()
return user_input
def find_index(self):
letter = self.user_input()
possition = self.random_word.index(letter)
return (letter, possition)
def substitue(self):
try:
guess_letter, guess_index = self.find_index()
self.empty_word[guess_index] = guess_letter
print(self.empty_word)
return True
except ValueError as e:
return False
def play_game(self):
while self.no_of_try > 0:
print("no: " + str(self.no_of_try))
game = self.substitue()
if game:
print("Bravo")
self.no_of_try -= 1
else:
self.no_of_try -= 1
print("Wrong")
if "_" not in self.empty_word:
print("You win")
break
if self.no_of_try == 0:
print("Game over")
break
if __name__ == "__main__":
h = Hangman()
h.play_game()
</code></pre>
|
[] |
[
{
"body": "<p>Right now the program will have a problem if you use a word which has the same letter more than once. string.index will only return the index of the first occurrence. What you could do instead is use a set to check what letters still need to be guessed. If a character in the word is still in the set, it hasn’t been guessed and an underscore should be printed. If it isn’t in the set, it has been guessed and it should be printed.</p>\n<p>The code can be simplified significantly. You only really need one function which takes a list of strings as an argument. You could do something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\ndef hangman(word_list):\n word = random.choice(word_list)\n letters = set(word)\n guesses = len(word) + 3\n while len(letters) > 0 and guesses > 0:\n guess = input(str(guesses) + " guesses left\\nguess something:\\n")\n if guess in letters:\n print("correct")\n letters.remove(guess)\n else:\n print("wrong")\n guesses -= 1\n print(*(ch if ch not in letters else '_' for ch in word))\n print("win" if len(letters) == 0 else "lose")\n\nif __name__ == "__main__":\n hangman(["bike", "monkey", "planet", "mississippi"])\n</code></pre>\n<h1><strong>NITPICKING</strong></h1>\n<p>You have a function in your current code which could be replaced with a call to input. the user_input function could be replaced with this: <code>input("Enter a guess:\\n")</code>. Also you can simplify this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if game:\n print("Bravo")\n self.no_of_try -= 1\nelse:\n self.no_of_try -= 1\n print("Wrong")\n</code></pre>\n<p>into this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>self.no_of_try -= 1\nprint("Bravo" if game else "Wrong")\n</code></pre>\n<p>I also noticed a couple things in the __init__ method. The word list and the randomly chosen word’s length don’t need to be instance variables because they’re only used in __init__, and you don’t need to cast the length to int because it’s already an int.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T09:33:56.490",
"Id": "502410",
"Score": "1",
"body": "Thank you. This was really helpful, I will consider this practices in the future projects :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T23:30:26.313",
"Id": "254724",
"ParentId": "254717",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254724",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T21:26:32.470",
"Id": "254717",
"Score": "3",
"Tags": [
"python-3.x",
"object-oriented",
"hangman"
],
"Title": "Simple Hangman game in Python3"
}
|
254717
|
<p>I am using expo and wanted to use the hook 'useFonts' from expo-fonts to retrieve fonts.
While the assets are being retrieved a splashscreen is displaying.</p>
<p>This is my solution.</p>
<pre><code>// Import the hook.
import { useFonts } from 'expo-font';
export default function App() {
const [appReady, setReady] = useState(false);
const [loaded] = useFonts({
Roboto: require('native-base/Fonts/Roboto.ttf'),
Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'),
})
useEffect(() => {
if (loaded) {
setReady(true);
}
}, [loaded])
//if assets are not loaded, load them first, then display app.
if (!appReady) {
return (
// Show splashscreen while waiting.
);
}
</code></pre>
<p>I'm new to react hooks and just wanted to know if this approach is acceptable.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T22:12:43.360",
"Id": "254720",
"Score": "1",
"Tags": [
"javascript",
"react.js",
"react-native"
],
"Title": "React-Native: Using expo-font hook to retrieve assets"
}
|
254720
|
<p>I'm new to python and curious if this is the most efficient way to read addresses from a SAP database, geocode them, read the results, and then write the information back to the database.</p>
<p>Everything below works, I'm just curious if this would make an expert cry beginner bad, or acceptable code for my first try. :-) I'm pretty sure my variable name formatting isn't 100% up to spec.</p>
<p>For reference on Geocodio, <a href="https://www.geocod.io/docs/?python#fields" rel="nofollow noreferrer">https://www.geocod.io/docs/?python#fields</a></p>
<pre><code>import platform
import json
import sys
from hdbcli import dbapi
from geocodio import GeocodioClient
client = GeocodioClient('x')
conn = dbapi.connect(address='x', port=x, user='x', password='x')
cursor = conn.cursor()
sql_command = "SELECT ADDRNUMBER, CITY1, REGION, POST_CODE1,STREET FROM CV_COORDS_TO_PROCESS"
cursor.execute(sql_command)
rows = cursor.fetchall()
address = ''
for row in rows:
#build the address string and save the address id
address = row[4] +", " + row[1] +", " + row[2] +" " + row[3]
addr_id = row[0]
#send the address to geocodio
location = client.geocode(address)
#Read the results and break after the first result, as per the geocodio documentation,
#in the event of multiple points, it lists them in order of confidence
for subs in location['results']:
lat = subs['location']['lat']
long = subs['location']['lng']
accuracy = subs['accuracy']
accuracy_type = subs['accuracy_type']
break
##update / insert into database
merge_query = "upsert zsa_addr_coords values ('100', %s, %f, %f, %f, '%s')"\
%(addr_id, lat, long, accuracy, accuracy_type ) + " where addr_id = '%s'" %addr_id
try:
cursor.execute(merge_query);
except:
print (ex)
address = ''
cursor.close()
conn.close()
</code></pre>
<p>This is example of the results Geocodio returns:</p>
<pre><code>{
"input": {
"address_components": {
"number": "1109",
"predirectional": "N",
"street": "Highland",
"suffix": "St",
"formatted_street": "N Highland St",
"city": "Arlington",
"state": "VA",
"zip": "22201",
"country": "US"
},
"formatted_address": "1109 N Highland St, Arlington, VA 22201"
},
"results": [
{
"address_components": {
"number": "1109",
"predirectional": "N",
"street": "Highland",
"suffix": "St",
"formatted_street": "N Highland St",
"city": "Arlington",
"county": "Arlington County",
"state": "VA",
"zip": "22201",
"country": "US"
},
"formatted_address": "1109 N Highland St, Arlington, VA 22201",
"location": {
"lat": 38.886665,
"lng": -77.094733
},
"accuracy": 1,
"accuracy_type": "rooftop",
"source": "Virginia GIS Clearinghouse"
}
]
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T03:56:18.093",
"Id": "502385",
"Score": "0",
"body": "This code is not complete. Please show all of it, including how you establish your connection and your `import` statements."
}
] |
[
{
"body": "<p>In Python, you don't need to create your variables before using them, so the <code>address = ''</code> before your loop is unnecessary. You also don't need to reset a variable before using it again, so the <code>address = ''</code> at the end of each loop iteration is particularly unnecessary.</p>\n<p>You currently get the addresses from the DB and then concatenate parts of that address as the query string for your geolocation. This would be easier if you got the address in the same order you need it later:</p>\n<pre><code>sql_command = "SELECT ADDRNUMBER, STREET, CITY1, REGION, POST_CODE1 FROM CV_COORDS_TO_PROCESS"\ncursor.execute(sql_command)\nrows = cursor.fetchall()\n\nfor row in rows:\n #build the address string and save the address id\n addr_id, address = row[0], ", ".join(row[1:])\n ...\n</code></pre>\n<p>There's probably a way to do the concatenation already in SQL, but I am not versed enough in that language to suggest how.</p>\n<p>If you want to get the first value from an iterable, you can use <code>next</code>:</p>\n<pre><code>location = next(iter(client.geocode(address)['results']))\n</code></pre>\n<p>Most DB wrappers support prepared statements, which would mean that you don't have to prepare the full query string, but rather use something like this:</p>\n<pre><code>merge_query = "upsert zsa_addr_coords values ('100', ?, ?, ?, ?, ?) where addr_id = ?"\ntry:\n cursor.execute(merge_query, (addr_id, lat, long, accuracy, accuracy_type, addr_id));\nexcept:\n print (ex)\n</code></pre>\n<p>Indeed, <code>hdbcli</code> also support this: <a href=\"https://blogs.sap.com/2017/07/26/sap-hana-2.0-sps02-new-feature-updated-python-driver/\" rel=\"nofollow noreferrer\">https://blogs.sap.com/2017/07/26/sap-hana-2.0-sps02-new-feature-updated-python-driver/</a></p>\n<p>It should even take care of quoting for you and prevents the most basic SQL\ninjection attacks.</p>\n<p>And since that string now never changes, you can pull it outside of the loop.</p>\n<p>You can probably speed up the execution time by disabling the auto-commit mode before your loop and manually committing at the end, which ensures that you don't have to do that every loop iteration:</p>\n<pre><code>conn.setautocommit(False)\nfor row in rows:\n ...\nconn.commit()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T16:47:33.407",
"Id": "254756",
"ParentId": "254721",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T22:14:26.030",
"Id": "254721",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"json"
],
"Title": "Geocoding addresses from a SAP database"
}
|
254721
|
<p>The task is relatively simple and until now it was always performed by some poor admin soul. There is a large table that needs to be filtered based on a simple criteria and each view has to be saved as a new spreadsheet.</p>
<p>The code is as simple as the task (and as my coding skills) so I would love to get some feedback about any tricks I might have missed to make it more robust or "best practices" advice.</p>
<pre><code>Option Explicit
Sub SplitWorksheet()
Dim d As Long
Dim dctList As Object
Dim varList As Variant
Dim varName As Variant
Dim wkb As Workbook
Dim wks As Worksheet
Dim rng As Range
Dim wkbNew As Workbook
Dim strPath As String
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set wkb = ThisWorkbook
Set wks = wkb.Sheets("Data")
Set rng = wks.Range("A1").CurrentRegion
strPath = Application.ThisWorkbook.Path & "\Distribution\"
Set dctList = CreateObject("Scripting.Dictionary")
dctList.CompareMode = vbTextCompare
With wks
varList = .Range(.Cells(6, "H"), .Cells(Rows.Count, "H").End(xlUp)).Value2
For d = LBound(varList) To UBound(varList)
dctList.Item(varList(d, 1)) = vbNullString
Next
For Each varName In dctList
.Range("a1").CurrentRegion.AutoFilter Field:=8, Criteria1:="=" & varName, Operator:=xlFilterValues
Set wkbNew = Workbooks.Add
.Range("A1").CurrentRegion.SpecialCells(xlCellTypeVisible).Copy _
Destination:=wkbNew.Sheets(1).Range("A1")
wkbNew.SaveAs strPath & varName & ".xlsx"
wkbNew.Close
Next
.Range("a1").CurrentRegion.AutoFilter
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "All done, individual spreadsheets have been saved", vbOKOnly, "Great success!"
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>I think Power Query (aka Get & Transform) could do this much more straightforwardly. Two queries one filtering for one thing another for the other they could live in the same or two different workbooks - refresh and save as, done. You could VBA the bit that saves them into separate books and names them in various ways I guess.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T06:08:57.557",
"Id": "510400",
"Score": "0",
"body": "Welcome to CodeReview. Could you please provide code as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-30T10:05:13.963",
"Id": "510403",
"Score": "0",
"body": "Showing possible replacement code, whilst helpful, isn't a requirement for a good review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-31T10:12:46.080",
"Id": "510491",
"Score": "0",
"body": "The Power Query \"get data from a folder\" type query can be \"written\" more or less in the gui - perhaps refined in a text editor, The save as part, if he can write the above then he can definitely do whatever he needs to to save the books. If it were me I'd likely have separate workbooks with the queries as templates and macro to refresh and then \"saves as\" to create new versions. The complexity and sophistication of that macro really depends on the detail of his the requirement."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-29T18:48:19.743",
"Id": "258849",
"ParentId": "254722",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-14T22:19:41.147",
"Id": "254722",
"Score": "1",
"Tags": [
"vba"
],
"Title": "VBA - create separate spreadsheets from a filtered table"
}
|
254722
|
<p>I have a simple utility to reallocate arrays of various kind and dimensions, an excerpt of which is reported below. I wonder however if one can avoid deallocate an array that just needs to be expanded, instead of deallocating it first. Also, I am interested in knowing what is a good strategy to avoid duplicating the code (e.g., due to different kind and dimensions of the array to be reallocated). Is it possible to return a reshaped array without allocating/deallocating it?</p>
<pre class="lang-fortran prettyprint-override"><code>module ModuleSystemUtils
implicit none
private
interface realloc
module procedure realloc_integer_vec
module procedure realloc_dble_vec
end interface realloc
public realloc
contains
subroutine realloc_integer_vec(vec,n)
integer, allocatable, intent(inout) :: vec(:)
integer , intent(in) :: n
if(allocated(vec))then
if(size(vec,1)/=n)then
deallocate(vec)
allocate(vec(n))
endif
else
allocate(vec(n))
endif
vec=0
end subroutine realloc_integer_vec
subroutine realloc_dble_vec(vec,n)
real(kind(1d0)), allocatable, intent(inout) :: vec(:)
integer , intent(in) :: n
if(allocated(vec))then
if(size(vec,1)/=n)then
deallocate(vec)
allocate(vec(n))
endif
else
allocate(vec(n))
endif
vec=0.d0
end subroutine realloc_dble_vec
end module ModuleSystemUtils
</code></pre>
<p>post scriptum:
For folks not familiar with the simple syntax of modern Fortran, I suggest the following <a href="https://fortran-lang.org/learn/quickstart" rel="nofollow noreferrer">quick modern Fortran tutorial</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T01:02:19.140",
"Id": "254725",
"Score": "0",
"Tags": [
"fortran"
],
"Title": "Is it possible to do a realloc that does not deallocate an array first?"
}
|
254725
|
<p>I have a problem with macro running too slow and I guess it is just because of lack of my knowledge.</p>
<p>I have a macro that is copying data from "database" and paste it to another sheet. Macro is taking the names from the list in Sheet1 and looks for matches in Sheet2. When the match is found is copying a specific cell.</p>
<p>Right now I have a macro for each person on the list so I have 5 the same macros doing the same thing so maybe that why it takes so much time.... (around 3min)</p>
<p>Is there any way to make it faster? below my code so far</p>
<pre><code>Sub CopySalesMan1()
Dim lastrow As Long, erow As Long
lastrow = Worksheets("Sheet2").Cells(Rows.Count, 2).End(xlUp).Row
For i = 2 To lastrow
If Worksheets("Sheet2").Cells(i, 25).Value = Worksheets("Sheet1").Cells(6, 12).Value Then
Worksheets("Sheet2").Cells(i, 2).Copy
erow = Worksheets("Sheet1").Cells(Rows.Count, 4).End(xlUp).Row
Worksheets("Sheet1").Cells(erow + 1, 3).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Worksheets("Sheet2").Cells(i, 25).Copy
Worksheets("Sheet1").Cells(erow + 1, 4).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Worksheets("Sheet2").Cells(i, 3).Copy
Worksheets("Sheet1").Cells(erow + 1, 5).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Worksheets("Sheet2").Cells(i, 4).Copy
Worksheets("Sheet1").Cells(erow + 1, 6).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Worksheets("Sheet2").Cells(i, 5).Copy
Worksheets("Sheet1").Cells(erow + 1, 7).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Worksheets("Sheet2").Cells(i, 6).Copy
Worksheets("Sheet1").Cells(erow + 1, 8).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Worksheets("Sheet2").Cells(i, 21).Copy
Worksheets("Sheet1").Cells(erow + 1, 9).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End If
Next i
End Sub
</code></pre>
<p>And the macro calling for every salesman in the list</p>
<pre><code>Sub All()
If Worksheets("Sheet1").Range("L7").Value <> "" Then Call CopySalesMan2
If Worksheets("Sheet1").Range("L8").Value <> "" Then Call CopySalesMan3
If Worksheets("Sheet1").Range("L9").Value <> "" Then Call CopySalesMan4
If Worksheets("Sheet1").Range("L10").Value <> "" Then Call CopySalesMan5
End Sub
</code></pre>
<p>Sheet1
<a href="https://i.stack.imgur.com/t0HZg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t0HZg.png" alt="Sheet1" /></a></p>
<p>Sheet2
<a href="https://i.stack.imgur.com/kGCpL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kGCpL.png" alt="Sheet2" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T07:55:19.010",
"Id": "502400",
"Score": "2",
"body": "Welcome to Code Review! This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question, including a title that describes the code's _purpose_ rather than your concerns about it. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226). Also see [ask] for examples of good Code Review question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T23:16:21.533",
"Id": "502681",
"Score": "0",
"body": "Hi! thanks for advice! I will keep that in mind when posting next question!"
}
] |
[
{
"body": "<p>Found the solution:</p>\n<pre><code>Sub CopySalesMan()\nApplication.ScreenUpdating = False\nDim XlWkSht As Worksheet, sVal As String, lRow As Long, i As Long, r As Long\nSet XlWkSht = Worksheets("Sheet1")\nlRow = XlWkSht.Range("D" & XlWkSht.Rows.Count).End(xlUp).Row\nFor i = 6 To 10\n If XlWkSht.Range("L" & i).Value <> "" Then\n sVal = XlWkSht.Range("L" & i).Value\n With Worksheets("Sheet2")\n For r = 2 To .Range("B" & .Rows.Count).End(xlUp).Row\n If .Range("Y" & r).Value2 = sVal Then\n lRow = lRow + 1\n XlWkSht.Range("B" & lRow).Value = .Range("B" & r).Value\n XlWkSht.Range("C" & lRow).Value = .Range("Y" & r).Value\n XlWkSht.Range("D" & lRow).Value = .Range("C" & r).Value\n XlWkSht.Range("E" & lRow).Value = .Range("D" & r).Value\n XlWkSht.Range("F" & lRow).Value = .Range("E" & r).Value\n XlWkSht.Range("G" & lRow).Value = .Range("F" & r).Value\n XlWkSht.Range("H" & lRow).Value = .Range("U" & r).Value\n End If\n Next r\n End With\n End If\nNext\nApplication.ScreenUpdating = True\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T23:15:29.913",
"Id": "254867",
"ParentId": "254729",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "254867",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T04:50:08.763",
"Id": "254729",
"Score": "-1",
"Tags": [
"vba",
"excel"
],
"Title": "Is it possible to make this macro faster? Copy and paste when condition is met"
}
|
254729
|
<p>This code searches for the word "Disbursements" and copies all of the rows with data below it, including the row with the specified word. After the rows are copied to a new sheet, the unnecessary rows below the contiguous range of data are deleted. In order to search for the last cell, I used a function that finds the last cell with data.</p>
<p>Instead of deleting the rows below the contiguous range, should I just copy the contiguous rows to begin with? Is there a better way to delete the rows below the first blank row?</p>
<pre><code>Sub Reformat_ZZ_CM_BNREG()
Application.ScreenUpdating = False
Application.Calculation = xlManual
Application.DisplayAlerts = False
'declare variables to search for within bank register
Dim searchText As String
Dim ws As Worksheet
Dim searchCell As Range
Dim newWS As Worksheet
Dim lastCell As String
Dim firstCell As String
Dim lastRow As Long
'set variables to sheet name, search text, and searchCell
searchText = "Disbursements"
Set ws = Sheets("ZZ_CM_BNREG")
lastCell = FindLast(3, "ZZ_CM_BNREG")
'Set lastCell = Range(Cells.Find("*", , xlFormulas, , xlRows, xlPrevious, , , False), Cells.Find("*", , xlFormulas, , xlColumns, xlPrevious, , , False))
Set newWS = Sheets.Add(After:=Sheets("ZZ_CM_BNREG"))
newWS.Name = "Bank Register"
'Unmerge all cells in Column A & get cell address of searchCell
With ws
ws.Activate
Range("A:A").UnMerge
Set searchCell = .Cells.Find(What:="Disbursements", _
SearchFormat:=True)
If searchCell Is Nothing Then
MsgBox ("Error")
Else
firstCell = searchCell.Address
End If
End With
'copy range using above function to get last cell in range
'paste range onto the new sheet
'we are starting with the cell containing disbursements
ws.Range(firstCell, lastCell).Copy _
Destination:=newWS.Range("A1")
DeleteRowsAndSheet
End Sub
Sub DeleteRowsAndSheet()
Dim LR As Long
LR = Sheets("Bank Register").Range("A1").End(xlDown).Row
Sheets("Bank Register").Activate
Rows(LR + 1 & ":" & LR + 20).Delete
Sheets("Bank Register").Range("1:1").Delete
Sheets("ZZ_CM_BNREG").Delete
Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
Application.DisplayAlerts = True
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T15:21:03.620",
"Id": "502436",
"Score": "0",
"body": "If you create a Class (BankRegister) that has a field for an identifier (ID - use the Register number or other unique qualifier) and a Collection (Disbursements) then as you loop the sheet and find a Disbursement item add that to the collection. Once you've got it all, you then loop the collection and add each to your new sheet. I suggest you avoid Copy/Pasta. If you have an object to work with the world is your oyster so to speak."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T23:51:32.800",
"Id": "503631",
"Score": "0",
"body": "I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T23:58:38.830",
"Id": "503632",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Thank you for the clarification. I wasn't sure if it would be appropriate to post it as an answer so that's why I added it to the question."
}
] |
[
{
"body": "<p>I will address your code in sections and at the end I will provide a full updated code based on the touched subjects.</p>\n<p><strong>Application state</strong></p>\n<p>You are turning the Application 'off' with:</p>\n<blockquote>\n<pre><code>Application.ScreenUpdating = False\nApplication.Calculation = xlManual\nApplication.DisplayAlerts = False\n</code></pre>\n</blockquote>\n<p>at the beginning of your method and then you turn it back 'on' with:</p>\n<blockquote>\n<pre><code>Application.ScreenUpdating = True\nApplication.Calculation = xlAutomatic\nApplication.DisplayAlerts = True\n</code></pre>\n</blockquote>\n<p>at the end of another method.</p>\n<p>It's a good idea to turn things back on within the scope of the same method. In your case you would add the latter 3 lines at the end of the <code>Reformat_ZZ_CM_BNREG</code> method immediately after calling the <code>DeleteRowsAndSheet</code> method. You should not rely on another method to 'clean-up' for you. What if you decide that you don't need to call that method in the future? There is a high chance you will forget to move the 'clean-up' code back in the main method.</p>\n<p>How about turning things 'off' and then back 'on'. It's not a good idea to do this, even if it works for you in this situation, because in time you can get used to this kind of approach and repeat it without giving too much thought. Imagine you have another method called <code>Main</code> that turns the application 'off' and then calls your <code>Reformat_ZZ_CM_BNREG</code> method and then does other stuff like calling a method called <code>MyMethod</code> and then finally turns the application back 'on'. Something like:</p>\n<pre><code>Sub Main()\n Application.ScreenUpdating = False\n Application.Calculation = xlManual\n Application.DisplayAlerts = False\n \n Reformat_ZZ_CM_BNREG\n MyMethod\n \n Application.ScreenUpdating = True\n Application.Calculation = xlAutomatic\n Application.DisplayAlerts = True\nEnd Sub\n</code></pre>\n<p>What if <code>MyMethod</code> expects the calculation to be 'off'? Well, <code>Reformat_ZZ_CM_BNREG</code> actually turns things back 'on' and you can clearly see this is not what <code>MyMethod</code> (or even <code>Main</code> expects).</p>\n<p>What if the Calculation needs to be Manual all the time because this is what the user of the Workbook wants?</p>\n<p>The best approach, which you should always use, is to make no assumption of what the current state is because you have no control of what other higher-level methods might expect/do with the state. Your method should look like this:</p>\n<pre><code>Sub Reformat_ZZ_CM_BNREG()\n Dim appScrUpdate As Boolean\n Dim appCalc As XlCalculation\n Dim appDispAlert As Boolean\n\n 'Store current Application state\n appScrUpdate = Application.ScreenUpdating\n appCalc = Application.Calculation\n appDispAlert = Application.DisplayAlerts\n \n 'Turn state off\n Application.ScreenUpdating = False\n Application.Calculation = xlManual\n Application.DisplayAlerts = False\n \n 'Actual code\n '...\n '...\n '...\n \n\nRestoreState:\n Application.ScreenUpdating = appScrUpdate\n Application.Calculation = appCalc\n Application.DisplayAlerts = appDispAlert\nEnd Sub\n</code></pre>\n<p><em><sup><code>RestoreState:</code> line label can be used in case you want to early exit the method using something like <code>GoTo RestoreState</code> which would still do the 'clean-up'</sup></em></p>\n<p>In short, you restore the state as it was, making no assumptions, to make sure you do not impact logic somewhere else.</p>\n<p>There is a lot of boilerplate code to do this so I use a class instead so that I can have multiple instances with stored state at any given time. <a href=\"https://github.com/cristianbuse/VBA-FastExcelUDFs/blob/master/Code%20Modules/ExcelAppState.cls\" rel=\"nofollow noreferrer\">Here</a> is what I usually use, and the code above would get simplified to something like:</p>\n<pre><code>Sub Reformat_ZZ_CM_BNREG()\n Dim app As New ExcelAppState\n app.StoreState\n app.Sleep\n \n 'Actual code\n '...\n '...\n '...\n \n app.RestoreState\nEnd Sub\n</code></pre>\n<p><strong>Indentation</strong></p>\n<p>For me, it is much easier to read this:</p>\n<pre><code>Function DoSomething() As Integer\n Dim iNumber As Integer\n For iNumber = 1 To 5\n DoSomething = DoSomething + iNumber\n Next iNumber\nEnd Sub\n</code></pre>\n<p>compared to this:</p>\n<pre><code>Function DoSomething() As Integer\nDim iNumber As Integer\nFor iNumber = 1 To 5\n DoSomething = DoSomething + iNumber\nNext iNumber\nEnd Sub\n</code></pre>\n<p>especially when I have a large number of methods. Although your code is working, please consider this aesthetic aspect when writing code. All code that is within the scope of the method should have an extra indentation level than the method definition.</p>\n<p><strong><a href=\"https://en.wikipedia.org/wiki/Hard_coding\" rel=\"nofollow noreferrer\">Hardcoding</a></strong></p>\n<p>You are using the same string literals in multiple places: "Disbursements", "ZZ_CM_BNREG", "Bank Register". Consider declaring them as constants so that you only need to change them (if needed) in a single place:</p>\n<pre><code>Const searchText As String = "Disbursements"\nConst sourceShtName As String = "ZZ_CM_BNREG"\nConst targetShtName As String = "Bank Register"\n</code></pre>\n<p>If you ever decide to receive these as method parameters then all you need to do is to move the constants (without the <code>Const</code> keyword) into the method definition without needing other changes e.g. <code>Sub Reformat_ZZ_CM_BNREG(ByVal searchText As String, ByVal sourceShtName As String, ByVal targetShtName)</code>. Might not be useful here, but you get the idea.</p>\n<p><strong>Worksheet assumptions</strong></p>\n<p>You are making the following assumptions:</p>\n<ol>\n<li>a worksheet named "ZZ_CM_BNREG" exists</li>\n<li>a worksheet named "Bank Register" does not exist</li>\n<li>sheet named "ZZ_CM_BNREG" is a Worksheet (it could be a chart sheet)</li>\n<li>the workbook is unprotected</li>\n</ol>\n<p>Obviously, it works for you but it's better to be a bit precautious to avoid unexpected errors and behaviour. Consider this: if any of the assumptions would fail then a runtime error would be raised, and you would not get the chance to restore the application state (or do other clean-up operations that might be required).</p>\n<p>Consider an auxiliary function to retrieve the worksheet:</p>\n<pre><code>Public Function GetWorksheetByName(ByVal wsName As String, ByVal book As Workbook) As Worksheet\n On Error Resume Next\n Set GetWorksheetByName = book.Worksheets(wsName)\n On Error GoTo 0\nEnd Function\n</code></pre>\n<p>you could simply use it like this:</p>\n<pre><code>Set ws = GetWorksheetByName(sourceShtName, ThisWorkbook)\nIf ws Is Nothing Then\n 'Do something e.g. show a message box if needed, restore state or exit method\n '...\nEnd If\n</code></pre>\n<p><em><sup>Notice the auxiliary function uses the <code>Worksheets</code> collection instead of the <code>Sheets</code> collection.</sup></em></p>\n<p>How about these 2 lines?</p>\n<blockquote>\n<pre><code>Set newWS = Sheets.Add(After:=Sheets("ZZ_CM_BNREG"))\nnewWS.Name = "Bank Register"\n</code></pre>\n</blockquote>\n<p>As mentioned, these would fail if the workbook is protected or if another sheet with the same name already exists. You can guard with something like:</p>\n<pre><code>On Error Resume Next\nSet newWs = ThisWorkbook.Worksheets.Add(After:=ws)\nIf Err.Number <> 0 Then\n MsgBox "Cannot insert new worksheet", vbExclamation, "Failed"\n Err.Clear\n 'Restore state or exit method\nEnd If\nnewWs.Name = targetShtName\nIf Err.Number <> 0 Then\n MsgBox "Cannot rename worksheet", vbExclamation, "Failed"\n 'This might not be critical so just resume\nEnd If\nOn Error GoTo 0\n</code></pre>\n<p><em><sup>Notice that I haven't retrieved the source worksheet again, unnecessarily. Instead I simply used <code>After:=ws</code></sup></em></p>\n<p><strong>Finding desired range</strong></p>\n<blockquote>\n<p>In order to search for the last cell, I used a function that finds the last cell with data.</p>\n</blockquote>\n<p>I am not sure what the <code>3</code> value does when calling the <code>FindLast</code> method with <code>FindLast(3, "ZZ_CM_BNREG")</code>. I suspect you are starting from the 3rd row.</p>\n<p>The commented line <code>Set lastCell = Range(Cells.Find("*", , xlFormulas, , xlRows, xlPrevious, , , False), Cells.Find("*", , xlFormulas, , xlColumns, xlPrevious, , , False))</code> returns a <code>Range</code> object while the variable was declared as text with <code>Dim lastCell As String</code>. The commented line simply does not compile if I uncomment it. It's missing a trailing <code>.Address</code> and the <code>Set</code> needs to be removed. Anyway, I assume your <code>FindLast</code> function returns the text address of the last row and column with data in a similar manner with the modified commented line.</p>\n<p>You are looking for the desired text with:</p>\n<blockquote>\n<pre><code>'Unmerge all cells in Column A & get cell address of searchCell\nWith ws\n\n ws.Activate\n \n Range("A:A").UnMerge\n \n Set searchCell = .Cells.Find(What:="Disbursements", _\n SearchFormat:=True)\n \n If searchCell Is Nothing Then\n MsgBox ("Error")\n Else\n firstCell = searchCell.Address\n End If\n\nEnd With\n</code></pre>\n</blockquote>\n<p>but although you are unmerging column A you are searching for your text within the whole worksheet with <code>ws.Cells.Find(What:="Disbursements", SearchFormat:=True)</code> (<code>ws</code> is implied from the <code>With</code> block).</p>\n<p>Assuming there is no "Disbursements" value in columns A and B but there is such a value in column C then your code copies data starting with column C and lose the information in column A and B. As I am unsure if this is intended functionality or not, I made the assumption that you want all columns of data regardless where the keyword is found.</p>\n<blockquote>\n<p>Instead of deleting the rows below the contiguous range, should I just copy the contiguous rows to begin with? Is there a better way to delete the rows below the first blank row?</p>\n</blockquote>\n<p>Yes, it's faster to simply copy only what you need instead of copying useless data that you are going to delete anyway. Your second question suggests that you are only interested in data up to (but not including) the first blank row.</p>\n<p>I do not know what you consider a "blank row" to be. I can see that you find the last row (in the target sheet) with <code>Sheets("Bank Register").Range("A1").End(xlDown).Row</code> but that means you are actually looking for the first blank cell in the 'A' column and you don't care if there is data in the rest of the columns. Anyway, I assumed that you are interested in actual "blank rows" (i.e. no data in any of the columns) not just on the 'A' column. Here is a function that can check if a row is empty for a 2D array:</p>\n<pre><code>Private Function Is2DArrayRowEmpty(arr() As Variant, ByVal rowIndex As Long, Optional ByVal ignoreEmptyStrings As Boolean = False) As Boolean\n Dim j As Long\n Dim v As Variant\n \n For j = LBound(arr, 2) To UBound(arr, 2)\n v = arr(rowIndex, j)\n Select Case VBA.VarType(v)\n Case VbVarType.vbEmpty\n 'Continue to next element\n Case VbVarType.vbString\n If Not ignoreEmptyStrings Then Exit Function\n If v <> vbNullString Then Exit Function\n Case Else\n Exit Function\n End Select\n Next j\n Is2DArrayRowEmpty = True 'If code reached this line then row is Empty\nEnd Function\n</code></pre>\n<p>Reading the worksheet's used range into an array should give us the flexibility to find the desired range faster.</p>\n<p>It's not really needed to insert a new worksheet (and to turn the application state to 'off' and later back 'on') if we cannot find any data that we want to take across. It makes more sense to first search for the data and only then proceed with the other operations.</p>\n<p><strong>Final code</strong></p>\n<p>Code in a standard module:</p>\n<pre><code>Option Explicit\n\nSub Reformat_ZZ_CM_BNREG()\n Const searchText As String = "Disbursements"\n Const sourceShtName As String = "ZZ_CM_BNREG"\n Const targetShtName As String = "Bank Register"\n \n Dim sourceWS As Worksheet\n Dim targetWS As Worksheet\n \n Set sourceWS = GetWorksheetByName(sourceShtName, ThisWorkbook)\n If sourceWS Is Nothing Then\n MsgBox "Missing worksheet", vbExclamation, "Cancelled"\n Exit Sub\n End If\n \n Dim rngUsed As Range\n \n On Error Resume Next\n Set rngUsed = sourceWS.UsedRange\n On Error GoTo 0\n If rngUsed Is Nothing Then\n MsgBox "Sheet has no data", vbExclamation, "Cancelled"\n Exit Sub\n ElseIf rngUsed.Count = 1 Then\n MsgBox "Sheet has only 1 cell of data", vbExclamation, "Cancelled"\n Exit Sub\n End If\n \n Dim arrData() As Variant: arrData = rngUsed.Value2\n Dim lowRowIndex As Long: lowRowIndex = LBound(arrData, 1)\n Dim uppRowIndex As Long: uppRowIndex = UBound(arrData, 1)\n Dim v As Variant\n Dim i As Long\n Dim firstRow As Long\n Dim lastRow As Long\n \n i = lowRowIndex\n For Each v In arrData 'Traverses array in column-wise order (faster than For...To)\n If VarType(v) = vbString Then\n If InStr(1, v, searchText, vbTextCompare) > 0 Then\n firstRow = i + 1\n Exit For\n End If\n End If\n i = i + 1\n If i > uppRowIndex Then 'Next column follows - You might want to Exit For if you are only interested in the first column\n i = lowRowIndex\n End If\n Next v\n \n If firstRow = 0 Then\n MsgBox "Text not found", vbExclamation, "Cancelled"\n Exit Sub\n End If\n \n 'Find last non-blank row\n lastRow = uppRowIndex\n For i = firstRow To uppRowIndex\n If Is2DArrayRowEmpty(arrData, i, True) Then\n lastRow = i - 1\n Exit For\n End If\n Next i\n If lastRow < firstRow Then\n MsgBox "No rows found after desired row", vbExclamation, "Cancelled"\n Exit Sub\n End If\n \n Dim app As New ExcelAppState: app.Sleep: app.StoreState\n\n 'Prepare Target\n On Error Resume Next\n Set targetWS = ThisWorkbook.Worksheets.Add(After:=sourceWS)\n If Err.Number <> 0 Then\n MsgBox "Cannot insert new worksheet", vbExclamation, "Failed"\n Err.Clear\n app.RestoreState\n Exit Sub\n End If\n targetWS.Name = targetShtName\n If Err.Number <> 0 Then\n MsgBox "Cannot rename worksheet", vbInformation, "Renaming skipped"\n 'This might not be critical so just continue\n End If\n On Error GoTo 0\n \n 'Write data\n With rngUsed\n Range(.Cells(firstRow, 1), .Cells(lastRow, .Columns.Count)).Copy _\n Destination:=targetWS.Cells(1, 1)\n End With\n \n sourceWS.Delete\n app.RestoreState\nEnd Sub\n\nPublic Function GetWorksheetByName(ByVal wsName As String, ByVal book As Workbook) As Worksheet\n On Error Resume Next\n Set GetWorksheetByName = book.Worksheets(wsName)\n On Error GoTo 0\nEnd Function\n\nPrivate Function Is2DArrayRowEmpty(arr() As Variant, ByVal rowIndex As Long, Optional ByVal ignoreEmptyStrings As Boolean = False) As Boolean\n Dim j As Long\n Dim v As Variant\n \n For j = LBound(arr, 2) To UBound(arr, 2)\n v = arr(rowIndex, j)\n Select Case VBA.VarType(v)\n Case VbVarType.vbEmpty\n 'Continue to next element\n Case VbVarType.vbString\n If Not ignoreEmptyStrings Then Exit Function\n If v <> vbNullString Then Exit Function\n Case Else\n Exit Function\n End Select\n Next j\n Is2DArrayRowEmpty = True 'If code reached this line then row is Empty\nEnd Function\n</code></pre>\n<p>and of course, a simplified version of the <code>ExcelAppState</code> class (that I linked to above). This one uses only the 3 application properties that you were using:</p>\n<pre><code>Option Explicit\n\nPrivate m_calculationMode As XlCalculation\nPrivate m_screenUpdating As Boolean\nPrivate m_displayAlerts As Boolean\n\nPrivate m_hasStoredState As Boolean\nPrivate m_hasStoredCalcMode As Boolean\n\nPublic Sub StoreState()\n With Application\n On Error Resume Next 'In case no Workbook is opened\n m_calculationMode = .Calculation\n m_hasStoredCalcMode = (Err.Number = 0)\n On Error GoTo 0\n m_screenUpdating = .ScreenUpdating\n m_displayAlerts = .DisplayAlerts\n End With\n m_hasStoredState = True\nEnd Sub\n\nPublic Sub RestoreState(Optional ByVal maxSecondsToWait As Integer)\n If Not m_hasStoredState Then\n Err.Raise 5, TypeName(Me) & ".RestoreState", "State not stored"\n End If\n With Application\n If m_hasStoredCalcMode Then\n On Error Resume Next\n If .Calculation <> m_calculationMode Then .Calculation = m_calculationMode\n On Error GoTo 0\n End If\n If .ScreenUpdating <> m_screenUpdating Then .ScreenUpdating = m_screenUpdating\n If .DisplayAlerts <> m_displayAlerts Then .DisplayAlerts = m_displayAlerts\n End With\n m_hasStoredState = False\nEnd Sub\n\nPublic Sub Sleep()\n With Application\n On Error Resume Next\n If .Calculation <> xlCalculationManual Then .Calculation = xlCalculationManual\n On Error GoTo 0\n If .ScreenUpdating Then .ScreenUpdating = False\n If .DisplayAlerts Then .DisplayAlerts = False\n End With\nEnd Sub\n\nPublic Sub Wake(Optional ByVal maxSecondsToWait As Integer = 10)\n With Application\n On Error Resume Next\n If .Calculation <> xlCalculationAutomatic Then .Calculation = xlCalculationAutomatic\n On Error GoTo 0\n If Not .ScreenUpdating Then .ScreenUpdating = True\n If Not .DisplayAlerts Then .DisplayAlerts = True\n End With\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T20:55:31.617",
"Id": "503620",
"Score": "0",
"body": "I am blown away by this response from you. This is definitely one of the best responses I've ever received from someone reviewing my code. I will definitely start using some better coding practices. Also, I would love to buy you a coffee if you have an account. In order to use the ExcelAppState, I created a class module, but it isn't working, and I'm getting syntax errors. I looked up the way you're instantiating the class, and people were saying that it's for VB and not VBA. Is this the case or am I doing something else wrong? Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T20:56:38.717",
"Id": "503621",
"Score": "0",
"body": "Do I need to install another reference?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T21:53:06.320",
"Id": "503624",
"Score": "0",
"body": "Also, instead of throwing an error message if the sheet name doesn't exist, can't I just rename sheet 1 to the desired name or is that bad practice? There is always only going to be one sheet in the workbook."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T23:24:24.463",
"Id": "503628",
"Score": "0",
"body": "Instead of using the class, I went ahead and just used the subroutines that you provided me. Does the Me keyword refer to ThisWorkbook? I went ahead and changed it to ThisWorkbook with that assumption. After some adjustments, everything seems to be working properly. I really appreciate this response. Also, what does the preceding m in the private variables refer to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T23:40:47.077",
"Id": "503629",
"Score": "0",
"body": "I apologize for the many questions, but I was curious about the 2DArray function. You are essentially just loading the UsedRange into the array and finding the last blank row, correct? Are there potential issues with using the UsedRange? I've read that there can be issues with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T23:49:39.893",
"Id": "503630",
"Score": "0",
"body": "Note: Your code with a few changes has been added to my question. It works perfectly, but please let me know if there will be any issues with my additions. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T09:07:16.293",
"Id": "503649",
"Score": "2",
"body": "@BobtheBuilder No need to buy me a coffee. My reward is knowing that I was able to help. The ```ExcelAppState``` is definitely a VBA class. Once you insert a class module, you need to make sure you name it properly in the **Properties** pane. See [Print Screen](https://i.stack.imgur.com/48cbI.png). Note that the code must end with ```End Sub``` but for some reason the webpage is not displaying the code tag properly and you see 3 extra quote-like characters that you should not copy across (see same print screen). You do not need to install any other reference!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T09:13:11.010",
"Id": "503650",
"Score": "1",
"body": "@BobtheBuilder I guess if the workbook has only one sheet it's up to you if you want to rename it but if you end up having more than one then you could display a Userform with a Listbox showing all the sheet names and let the user choose which one to use. The ```Me``` keyword always refers to the instance of the class you are currently in. ```ThisWorkbook``` is an object like any other class. Code within the ```ExcelAppState``` can refer to the current instance with the ```Me``` keyword. Similarly, code within a ```Class1``` class can refer to the current instance with ```Me``` as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T09:15:50.387",
"Id": "503651",
"Score": "1",
"body": "@BobtheBuilder You should not have changed ```Me``` to ```ThisWorkbook```. It simply did not work because (I suspect) you did not set-up the class properly (please refer to my previous comment with a print screen). The ```m_``` prefix is just a convention I use to prefix class members. You can use any naming convention you see fit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T09:19:26.257",
"Id": "503652",
"Score": "1",
"body": "@BobtheBuilder Correct, I load the used range into an array and the search for the first blank row. I've been using the ```UsedRange``` property for 8 years and never had issues. As in my response, I always check if it actually set with ```Is Nothing```. Had a quick look at your code and it seems that you declared the ```ExcelAppState``` as a standard .bas module. Try to declare it as a class and use the code in my answer to create a new instance using the ```New``` keyword."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T09:23:12.583",
"Id": "503653",
"Score": "1",
"body": "@BobtheBuilder Finally, a class is a blueprint. Consider a ```Car``` class that has ```Brand``` and ```Model``` properties. You could create an instance that is for example an BMW X5 and another instance of the Car class that is a Tesla Model X. Try googling something like *Class vs Instance* to get a better idea of how it works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T22:24:39.773",
"Id": "503705",
"Score": "1",
"body": "I set up the class correctly the first time using the attributes from your class hosted on GitHub. Was this the correct way to go about it? The attributes are throwing a syntax error. Sorry, I wasn't referring to an instance. I was just wondering whether the attributes were the correct way to initialize the class. Also, based on the class on GitHub, the `End Sub` was already there so I didn't have any issues with that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T22:45:49.837",
"Id": "503708",
"Score": "0",
"body": "Here is a screenshot of the error: https://i.imgur.com/0JiBrWC.png. Note: This does include the class module being named properly. Should the class be set up without these attributes? Also, if I were to go the .bas route, what would I change the `Me` to? Does the code only work for a class module? I've never worked with the `Me` keyword. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T00:22:12.510",
"Id": "503711",
"Score": "1",
"body": "@BobtheBuilder Makes perfect sense now, did not cross my mind to tell you this. Those attributes are always hidden by the IDE. If you create the class yourself then just copy-paste the code starting from ```Option Explicit```. But, if you import the class module from a file then the attributes are always there. Try creating a new class and then export the class module to a .cls file .Then open the .cls file with Notepad (or any text editor) and you will see that the attributes are there. It's just that you should not see them in the IDE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T00:23:16.480",
"Id": "503712",
"Score": "1",
"body": "@BobtheBuilder Please don't go the .bas route. It would defeat the purpose of having the application state as a single snapshot in time. It needs to be a class precisely because you want multiple states (which could be different) to be saved at the same time while multiple routines juggle with application state. I saw that in your answer you used ```ExcelAppState.StoreState``` and that should not compile unless you turned the class into a standard .bas module or the VB_PredeclaredId attribute is set to True (in a text editor and then importing the .cls module)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T00:29:47.423",
"Id": "503713",
"Score": "1",
"body": "@BobtheBuilder ```Dim app As New ExcelAppState: app.Sleep: app.StoreState``` (accompanied later by ```app.RestoreState```) should work once you set up the class properly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T12:29:51.910",
"Id": "503744",
"Score": "0",
"body": "Thank you so much for your help! I was able to get it to work after removing the attributes. I had another question about your function that checks whether an array is empty. Do you use this as a standard for checking all of your arrays? I've been searching online for the best way to check whether an array is empty, and I'm wondering whether I should just use yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T13:10:04.257",
"Id": "503748",
"Score": "2",
"body": "@BobtheBuilder Glad it was helpful. Yes, I do use the array function as a standard. I do not want to use Excel Worksheet functions (e.g. COUNTBLANK) because I want to be application independent (e.g. might use it in Access, Word, AutoCAD and so on). I have a standard library to work with arrays [here](https://github.com/cristianbuse/VBA-ArrayTools) that should work in any VBA-capable application. The function that checks if a row is empty is part of that library."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T14:45:31.023",
"Id": "503757",
"Score": "0",
"body": "If you have the time and if you don't mind, I posted another code for review. I promise this one is muuuuccchhh better. LOL. https://codereview.stackexchange.com/questions/255326/create-table-after-deleting-rows-before-desired-range-and-filter-to-delete-all-o"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-28T15:58:14.330",
"Id": "503776",
"Score": "1",
"body": "if there is any new information that needs to be added into the question from these comments, please edit it in carefully. if you need more conversation about things that don't pertain specifically to this answer, please start chat. please keep in mind that comments are not permanent and can be deleted at any time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T12:02:09.217",
"Id": "504356",
"Score": "0",
"body": "@CristianBuse Also, in my original code, I had a line that unmerged one column's cells, and it also impacted all other columns. What is the best way to go about unmerging columns? Should I just go with `UsedRange.UnMerge`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T12:25:22.647",
"Id": "504359",
"Score": "0",
"body": "Sorry, that wouldn't work. Should I just use `targetWS.Cells.UnMerge`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T12:29:03.487",
"Id": "504360",
"Score": "1",
"body": "@BobtheBuilder You should unmerge only the cells that you are copying across. You can add a second ```With``` before the copy: ```With Range(.Cells(firstRow, 1), .Cells(lastRow, .Columns.Count))``` and then ```.UnMerge``` and only then ```.Copy Destination:=targetWS.Cells(1, 1)``` and you would obviously close both ```End With``` blocks. Alternatively you can just copy the values instead which would not need the unmerge. Something like ```targetRange.Value2 = sourceRange.Value2```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T12:48:44.280",
"Id": "504363",
"Score": "0",
"body": "@CristianBuse Worked like a charm. Thank you, sir."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T14:17:14.977",
"Id": "504371",
"Score": "0",
"body": "@CristianBuse After unmerging the cells, there are two columns within the used range that are completely blank. Should I delete those columns using another `With` statement within the one I just created?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T14:57:58.750",
"Id": "504377",
"Score": "0",
"body": "@BobtheBuilder It depends. You need logic to identify the blank columns. They might not be there all the time in all the workbooks that you use (or same order). Once you know what needs to be deleted then you can do it in any way you want. The ```With``` statement is optional, it all comes down to your coding style. If you decide it's worth the time, then simply post a new question toghether with some print screens of the sheet data and a minimal code that shows what you are trying to achieve. For example, do you always expect a specific set of table headers? Then things can be automated."
}
],
"meta_data": {
"CommentCount": "26",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T16:18:53.857",
"Id": "255006",
"ParentId": "254730",
"Score": "5"
}
},
{
"body": "<p>Updated Code Based on <a href=\"https://codereview.stackexchange.com/a/255006/100790\">Accepted Solution</a></p>\n<pre><code>Option Explicit\n\nSub Reformat_ZZ_CM_BNREG()\n Const searchText As String = "Disbursements"\n Const sourceShtName As String = "ZZ_CM_BNREG"\n Const targetShtName As String = "Bank Register"\n \n Dim sourceWS As Worksheet\n Dim targetWS As Worksheet\n \n Set sourceWS = GetWorksheetByName(sourceShtName, ActiveWorkbook)\n If sourceWS Is Nothing Then\n Set sourceWS = GetUpdatedName(ActiveWorkbook)\n If sourceWS Is Nothing Then\n MsgBox "Please change sheet (tab) name to ZZ_CM_BNREG", vbExclamation, "Cancelled"\n Exit Sub\n End If\n End If\n \n Dim rngUsed As Range\n \n On Error Resume Next\n Set rngUsed = sourceWS.UsedRange\n On Error GoTo 0\n If rngUsed Is Nothing Then\n MsgBox "Sheet has no data", vbExclamation, "Cancelled"\n Exit Sub\n ElseIf rngUsed.Count = 1 Then\n MsgBox "Sheet has only 1 cell of data", vbExclamation, "Cancelled"\n Exit Sub\n End If\n \n Dim arrData() As Variant: arrData = rngUsed.Value2\n Dim lowRowIndex As Long: lowRowIndex = LBound(arrData, 1)\n Dim uppRowIndex As Long: uppRowIndex = UBound(arrData, 1)\n Dim v As Variant\n Dim i As Long\n Dim firstRow As Long\n Dim lastRow As Long\n \n i = lowRowIndex\n For Each v In arrData 'Traverses array in column-wise order (faster than For...To)\n If VarType(v) = vbString Then\n If InStr(1, v, searchText, vbTextCompare) > 0 Then\n firstRow = i + 1\n Exit For\n End If\n End If\n i = i + 1\n If i > uppRowIndex Then 'Next column follows - You might want to Exit For if you are only interested in the first column\n i = lowRowIndex\n End If\n Next v\n \n If firstRow = 0 Then\n MsgBox "Text not found", vbExclamation, "Cancelled"\n Exit Sub\n End If\n \n 'Find last non-blank row\n lastRow = uppRowIndex\n For i = firstRow To uppRowIndex\n If Is2DArrayRowEmpty(arrData, i, True) Then\n lastRow = i - 1\n Exit For\n End If\n Next i\n If lastRow < firstRow Then\n MsgBox "No rows found after desired row", vbExclamation, "Cancelled"\n Exit Sub\n End If\n \n ExcelAppState.StoreState\n ExcelAppState.Sleep\n 'Dim app As New ExcelAppState: app.Sleep: app.StoreState\n\n 'Prepare Target\n On Error Resume Next\n Set targetWS = ActiveWorkbook.Worksheets.Add(After:=sourceWS)\n If Err.Number <> 0 Then\n MsgBox "Cannot insert new worksheet", vbExclamation, "Failed"\n Err.Clear\n ExcelAppState.RestoreState\n Exit Sub\n End If\n targetWS.Name = targetShtName\n If Err.Number <> 0 Then\n MsgBox "Cannot rename worksheet", vbInformation, "Renaming skipped"\n 'This might not be critical so just continue\n End If\n On Error GoTo 0\n \n 'Write data\n With rngUsed\n Range(.Cells(firstRow, 1), .Cells(lastRow, .Columns.Count)).Copy _\n Destination:=targetWS.Cells(1, 1)\n End With\n \n sourceWS.Delete\n ExcelAppState.RestoreState\nEnd Sub\n\nPublic Function GetWorksheetByName(ByVal wsName As String, ByVal book As Workbook) As Worksheet\n On Error Resume Next\n Set GetWorksheetByName = book.Worksheets(wsName)\n On Error GoTo 0\nEnd Function\n\nPublic Function GetUpdatedName(ByVal actBook As Workbook) As Worksheet\n On Error Resume Next\n Set GetUpdatedName = actBook.Worksheets(1)\n On Error GoTo 0\nEnd Function\n\nPrivate Function Is2DArrayRowEmpty(arr() As Variant, ByVal rowIndex As Long, Optional ByVal ignoreEmptyStrings As Boolean = False) As Boolean\n Dim j As Long\n Dim v As Variant\n \n For j = LBound(arr, 2) To UBound(arr, 2)\n v = arr(rowIndex, j)\n Select Case VBA.VarType(v)\n Case VbVarType.vbEmpty\n 'Continue to next element\n Case VbVarType.vbString\n If Not ignoreEmptyStrings Then Exit Function\n If v <> vbNullString Then Exit Function\n Case Else\n Exit Function\n End Select\n Next j\n Is2DArrayRowEmpty = True 'If code reached this line then row is Empty\nEnd Function\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T23:56:18.403",
"Id": "255265",
"ParentId": "254730",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "255006",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T05:48:29.540",
"Id": "254730",
"Score": "6",
"Tags": [
"vba",
"excel"
],
"Title": "Copy a contiguous sub-column of cells"
}
|
254730
|
<p>I have written a game. Its a very simple clone of the Dwarf Fortress. The game seems to be working fine at least from my testing. I would like to improve my programming game and fix all the bad design, bad practices and possible performance bottlenecks in my code. So any comment that would help me become a better developer is welcome.</p>
<p>Since the game contains multiple classes it seems kind of pointless to paste every class here so here is the link to repository: <a href="https://github.com/th3v0ice/Dwarf_Fortress_Clone" rel="noreferrer">https://github.com/th3v0ice/Dwarf_Fortress_Clone</a></p>
<p>Armor.cpp</p>
<pre><code>#include "Armor.h"
std::vector<std::string> Armor::armor_names = {
"Edge of Patience",
"Defense of Twilight",
"Armor of Absorption",
"Armor of Dominance",
"Adamantite Cuirass",
"Golden Armor",
"Armor of Illusions",
"Chestplate of Soul",
"Mail Chestplate",
"Vengeful Adamantite",
"Tunic of Fury",
"Protector of Souls",
"Chestguard of Time"
};
std::shared_ptr<Armor> Armor::generateArmor(){
unsigned seed = time(0);
srand(seed);
int def = rand() % 200;
int idx = rand() % armor_names.size();
std::shared_ptr<Armor> armor(new Armor(armor_names[idx], def));
return armor;
}
</code></pre>
<p>Armor.h</p>
<pre><code>#pragma once
#include "Item.h"
#include <vector>
#include <memory>
class Armor : public Item
{
private:
int defense_value;
public:
static std::vector<std::string> armor_names;
Armor(std::string _name, int value) : defense_value(value) {
type = item_type::ITEM_TYPE_ARMOR;
name = _name;
};
int get_defense() { return defense_value; }
std::string toString(){
std::string res = "[A] " + name + " (+" + std::to_string(defense_value) + " def)";
return res;
}
static std::shared_ptr<Armor> generateArmor();
};
</code></pre>
<p>Consumable.cpp</p>
<pre><code>#include "Consumable.h"
std::shared_ptr<Consumable> Consumable::generateConsumable() {
unsigned seed = time(0);
srand(seed);
int hp = rand() % 100;
std::string hpn = "Lesser Health Potion";
if(hp > 80)
hpn = "Greater Health Potion";
else if(hp > 50)
hpn = "Great Health Potion";
std::shared_ptr<Consumable> cons(new Consumable(hpn, hp));
return cons;
}
</code></pre>
<p>Consumable.h</p>
<pre><code>#pragma once
#include "Item.h"
#include <memory>
class Consumable : public Item
{
private:
std::size_t amount;
public:
Consumable(std::string _name, std::size_t a) : amount(a) {
type = item_type::ITEM_TYPE_POTION;
name = _name;
};
~Consumable() {};
int get_amount() { return amount; }
std::string toString(){
std::string res = "[C] " + name + " (+" + std::to_string(amount) + " health)";
return res;
}
static std::shared_ptr<Consumable> generateConsumable();
};
</code></pre>
<p>Entity.cpp</p>
<pre><code>#include "Entity.h"
Entity::Entity()
{
name = "";
health = 100;
armor = nullptr;
weapon = nullptr;
attack = 10;
defense = 0;
inventory.setLimit(3);
}
bool Entity::reduceHealth(int amount)
{
health -= amount;
if (health <= 0)
return false;
return true;
}
int Entity::equipOrConsume(std::shared_ptr<Item> i)
{
switch (i->getType()) {
case item_type::ITEM_TYPE_ARMOR:
{
std::shared_ptr<Armor> a_armor = std::dynamic_pointer_cast<Armor>(i);
//We first unequip the previous armor if one existed
if (armor)
defense -= armor->get_defense();
defense += a_armor->get_defense();
armor = a_armor;
break;
}
case item_type::ITEM_TYPE_POTION:
{
std::shared_ptr<Consumable> c_cons = std::dynamic_pointer_cast<Consumable>(i);
health += c_cons->get_amount();
if (health > 100)
health = 100;
break;
}
case item_type::ITEM_TYPE_WEAPON:
{
std::shared_ptr<Weapon> w_weapon = std::dynamic_pointer_cast<Weapon>(i);
//Unequip a weapon first
if (weapon)
attack -= weapon->get_damage();
attack += w_weapon->get_damage();
weapon = w_weapon;
break;
}
default:
{
break;
}
}
return 0;
}
</code></pre>
<p>Entity.h</p>
<pre><code>#pragma once
#include "Inventory.h"
#include "Weapon.h"
#include "Armor.h"
#include "Consumable.h"
#include "Item.h"
#include <string>
#include <memory>
class Entity
{
protected:
std::string name;
std::shared_ptr<Armor> armor;
std::shared_ptr<Weapon> weapon;
int
health,
attack,
defense;
Inventory inventory;
public:
Entity();
~Entity() {};
/**
* Reduces the health of the entity by the given amount.
* If the health goes to zero or below zero, method will
* return false, which means that the entity is dead. Otherwise
* it will return true;
*/
bool reduceHealth(int amount);
std::string& getName() {
return name;
}
int getHealth() {
return health;
}
/**
* Equip will calculate entities armor and attack values based on the
* equiped item.
*/
int equipOrConsume(std::shared_ptr<Item> i);
void testFillInventory(){
inventory.fillWithDummyData();
}
virtual void dropFromInventory() = 0;
int getAttack() { return attack; }
int getDefense() { return defense; }
};
</code></pre>
<p>Inventory.cpp</p>
<pre><code>#include "Inventory.h"
void Inventory::drawInventory(BUFFER &buffer)
{
int
height = buffer.size(),
width = buffer[0].size(),
inv_width = (width >= 50) ? 50 : width,
inv_height = (height >= 16) ? 16 : height,
temp_h_start = height / 2 - inv_height / 2,
h_start = (temp_h_start > 0) ? temp_h_start : 0,
temp_w_start = width / 2 - inv_width / 2,
w_start = (temp_w_start > 0) ? temp_w_start : 0,
spacing = 2;
//Clear the buffer in that region
for (int i = h_start; i < h_start + inv_height; i++) {
buffer[i][w_start] = '|';
buffer[i][w_start + inv_width-1] = '|';
for (int j = w_start + 1; j < w_start + inv_width - 1; j++) {
buffer[i][j] = ' ';
}
}
//First line ╔════════╗
for (int j = w_start; j < w_start + inv_width; j++) {
if(j == w_start)
buffer[h_start][j] = '+';
else if(j == w_start + inv_width - 1)
buffer[h_start][j] = '+';
else
buffer[h_start][j] = '-';
}
h_start += spacing;
selected_item_idx = 0;
selected_item_idx_y = h_start;
selected_item_idx_x = w_start + spacing;
//Inventory is limited to 3 items
for (int i = h_start, inv_cnt = 0; i < h_start + inv_height - spacing, inv_cnt < inventory.size(); i++, inv_cnt++) {
std::string desc = (inv_cnt == 0) ? "*" : " ";
desc += inventory[inv_cnt]->toString();
int start_offset = w_start + spacing;
for (int j = start_offset, k = 0; j < w_start + inv_width - spacing && k < desc.length(); j++, k++) {
buffer[i][j] = desc[k];
}
}
if(inv_height < 16)
h_start = inv_height - 1;
else
h_start = h_start + inv_height - 2;
//Last line ╚══Drop(x)══Use(u)═══╝
std::string usedu = "Drop(x)---Use(u)";
int cnt = 0;
for (int j = w_start; j < w_start + inv_width; j++) {
if(j == w_start)
buffer[h_start][j] = '+';
else if(j == w_start + inv_width - 1)
buffer[h_start][j] = '+';
else if(j > w_start + spacing && cnt < usedu.length()) {
buffer[h_start][j] = usedu[cnt];
cnt++;
} else
buffer[h_start][j] = '-';
}
return;
}
void Inventory::dropFromInventory()
{
if(inventory.size() > 0 && inventory.size() > selected_item_idx)
inventory.erase(inventory.begin() + selected_item_idx);
}
void Inventory::changeInventorySelection(int p, BUFFER &buffer)
{
buffer[selected_item_idx_y][selected_item_idx_x] = ' ';
if(inventory.empty())
return;
if(p > 0 && selected_item_idx < inventory.size()-1){
selected_item_idx++;
selected_item_idx_y++;
}
else if(p < 0 && selected_item_idx > 0){
selected_item_idx--;
selected_item_idx_y--;
}
buffer[selected_item_idx_y][selected_item_idx_x] = '*';
return;
}
std::shared_ptr<Item> Inventory::getSelectedItem()
{
if(inventory.size() > 0)
return inventory[selected_item_idx];
return std::shared_ptr<Item>(nullptr);
}
int Inventory::addToInventory(std::shared_ptr<Item> item) {
if(inventory.size() >= limit)
return -1;
inventory.push_back(item);
return 0;
}
</code></pre>
<p>Inventory.h</p>
<pre><code>#include <vector>
#include <memory>
#include "Item.h"
#include "Weapon.h"
#include "Armor.h"
#include "Consumable.h"
#include "Map.h"
#pragma once
class Inventory
{
public:
Inventory() : selected_item_idx(0), limit(3) { inventory.reserve(3); }
Inventory(int l): selected_item_idx(0), limit(l) { inventory.reserve(limit); }
void drawInventory(BUFFER &buffer);
void dropFromInventory();
int addToInventory(std::shared_ptr<Item> item);
void changeInventorySelection(int p, BUFFER &buffer);
void setLimit(int lim) { limit = lim; }
int getLimit() { return limit; }
std::shared_ptr<Item> getSelectedItem();
void fillWithDummyData(){
std::shared_ptr<Weapon> w(new Weapon("Mighty sword", 100));
std::shared_ptr<Armor> a(new Armor("Shiny armor", 20));
std::shared_ptr<Consumable> c(new Consumable("Small potion", 10));
std::shared_ptr<Item> w_i = w;
std::shared_ptr<Item> a_i = a;
std::shared_ptr<Item> c_i = c;
inventory.push_back(w_i);
inventory.push_back(a_i);
inventory.push_back(c_i);
}
std::size_t size() { return inventory.size(); }
void clear() { inventory.clear(); }
item_type getItemTypeAtIndex(int i) { return inventory[i]->getType(); };
private:
std::vector<std::shared_ptr<Item>> inventory;
int selected_item_idx;
int limit;
//Coordinates for a star which designates selected item.
//It will be much faster to change the selection instead
//of drawing everything again.
int selected_item_idx_x;
int selected_item_idx_y;
};
</code></pre>
<p>Item.h</p>
<pre><code>#pragma once
#include <string>
enum class item_type {
ITEM_TYPE_ARMOR = 0,
ITEM_TYPE_WEAPON = 1,
ITEM_TYPE_POTION = 2
};
class Item
{
private:
protected:
item_type type;
std::string name;
public:
Item() {};
virtual ~Item();
item_type getType() {
return type;
}
virtual std::string toString() = 0;
void setType(item_type itype) {
type = itype;
}
};
</code></pre>
<p>Map.cpp</p>
<pre><code>#include "Map.h"
int Map::loadMap(std::string fileName)
{
namespace bpt = boost::property_tree;
std::string data;
bpt::ptree root;
try {
bpt::read_json(fileName, root); //pt::json_parser::json_parser_error
}
catch (bpt::json_parser::json_parser_error) {
std::cout << "Ill formatted JSON file!" << std::endl;
return BAD_JSON;
}
try {
height = root.get<int>("height");
}
catch (bpt::ptree_bad_path) {
std::cout << "Height is not specified in maps configuration file!" << std::endl;
return HEIGHT_ERROR;
}
try {
width = root.get<int>("width");
}
catch (bpt::ptree_bad_path) {
std::cout << "Width is not specified in maps configuration file!" << std::endl;
return WIDTH_ERROR;
}
try {
data = root.get<std::string>("data");
}
catch (bpt::ptree_bad_path) {
std::cout << "Data is not specified in maps configuration file!" << std::endl;
return DATA_ERROR;
}
//Resize the map to accomodate the data and fill the map with blanks
map.resize((height + FULL_BORDER) * (width + FULL_BORDER), L" ");
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::wstring wide = converter.from_bytes(data);
//Position the data correctly inside the map
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
int map_index = (i + BORDER) * (width + FULL_BORDER) + (j + BORDER);
int data_index = i * width + j;
map[map_index] = wide[data_index];
}
}
return 0;
}
int Map::getMapAroundPlayer(int x, int y, int center_x, int center_y, BUFFER& buffer)
{
//The current position of the player on the screen is (center_x, center_y)
//The current position of the player on the map is (x, y)
int
map_start_x = x - center_x,
map_start_y = y - center_y,
bufh = buffer.size(),
bufw = buffer[0].size();
for (int i = 0; i < buffer.size(); i++) {
for (int j = 0; j < bufw; j++) {
int map_index = (map_start_y + i) * (width + FULL_BORDER) + map_start_x;
buffer[i][j] = map[map_index + j];
}
}
return 0;
}
int Map::updateMap(int x, int y, data_t c) {
//The current position of the player on the map is (x, y)
int
offset_x = x,
offset_y = y;
int map_index = offset_y * (width + FULL_BORDER) + offset_x;
map[map_index] = c;
return 0;
}
int Map::self_check()
{
test_load_bad_file1();
test_load_bad_file2();
test_load_bad_file3();
test_load_bad_file4();
test_load_good_file();
test_get_map();
return 0;
}
int Map::test_load_bad_file1()
{
std::cout << "Invoking test 1 ... " << std::endl;
int ret = loadMap("tests/bad_test1.json");
if (ret == HEIGHT_ERROR)
std::cout << "Pass" << std::endl;
else
std::cout << "Fail" << std::endl;
return 0;
}
int Map::test_load_bad_file2()
{
std::cout << "Invoking test 2 ... " << std::endl;
int ret = loadMap("tests/bad_test2.json");
if (ret == WIDTH_ERROR)
std::cout << "Pass" << std::endl;
else
std::cout << "Fail" << std::endl;
return 0;
}
int Map::test_load_bad_file3()
{
std::cout << "Invoking test 3 ... " << std::endl;
int ret = loadMap("tests/bad_test3.json");
if (ret == DATA_ERROR)
std::cout << "Pass" << std::endl;
else
std::cout << "Fail" << std::endl;
return 0;
}
int Map::test_load_bad_file4()
{
std::cout << "Invoking test 4 ... " << std::endl;
int ret = loadMap("tests/bad_test4.json");
if (ret == BAD_JSON)
std::cout << "Pass" << std::endl;
else
std::cout << "Fail" << std::endl;
return 0;
}
int Map::test_load_good_file()
{
std::cout << "Invoking test 5 ... " << std::endl;
int ret = loadMap("tests/good_test.json");
if (ret == 0)
std::cout << "Pass" << std::endl;
else
std::cout << "Fail" << std::endl;
return 0;
}
int Map::draw_map(BUFFER &buffer)
{
int height = buffer.size();
int width = buffer[0].size();
std::wstring buf;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
data_t c = buffer[i][j];
buf.append(c);
}
}
erase();
move(0,0);
addwstr(buf.c_str());
refresh();
return 0;
}
int Map::test_get_map()
{
std::chrono::seconds tm(1);
BUFFER buffer;
getMapAroundPlayer(92, 15, 185, 30, buffer);
draw_map(buffer);
std::this_thread::sleep_for(tm);
//Move right
getMapAroundPlayer(93, 15, 185, 30, buffer);
draw_map(buffer);
std::this_thread::sleep_for(tm);
//Move right
getMapAroundPlayer(94, 15, 185, 30, buffer);
draw_map(buffer);
std::this_thread::sleep_for(tm);
//Move up
getMapAroundPlayer(94, 14, 185, 30, buffer);
draw_map(buffer);
std::this_thread::sleep_for(tm);
std::this_thread::sleep_for(tm);
std::this_thread::sleep_for(tm);
return 0;
}
</code></pre>
<p>Map.h</p>
<pre><code>#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <locale>
#include <codecvt>
#include <curses.h>
#include <stdio.h>
//Needed for testing.
#include <chrono>
#include <thread>
#include <sstream>
enum {
HEIGHT_ERROR = -1,
WIDTH_ERROR = -2,
DATA_ERROR = -3,
BAD_JSON = -4
};
/**
* Note: If the console window size changes, we could change the
* border size accordingly.
*/
#define FULL_BORDER 400
#define BORDER (FULL_BORDER/2)
#define CLEAR printf("\033[H\033[J")
#define GOTOXY(x,y) printf("\033[%d;%dH", (y), (x))
typedef std::wstring data_t;
typedef std::vector<data_t> VSBUFF;
typedef std::vector<VSBUFF> BUFFER;
class Map
{
private:
int width;
int height;
/**
* Map is actually bigger by 200 characters on each side.
* This will enable very fast retrieving of the "view" player
* is looking at.
*/
VSBUFF map;
public:
Map(int w, int h) {
width = w + FULL_BORDER;
height = h + FULL_BORDER;
map.resize(width * height);
}
Map() {
width = 0;
height = 0;
map.clear();
}
~Map() {
map.clear();
}
/**
* Loads the configuration file in JSON format of the map view. Expected
* value : data pairs are
*
* width -> width of the map
* height -> height of the map
* data -> Array of characters representing specific things on the map.
* Map is expected to be a single array.
*/
int loadMap(std::string fileName);
/**
* Returns the area around the player given the players coordinates. Player
* is always centered on the screen. If the player is near a maps bounds
* then buffer will be populated with blank's or "space" characters.
*
* x -> is the players X coordinate on the map, not on the screen
* y -> is the players Y coordinate on the map, not on the screen
* center_x -> is the center x of the console window
* center_y -> is the center y of the console window
* buffer -> is a reference to the vector matrix in which we should
* put the screen data
*/
int getMapAroundPlayer(int x, int y, int bufw, int bufh, BUFFER& buffer);
/**
* Updates the map at the designated coordinates.
*
* x -> is the players X coordinate on the map, not on the screen
* y -> is the players Y coordinate on the map, not on the screen
* c -> character to place at coordinates
*/
int updateMap(int x, int y, data_t c);
//Testing code
int self_check();
int draw_map(BUFFER& buffer);
int getWidth() { return width; }
int getHeight() { return height; }
private:
//UNIT TESTS BELOW
int test_load_bad_file1();
int test_load_bad_file2();
int test_load_bad_file3();
int test_load_bad_file4();
int test_load_good_file();
int test_get_map();
};
</code></pre>
<p>Monster.cpp</p>
<pre><code>
#include "Monster.h"
/**
* All ASCII Art was downloaded from
*
* https://www.asciiart.eu/mythology
*
*/
creature_t Monster::centaur = {
" <=======]}======",
" --. /|",
" _\"/_.'/",
" .'._._,.'",
" :/ \\{}/",
"(L /--',----._",
" | \\\\",
" : /-\\ .'-'\\ / |",
" \\\\, || \\|",
" \\/ || ||"
};
creature_t Monster::ghost = {
" .-.",
" ( \" )",
" /\\_.' '._/\\",
" | |",
" \\ /",
" \\ /`",
" (__) /",
" `.__.'"
};
creature_t Monster::gryphon = {
" .-')",
" (`_^ ( .----`/",
" ` ) \\_/` __/ __,",
" __{ |` __/ /_/",
" / _{ \\__/ '--. //",
" \\_> \\_\\ >__/ \\((",
" _/ /` _\\_ |))",
" /__( /______/`"
};
std::vector<creature_t> Monster::creatures = {centaur, ghost, gryphon};
void Monster::fillInventoryWithRandomItems() {
unsigned seed = time(0);
srand(seed);
int inv_size = rand() % inventory.getLimit();
for(int i = 0; i < inv_size; i++) {
int itm_type = rand() % 3;
switch(itm_type)
{
case 0: {
std::shared_ptr<Armor> armor = Armor::generateArmor();
inventory.addToInventory(std::static_pointer_cast<Item>(armor));
break;
}
case 1: {
std::shared_ptr<Weapon> weapon = Weapon::generateWeapon();
inventory.addToInventory(std::static_pointer_cast<Item>(weapon));
break;
}
case 2: {
std::shared_ptr<Consumable> cons = Consumable::generateConsumable();
inventory.addToInventory(std::static_pointer_cast<Item>(cons));
break;
}
}
}
return;
}
std::shared_ptr<Monster> Monster::generateMonster() {
unsigned seed = time(0);
srand(seed);
int att = rand() % 80;
int def = rand() % 300;
std::shared_ptr<Monster> monster(new Monster("Monster", att, def));
monster->fillInventoryWithRandomItems();
return monster;
}
void Monster::itemsInInventory(int& w, int& a, int& c) {
w = 0;
a = 0;
c = 0;
for(int i = 0; i < inventory.size(); i++) {
item_type t = inventory.getItemTypeAtIndex(i);
switch (t)
{
case item_type::ITEM_TYPE_ARMOR:
a++;
break;
case item_type::ITEM_TYPE_WEAPON:
w++;
break;
case item_type::ITEM_TYPE_POTION:
c++;
break;
default:
break;
}
}
return;
}
</code></pre>
<p>Monster.h</p>
<pre><code>#pragma once
#include "Entity.h"
#include <vector>
#include <memory>
#include <map>
typedef std::vector<std::string> creature_t;
class Monster : public Entity
{
private:
static creature_t centaur;
static creature_t ghost;
static creature_t gryphon;
static std::vector<creature_t> creatures;
creature_t shape;
public:
Monster(std::string _n, int att, int def) {
name = _n;
health = 100;
attack = att;
defense = def;
unsigned seed = time(0);
srand(seed);
shape = creatures[rand() % 3];
};
~Monster(){};
void fillInventoryWithRandomItems();
static std::shared_ptr<Monster> generateMonster();
void dropFromInventory() { inventory.clear(); };
void itemsInInventory(int& w, int& a, int& c);
creature_t getShape() { return shape; }
};
</code></pre>
<p>Player.cpp</p>
<pre><code>#include "Player.h"
std::vector<std::string> Player::shape = {
" \\\\\\|||///",
" . =======",
"/ \\| O O |",
"\\ / \\`___'/ ",
" # _| |_",
"(#) ( )",
" #\\//|* *|\\\\ ",
" #\\/( * )/",
" # =====",
" # ( U )",
" # || ||",
".#---'| |`----.",
"`#----' `-----'"
};
void Player::useSelectedItemFromInventory() {
std::shared_ptr<Item> item = inventory.getSelectedItem();
if(!item)
return;
inventory.dropFromInventory();
equipOrConsume(item);
return;
}
void Player::drawCharacterStats(BUFFER &buffer) {
int
height = buffer.size(),
width = buffer[0].size(),
inv_width = (width >= 50) ? 50 : width,
inv_height = (height >= 16) ? 16 : height,
temp_h_start = height / 2 - inv_height / 2,
h_start = (temp_h_start > 0) ? temp_h_start : 0,
temp_w_start = width / 2 - inv_width / 2,
w_start = (temp_w_start > 0) ? temp_w_start : 0,
spacing = 2;
//Clear the buffer in that region
for (int i = h_start; i < h_start + inv_height; i++) {
buffer[i][w_start] = '|';
buffer[i][w_start + inv_width-1] = '|';
for (int j = w_start + 1; j < w_start + inv_width - 1; j++) {
buffer[i][j] = ' ';
}
}
//First line ╔════════╗
for (int j = w_start; j < w_start + inv_width; j++) {
if(j == w_start)
buffer[h_start][j] = '+';
else if(j == w_start + inv_width - 1)
buffer[h_start][j] = '+';
else
buffer[h_start][j] = '-';
}
h_start += spacing;
std::string desc;
int start_offset = w_start + spacing;
#define PRINT_STAT(description, var){\
std::stringstream ss;\
ss << description << var;\
desc = ss.str();\
h_start++;\
for (int j = start_offset, k = 0; j < w_start + inv_width - spacing && k < desc.length(); j++, k++)\
buffer[h_start][j] = desc[k];\
}
PRINT_STAT("Health: ", health)
PRINT_STAT("Attack: ", attack)
PRINT_STAT("Defense: ", defense)
PRINT_STAT("====================" , "-")
if(armor)
PRINT_STAT("Armor: ", armor->toString())
else
PRINT_STAT("Armor: ", "Not equiped")
if(weapon)
PRINT_STAT("Weapon: ", weapon->toString())
else
PRINT_STAT("Weapon: ", "Not equiped")
#undef PRINT_STAT
if(inv_height < 16)
h_start = inv_height - 1;
else
h_start = h_start + inv_height - 2;
//Last line ╚══Drop(x)══Use(u)═══╝
int cnt = 0;
for (int j = w_start; j < w_start + inv_width; j++) {
if(j == w_start)
buffer[h_start][j] = '+';
else if(j == w_start + inv_width - 1)
buffer[h_start][j] = '+';
else
buffer[h_start][j] = '-';
}
return;
}
int Player::addToInventory(std::shared_ptr<Item> item) {
return inventory.addToInventory(item);
}
</code></pre>
<p>Player.h</p>
<pre><code>#pragma once
#include <sstream>
#include "Entity.h"
#include "Map.h"
class Player : public Entity
{
public:
Player(){
name = "Player";
health = 100;
defense = 10;
attack = 20;
inventory.setLimit(5);
}
void drawInventory(BUFFER &buffer){
inventory.drawInventory(buffer);
}
void changeInventorySelection(BUFFER &buffer, int p){
inventory.changeInventorySelection(p, buffer);
return;
}
void dropFromInventory(){
inventory.dropFromInventory();
}
void useSelectedItemFromInventory();
void drawCharacterStats(BUFFER &buffer);
int addToInventory(std::shared_ptr<Item> item);
static std::vector<std::string> shape;
};
</code></pre>
<p>View.cpp</p>
<pre><code>#include "View.h"
void View::drawFightScreen(std::shared_ptr<Monster> monster, int& p_hp_x_coord, int& m_hp_x_coord, int& hp_y_coord) {
//Draw border and fill with blanks
for (int i = 0; i < height; i++) {
buffer[i][0] = '|';
buffer[i][width - 1] = '|';
for(int j = 1; j < width - 1; j++)
buffer[i][j] = ' ';
}
//Draw border
for (int j = 0; j < width; j++) {
buffer[0][j] = '=';
buffer[height - 1][j] = '=';
}
int
spacing = 2,
h_start = 2,
left_width_start = width - 30;
//Draw player shape and stats
for(int i = 0; i < Player::shape.size() && h_start < height-1; i++, h_start++) {
printMessage(spacing, h_start, Player::shape[i]);
}
if(h_start + 4 >= height) {
spacing = 30;
h_start = 2;
}
printMessage(spacing, h_start++, "========================");
printMessage(spacing, h_start++, "Attack " + std::to_string(shrdPlayer->getAttack()));
printMessage(spacing, h_start++, "Defense " + std::to_string(shrdPlayer->getDefense()));
p_hp_x_coord = spacing;
hp_y_coord = h_start;
printMessage(spacing, h_start++, "Health " + std::to_string(shrdPlayer->getHealth()));
creature_t shape = monster->getShape();
h_start = 2;
//Draw monster shape and stats
for(int i = 0; i < shape.size() && h_start < height - 1; i++) {
printMessage(left_width_start, h_start, shape[i]);
h_start++;
}
if(h_start + 4 >= height) {
left_width_start -= 30;
h_start = 2;
}
printMessage(left_width_start, h_start++, "========================");
printMessage(left_width_start, h_start++, "Attack " + std::to_string(monster->getAttack()));
printMessage(left_width_start, h_start++, "Defense " + std::to_string(monster->getDefense()));
m_hp_x_coord = left_width_start;
printMessage(left_width_start, h_start++, "Health " + std::to_string(monster->getHealth()));
drawMap();
return;
}
void View::printMessage(int x, int y, std::string s) {
for(int i = 0; i < s.length() && i < buffer[y].size(); i++)
buffer[y][x+i] = s[i];
return;
}
int View::initiateFight(std::shared_ptr<Monster> m) {
//Fight takes turns. Firstly player attacks the monster
//then the monster fights back. This cycle is repeated
//until one of the contestans dies.
bool
alive_p = true,
alive_m = true;
int
p_hp_x = 0,
hp_y = 0,
m_hp_x = 0;
drawFightScreen(m, p_hp_x, m_hp_x, hp_y);
float
p_att = shrdPlayer->getAttack(),
p_def = shrdPlayer->getDefense(),
m_att = m->getAttack(),
m_def = m->getDefense();
nodelay(stdscr, FALSE);
while (alive_p && alive_m) {
float dmg = p_att * ( p_att / (p_att + m_def));
if(dmg <= 0) dmg = 1;
alive_m = m->reduceHealth(dmg);
printMessage(m_hp_x, hp_y, "Health " + std::to_string(m->getHealth()) + " ");
drawMap();
if(!alive_m)
break;
dmg = m_att * ( m_att / ( m_att + p_def));
if(dmg <= 0) dmg = 1;
alive_p = shrdPlayer->reduceHealth(dmg);
printMessage(p_hp_x, hp_y, "Health " + std::to_string(shrdPlayer->getHealth()) + " ");
drawMap();
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
printMessage(center_x - 12, height - 2, "Press any key to continue");
drawMap();
getch();
nodelay(stdscr, TRUE);
return (alive_p) ? 0 : 1;
}
int View::checkFieldAndPerfAction(){
data_t c = buffer[center_y][center_x];
switch(hash(c))
{
case MONSTER: {
std::shared_ptr<Monster> monster = Monster::generateMonster();
if(initiateFight(monster)) {
//Player has died
printMessage(center_x, center_y, "You have DIED!");
drawMap();
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
return -1;
} else {
//std::this_thread::sleep_for(std::chrono::milliseconds(3000));
shrdMap->updateMap(x_cord, y_cord, L".");
//We need to drop the items that monster had
int x = x_cord,
y = y_cord,
w, a, c;
monster->itemsInInventory(w, a, c);
for(int i = 0; i < w; i++)
shrdMap->updateMap(x - i, y, L"W");
y++;
for(int i = 0; i < a; i++)
shrdMap->updateMap(x - i, y, L"A");
y++;
for(int i = 0; i < c; i++)
shrdMap->updateMap(x - i, y, L"H");
shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);
}
break;
}
case POTION: {
std::shared_ptr<Consumable> cons = Consumable::generateConsumable();
if( shrdPlayer->addToInventory(std::static_pointer_cast<Item>(cons)) >= 0)
shrdMap->updateMap(x_cord, y_cord, L" "); //If Item was consumed we need to update the main map here.
break;
}
case ARMOR: {
std::shared_ptr<Armor> armor = Armor::generateArmor();
if( shrdPlayer->addToInventory(std::static_pointer_cast<Item>(armor)) >= 0)
shrdMap->updateMap(x_cord, y_cord, L" "); //If Item was consumed we need to update the main map here.
break;
}
case WEAPON: {
std::shared_ptr<Weapon> weapon = Weapon::generateWeapon();
if( shrdPlayer->addToInventory(std::static_pointer_cast<Item>(weapon)) >= 0)
shrdMap->updateMap(x_cord, y_cord, L" "); //If Item was consumed we need to update the main map here.
break;
}
case WALL: {
y_cord = prev_y;
x_cord = prev_x;
shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);
break;
}
}
return 0;
}
int View::gameLogic(gcode &code) {
switch(code)
{
case gcode::DF_KEY_INVENTORY: {
if(!inv_open) {
inv_open = true;
stats_open = false;
shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);
shrdPlayer->drawInventory(buffer);
} else {
//Closing the inventory
inv_open = false;
shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);
buffer[center_y][center_x] = 'P';
}
break;
}
case gcode::DF_KEY_DROP: {
if(inv_open){
shrdPlayer->dropFromInventory();
shrdPlayer->drawInventory(buffer);
}
break;
}
case gcode::DF_KEY_USE: {
if(inv_open) {
shrdPlayer->useSelectedItemFromInventory();
shrdPlayer->drawInventory(buffer);
}
break;
}
case gcode::DF_KEY_STATS: {
if(!stats_open) {
stats_open = true;
inv_open = false;
shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);
shrdPlayer->drawCharacterStats(buffer);
} else {
stats_open = false;
shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);
buffer[center_y][center_x] = 'P';
}
break;
}
case gcode::DF_KEY_UP: {
if(inv_open && !stats_open){
shrdPlayer->changeInventorySelection(buffer, -1);
y_cord = prev_y; //Forbid moving while inventory is open
} else if (stats_open) {
y_cord = prev_y;
} else {
y_cord--;
if (y_cord < BORDER)
y_cord = BORDER;
shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);
if(checkFieldAndPerfAction() < 0)
return -1;
buffer[center_y][center_x] = 'P';
prev_y = y_cord;
}
break;
}
case gcode::DF_KEY_DOWN: {
if(inv_open && !stats_open){
shrdPlayer->changeInventorySelection(buffer, 1);
y_cord = prev_y; //Forbid moving while inventory is open
} else if(stats_open) {
y_cord = prev_y;
} else {
y_cord++;
if(y_cord > limit_y)
y_cord = limit_y;
shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);
if(checkFieldAndPerfAction() < 0)
return -1;
buffer[center_y][center_x] = 'P';
prev_y = y_cord;
}
break;
}
case gcode::DF_KEY_LEFT: {
if(inv_open || stats_open){
x_cord = prev_x;
} else {
x_cord--;
if(x_cord < BORDER)
x_cord = BORDER;
shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);
if(checkFieldAndPerfAction() < 0)
return -1;
buffer[center_y][center_x] = 'P';
prev_x = x_cord;
}
break;
}
case gcode::DF_KEY_RIGHT: {
if(inv_open || stats_open){
x_cord = prev_x;
} else {
x_cord++;
if(x_cord > limit_x)
x_cord = limit_x;
shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);
if(checkFieldAndPerfAction() < 0)
return -1;
buffer[center_y][center_x] = 'P';
prev_x = x_cord;
}
break;
}
}
shrdMap->draw_map(buffer); //Its not neccessary to redraw everytime
code = gcode::DF_KEY_NONE;
std::this_thread::sleep_for(std::chrono::milliseconds(30));
return 0;
}
int View::init() {
buffer.reserve(height);
VSBUFF dd(width);
for(int i = 0; i < height; i++)
buffer.push_back(dd);
for(int i = 0; i < height; i++)
for(int j = 0; j < width; j++)
buffer[i][j] = ' ';
std::string buf = "Use WASD or Arrow Keys to move around the map.";
std::string buf2 = "M represents a Monster and will initiate a fight";
std::string buf3 = "W is a Weapon pickup";
std::string buf4 = "A is a Armor pickup";
std::string buf5 = "H is a Health potion";
std::string buf6 = "Use I to open the inventory";
std::string buf7 = "Use C to display player stats";
std::string buf8 = "Use a move key to start the game!";
erase();
move(2, 10); addstr(buf.c_str());
move(3, 10); addstr(buf2.c_str());
move(4, 10); addstr(buf3.c_str());
move(5, 10); addstr(buf4.c_str());
move(6, 10); addstr(buf5.c_str());
move(7, 10); addstr(buf6.c_str());
move(8, 10); addstr(buf7.c_str());
move(9, 10); addstr(buf8.c_str());
refresh();
//drawMap();
shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);
return 0;
}
int View::drawMap()
{
std::wstring buf;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
data_t c = buffer[i][j];
buf.append(c);
}
}
erase();
move(0,0);
addwstr(buf.c_str());
refresh();
return 0;
}
</code></pre>
<p>View.h</p>
<pre><code>#pragma once
#include <vector>
#include "Player.h"
#include "Map.h"
#include "Consumable.h"
#include "Armor.h"
#include "Weapon.h"
#include "Monster.h"
#include <curses.h>
enum fields
{
MONSTER,
POTION,
ARMOR,
WEAPON,
WALL,
NONE
};
enum class gcode
{
DF_KEY_NONE = -1,
DF_KEY_INVENTORY = 0,
DF_KEY_MENU = 1,
DF_KEY_DROP = 2,
DF_KEY_LEFT = 3,
DF_KEY_RIGHT = 4,
DF_KEY_UP = 5,
DF_KEY_DOWN = 6,
DF_KEY_USE = 7,
DF_KEY_STATS = 8
};
class View {
private:
int
width,
height,
x_cord,
y_cord,
prev_x,
prev_y,
center_x,
center_y,
limit_x,
limit_y;
bool
inv_open,
stats_open;
BUFFER buffer;
std::shared_ptr<Player> shrdPlayer;
std::shared_ptr<Map> shrdMap;
int drawMap();
int checkFieldAndPerfAction();
int initiateFight(std::shared_ptr<Monster> monster);
void printMessage(int x, int y, std::string s);
void drawFightScreen(std::shared_ptr<Monster> monster, int& p_hp_x_coord, int& m_hp_x_coord, int& hp_y_coord);
fields hash(data_t in) {
if(in == L"M") return MONSTER;
if(in == L"W") return WEAPON;
if(in == L"A") return ARMOR;
if(in == L"H") return POTION;
if(in == L"~") return WALL;
return NONE;
}
public:
View(int w, int h,
std::shared_ptr<Map> m,
std::shared_ptr<Player> p): width(w), height(h), shrdMap(m), shrdPlayer(p)
{
x_cord = BORDER + m->getWidth() / 2;
y_cord = BORDER + m->getHeight() / 2;
prev_x = x_cord;
prev_y = y_cord;
center_x = width / 2;
center_y = height / 2;
limit_x = BORDER + m->getWidth() - 1;
limit_y = BORDER + m->getHeight() - 1;
inv_open = false;
stats_open = false;
}
~View(){}
int gameLogic(gcode &code);
int init();
};
</code></pre>
<p>Weapon.cpp</p>
<pre><code>#include "Weapon.h"
std::vector<std::string> Weapon::weapon_names = {
"Tyrhung",
"Tranquility",
"King's Legacy",
"Firestorm Sword",
"Corrupted Blade",
"Cataclysm",
"Worldslayer",
"Espada",
"Windsong Protector",
"Spectral Sword",
"Armageddon",
"Severance"
};
std::shared_ptr<Weapon> Weapon::generateWeapon() {
unsigned seed = time(0);
srand(seed);
int att = rand() % 120;
int idx = rand() % weapon_names.size();
std::shared_ptr<Weapon> weapon(new Weapon(weapon_names[idx], att));
return weapon;
}
</code></pre>
<p>Weapon.h</p>
<pre><code>#pragma once
#include "Item.h"
#include <vector>
#include <memory>
class Weapon : public Item
{
private:
int damage;
public:
static std::vector<std::string> weapon_names;
Weapon(std::string _name, int dmg) : damage(dmg) {
type = item_type::ITEM_TYPE_WEAPON ;
name = _name;
}
~Weapon() {}
int get_damage() { return damage; }
std::string toString(){
std::string res = "[W] " + name + " (+" + std::to_string(damage) + " Att)";
return res;
}
static std::shared_ptr<Weapon> generateWeapon();
};
</code></pre>
<p>Can a switch statement be replaced with something more efficient?
What are your thoughts about the architecture of the game?</p>
<p>Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:10:17.393",
"Id": "502418",
"Score": "0",
"body": "This is a lot of code to peruse: Please provide a \"road map\" if not a *travel guide*: Why would someone with an interest in *how to code games in C++ well* want to read your code? Are there areas that worked out remarkably well? Parts you are not quite comfortable with? (Re) Visit [How to get the best value out of Code Review When Asking](https://codereview.meta.stackexchange.com/questions/2436/how-to-get-the-best-value-out-of-code-review-asking-questions/2438#2438) for ideas."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:38:16.370",
"Id": "502422",
"Score": "0",
"body": "Well I am not sure about how to achieve that. Maybe simple solution would be to read some book about game development. Thanks for reading my post!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T22:49:38.387",
"Id": "502477",
"Score": "3",
"body": "I’m happy to review this, but… just a warning… it’s going to a take a *long* time because there’s so much code. I prefer to do *really* detailed reviews, class-by-class, line-by-line, plus an overall design review of patterns and general ideas. If all that sounds good, and you’re willing to wait a week or so, then yup, I’ll be happy to review this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T05:58:47.220",
"Id": "502492",
"Score": "0",
"body": "@indi If it wouldn't be a problem for You because I am ready to learn!"
}
] |
[
{
"body": "<p>Here are a number of things to help you improve your code.</p>\n<h2>Write member initializers in declaration order</h2>\n<p>The <code>View</code> class has this constructor:</p>\n<pre><code>View(int w, int h, \n std::shared_ptr<Map> m, \n std::shared_ptr<Player> p): width(w), height(h), shrdMap(m), shrdPlayer(p) \n{ /* ... */ }\n</code></pre>\n<p>That looks fine, but in fact, <code>shrdPlayer</code> will be initialized <em>before</em> <code>shrdMap</code> because members are always initialized in <em>declaration</em> order and <code>shrdPlayer</code> is declared before <code>shrdMap</code> in this class. To avoid misleading another programmer, you should swap the order of declaration of those two class members.</p>\n<h2>Be careful with signed and unsigned</h2>\n<p>In many cases, the code compares an <code>int</code> <code>i</code> with an unsigned <code>size_t</code> <code>size</code>. It would be better to declare <code>i</code> to also be <code>size_t</code>.</p>\n<h2>Use include guards</h2>\n<p>There should be an include guard in each <code>.h</code> file. That is, start the file with:</p>\n<pre><code>#ifndef VIEW_H\n#define VIEW_H\n// file contents go here\n#endif // VIEW_H\n</code></pre>\n<p>The use of <code>#pragma once</code> is a common extension, but it's not in the standard and thus represents at least a potential portability problem. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">SF.8</a></p>\n<h2>Don't define an empty destructor</h2>\n<p>The current <code>~View</code> is empty. Better would be to simply omit it. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-dtor\" rel=\"nofollow noreferrer\">C.30</a>.</p>\n<h2>Don't write getters and setters for every class</h2>\n<p>C++ isn't Java and writing getter and setter functions for every C++ class is not good style. For instance, although <code>type</code> is a <code>protected</code> data member of <code>Item</code>, anything is allowed to either <code>setType()</code> or <code>getType()</code> rendering any protection meaningless. Better would be to simply declare it <code>public</code> or to eliminate <code>setType()</code> which is never used. If you do keep <code>getType</code>, make it a <code>const</code> function. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rh-get\" rel=\"nofollow noreferrer\">C.131</a></p>\n<h2>Don't reseed the random number generator more than once</h2>\n<p>The program currently calls <code>srand</code> in many places in the code. This is really neither necessary nor advisable. Instead, just call it once when the program begins and then continue to use <code>rand()</code> to get random numbers. Better yet, see the next suggestion.</p>\n<h2>Consider using a better random number generator</h2>\n<p>Since you are using a compiler that supports at least C++11, consider using a better random number generator. In particular, instead of <code>rand</code>, you might want to look at <a href=\"http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"nofollow noreferrer\"><code>std::uniform_int_distribution</code></a> and friends in the <code><random></code> header.</p>\n<h2>Use <code>const</code> where practical</h2>\n<p>Many of the small helper functions return a value but don't alter the underlying object. These should be <code>const</code>:</p>\n<pre><code>int getAttack() const { return attack; }\nint getDefense() const { return defense; }\n</code></pre>\n<h2>Separate test code</h2>\n<p>There are a number of things such as <code>testFillInventory</code> which are clearly intended solely for testing. It's a great idea to write tests, but the better strategy is to separate the test code from the main code.</p>\n<h2>Don't define a default constructor that only initializes data members</h2>\n<p>Instead of this:</p>\n<pre><code>Entity::Entity()\n{\n name = "";\n health = 100;\n armor = nullptr;\n weapon = nullptr;\n attack = 10;\n defense = 0;\n inventory.setLimit(3);\n}\n</code></pre>\n<p>Better would be to use in-class member initializers. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-default\" rel=\"nofollow noreferrer\">C.45</a></p>\n<h2>Provide rational constructors for base classes</h2>\n<p>In a similar vein to the above, the <code>Player</code> constructor is currently this:</p>\n<pre><code>Player(){\n name = "Player";\n health = 100;\n defense = 10;\n attack = 20;\n\n inventory{5};\n}\n</code></pre>\n<p>Instead, I'd suggest creating a constructor like this:</p>\n<pre><code>Entity::Entity(std::string name, int defense, int attack, int inv_limit)\n : name{name}\n , defense{defense}\n , attack{attack}\n , inventory{inv_limit}\n{}\n</code></pre>\n<p>Now the <code>Player</code> constructor could be this:</p>\n<pre><code>Player()\n : Entity{"Player", 10, 20, 5}\n{}\n</code></pre>\n<p>And the <code>Monster</code> constructor is this:</p>\n<pre><code>Monster(std::string _n, int att, int def) \n : Entity{_n, def, att, 3}\n , shape{creatures[rand() % 3]}\n{}\n</code></pre>\n<h2>Reconsider the use of pointers</h2>\n<p>The use of <code>std::shared_ptr<></code> is better than using raw pointers, but in this case, it seems more likely that <code>std::unique_ptr<></code> is a better choice. There is only one owner for a <code>Weapon</code> or <code>Armor</code> object and when the player picks one up, it transfers ownership of that object. For that reason, I'd suggest rewriting <code>addToInventory</code> like this:</p>\n<pre><code> int Inventory::addToInventory(std::unique_ptr<Item> &&item) {\n if(inventory.size() >= limit)\n return -1;\n inventory.push_back(std::move(item));\n return 0;\n }\n</code></pre>\n<p>Note that we're using move semantics because we're not duplicating the <code>item</code> but simply moving it to a new owner.</p>\n<h2>Don't reinvent polymorphism</h2>\n<p>Whenever you find yourself writing code like this:</p>\n<pre><code> int Entity::equipOrConsume(std::shared_ptr<Item> i)\n {\n switch (i->getType()) {\n case item_type::ITEM_TYPE_ARMOR:\n {\n std::shared_ptr<Armor> a_armor = std::dynamic_pointer_cast<Armor>(i);\n</code></pre>\n<p>stop and reconsider your design. We want to do a different thing if we're passed <code>Armor</code> or <code>Consumable</code>. A better way to do that is to use <a href=\"https://en.cppreference.com/w/cpp/language/dynamic_cast\" rel=\"nofollow noreferrer\"><code>dynamic_cast</code></a> which will check at runtime whether casting to a derived object is possible. So for example,</p>\n<pre><code> int Entity::equipOrConsume(std::unique_ptr<Item> &&i)\n {\n auto old{std::move(i)};\n if (Weapon* new_weapon = dynamic_cast<Weapon*>(old.get())) {\n old.release();\n if (weapon) {\n attack -= weapon->get_damage();\n }\n weapon.reset(new_weapon);\n std::cerr << "Using weapon " << weapon->toString() << '\\n';\n attack += weapon->get_damage();\n }\n else if (Consumable* new_consumable = dynamic_cast<Consumable*>(old.get())) {\n health += new_consumable->get_amount();\n if (health > 100)\n health = 100;\n std::cerr << "Using potion " << new_consumable->toString() << '\\n';\n old.reset();\n }\n else if (Armor* new_armor = dynamic_cast<Armor*>(old.get())) {\n old.release();\n if (armor)\n defense -= armor->get_defense();\n armor.reset(new_armor);\n std::cerr << "Using armor " << armor->toString() << '\\n';\n defense += armor->get_defense();\n }\n return 0;\n }\n</code></pre>\n<h2>Reconsider naming of <code>enum class</code> items</h2>\n<p>Because the <code>enum class</code> requires naming the class for each use, I would suggest that rather than <code>item_type::ITEM_TYPE_ARMOR</code> it is just as descriptive to write <code>item_type::ARMOR</code>.</p>\n<h2>Eliminate spurious semicolons</h2>\n<p>In lines like this within <code>Entity.cpp</code></p>\n<pre><code> ~Consumable() {};\n</code></pre>\n<p>the trailing semicolon is not needed.</p>\n<h2>Reconsider class members</h2>\n<p>Instead of <code>item_type</code> being a field, it seems to me that it would make more sense for the <code>getType()</code> class to be pure virtual in the base class and then have an override for each derived type, like this:</p>\n<pre><code> item_type getType() const override { return item_type::POTION; }\n</code></pre>\n<h2>Know your library</h2>\n<p>There are a number of lines that look like this:</p>\n<pre><code> std::string buf3 = "W is a Weapon pickup";\n std::string buf4 = "A is a Armor pickup";\n // etc.\n erase();\n move(4, 10); addstr(buf3.c_str());\n move(5, 10); addstr(buf4.c_str());\n</code></pre>\n<p>That's not at all necessary. Instead use <code>mvaddstr</code> like this:</p>\n<pre><code> mvaddstr(4, 10, "W is a Weapon pickup");\n mvaddstr(5, 10, "A is a Armor pickup");\n</code></pre>\n<h2>Use appropriate data types</h2>\n<p>At the moment, the code has these definitions:</p>\n<pre><code>typedef std::wstring data_t;\ntypedef std::vector<data_t> VSBUFF;\ntypedef std::vector<VSBUFF> BUFFER;\n</code></pre>\n<p>This is almost certainly not what you really want. The smallest unit here should be a <code>wchar_t</code>, not a <code>std::wstring</code>. If you instead define these like so:</p>\n<pre><code>typedef wchar_t data_t;\ntypedef std::wstring VSBUFF;\ntypedef std::vector<VSBUFF> BUFFER;\n</code></pre>\n<p>You will find that a great many things become much easier. For example, the <code>View::init</code>, using the suggestion above as well, becomes as simple as this:</p>\n<pre><code>void View::init() {\n buffer.reserve(height);\n VSBUFF dd(width, ' ');\n for(int i = 0; i < height; i++)\n buffer.push_back(VSBUFF{width, ' '});\n\n erase();\n mvaddstr(2, 10, "Use WASD or Arrow Keys to move around the map.");\n mvaddstr(3, 10, "M represents a Monster and will initiate a fight");\n mvaddstr(4, 10, "W is a Weapon pickup");\n mvaddstr(5, 10, "A is a Armor pickup");\n mvaddstr(6, 10, "H is a Health potion");\n mvaddstr(7, 10, "Use I to open the inventory");\n mvaddstr(8, 10, "Use C to display player stats");\n mvaddstr(9, 10, "Use a move key to start the game!");\n refresh();\n\n shrdMap->getMapAroundPlayer(x_cord, y_cord, center_x, center_y, buffer);\n}\n</code></pre>\n<h2>Clean up on exit</h2>\n<p>The <code>curses</code> library requires you to call <code>endwin</code> when the program ends. The simplest way to do that is to use the <code>atexit()</code> function:</p>\n<pre><code> void finish() {\n endwin();\n }\n</code></pre>\n<p>Then within <code>main</code>:</p>\n<pre><code> initscr();\n atexit(finish);\n</code></pre>\n<h2>Catch errors by reference</h2>\n<p>The code includes a few lines like this:</p>\n<pre><code>catch (bpt::json_parser::json_parser_error) {\n</code></pre>\n<p>This has the effect of catching the error by value and then throwing it away.</p>\n<h2>Avoid using function-like macros</h2>\n<p>The <code>PRINT_STAT</code> macro is not a good idea. It's prone to error and is not very efficient. I would suggest that if the entire function is rewritten, the need for it goes away anyway. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Res-macros2\" rel=\"nofollow noreferrer\">ES.31</a> for details.</p>\n<h2>Think of the user</h2>\n<p>Other than dying, there's no way for the user to end the program gracefully. Think of adding an exit key sequence. Also, adding color would greatly enhance the play of the game.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T05:50:20.720",
"Id": "502490",
"Score": "1",
"body": "Thank You very much!!! Great insights! One question, is this line really needed: auto old{std::move(i)};?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T06:36:24.153",
"Id": "502493",
"Score": "1",
"body": "No, that line isn't needed. One can simply use `i` where `old` is referenced in that function."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T23:22:07.343",
"Id": "254767",
"ParentId": "254731",
"Score": "6"
}
},
{
"body": "<h1>Terminology</h1>\n<p>I would not call your game a clone of Dwarf Fortress, for that it is way too simple, and the only similarity I see is that you have an overworld map rendered using ASCII characters. It would be more honest to just call it a <a href=\"https://en.wikipedia.org/wiki/Roguelike\" rel=\"nofollow noreferrer\">roguelike</a>, unless of course you really plan to turn this into a highly detailed world simulation with a colony of dwarves living in it.</p>\n<p>You have a class <code>Entity</code>, which can be either a <code>Player</code> or a <code>Monster</code>. However, the word "entity" is often used in game engines to mean any kind of object, or even non-objects like light or sound sources. It might be better to rename your <code>Entity</code> to <code>Character</code>, as you have "player characters" (you) and "non-player characters" (monsters and allies).</p>\n<h1>Be consistent when naming things</h1>\n<p>Choose whether to use <code>snake_case</code> or <code>camelCase</code> for function names, and stick to it. I see both ways used, for example <code>Armor::get_defense()</code> vs <code>Entity::getHealth()</code>.</p>\n<p>Also avoid very short names like <code>m</code>. Is it a <code>Monster</code> or a <code>Map</code>? Only use single-character variable names for things like loop counters (<code>i</code>, <code>j</code>), coordinates (<code>x</code>, <code>y</code>, <code>z</code>) and perhaps width/heights (<code>w</code>, <code>h</code>).</p>\n<h1>Prefer using <code>std::make_shared<>()</code></h1>\n<p>Avoid calling <code>new</code> manually. If you need to create a <code>std::shared_ptr</code> of some object, use <a href=\"https://en.cppreference.com/w/cpp/memory/shared_ptr/make_shared\" rel=\"nofollow noreferrer\"><code>std::make_shared<>()</code></a> to create it, like so:</p>\n<pre><code>std::shared_ptr<Armor> Armor::generateArmor() {\n ...\n return std::make_shared<Armor>(armor_names[idx], def);\n}\n</code></pre>\n<h1>Use proper random number generators</h1>\n<p>Don't use <code>srand()</code> and <code>rand()</code>, those are old C functions that are quite bad random number generators. Furthermore, using the modulo operator will not give you correctly distributed random numbers.\nThe proper way to generate random numbers in C++ is to use define a <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\">random engine</a> that provides randomness, seed it using a <a href=\"https://en.cppreference.com/w/cpp/numeric/random/random_device\" rel=\"nofollow noreferrer\"><code>std::random_device</code></a>, and then use a class like <a href=\"https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"nofollow noreferrer\"><code>std::uniform_int_distribution</code></a> to generate properly distributed numbers within a given range. Make sure the random engine is declared only once as it is rather expensive to construct, but it is normally fine to create a throw-away distribution. So:</p>\n<pre><code>static std::random_device random_device;\nstatic std::default_random_engine random_engine(random_device());\n\nstd::shared_ptr<Armor> Armor::generateArmor() {\n std::uniform_int_distribution def_distrib(0, 200);\n std::uniform_int_distribution idx_distrib(0, armor_names.size());\n int def = def_distrib(random_engine);\n int idx = idx_distrib(random_engine);\n return std::make_shared<Armor>(armor_names[idx], def);\n}\n</code></pre>\n<h1>Move <code>armor_names</code> out of <code>class Armor</code></h1>\n<p>The vector of strings <code>armor_names</code> doesn't look like it should be accessible by other objects, it's just a list of names used by <code>generateArmor()</code> internally. So you could make it <code>private</code>, but I would just remove it completely from <code>class Armor</code>, and instead just declare it only in <code>Armor.cpp</code>, like so:</p>\n<pre><code>static std::vector<std::string> armor_names = {\n ...\n};\n</code></pre>\n<h1>Avoid writing empty constructors and destructors</h1>\n<p>I see various empty destructors, like:</p>\n<pre><code>class Consumable: public Item {\n ...\n ~Consumable() {};\n ...\n};\n</code></pre>\n<p>But even empty constructors:</p>\n<pre><code>class Item {\n ...\n Item() {};\n ...\n};\n</code></pre>\n<p>This is not useful, and you should remove them. Sometimes you have multiple overloads for the constructor, and you want to keep the one without parameters, in that case you can tell the compiler to bring back the <a href=\"https://en.cppreference.com/w/cpp/language/default_constructor\" rel=\"nofollow noreferrer\">default constructor</a> like so:</p>\n<pre><code> Item() = default;\n</code></pre>\n<h1>Preferable way to initialize member variables</h1>\n<p>Initializing member variables inside the body of the constructor is something that you should avoid. It can be less efficient than using a <a href=\"https://en.cppreference.com/w/cpp/language/data_members#Member_initialization\" rel=\"nofollow noreferrer\">member initializer list or default member initializers</a>, and it might also be problematic if exceptions can be thrown while constructing an object. So prefer default member initializers (to avoid having to repeat yourself when you have multiple constructors for a class), then member initializer lists, and only initialize in the body if the other two methods are not possible.</p>\n<p>If you have derived classes that need to initialize members of the base class, the best way would be to provide a constructor for the base class that allows that to be done. For example:</p>\n<pre><code>class Entity {\n std::string name;\n\n std::shared_ptr<Armor> armor;\n std::shared_ptr<Weapon> weapon;\n\n int health{100};\n int attack{10};\n int defense{0};\n\n Inventory inventory{3};\n\npublic:\n Entity() = default;\n Entity(const std::string &name, ...): name(name), ... {}\n ...\n};\n\nclass Player: public Entity {\n Player(): Entity("Player", ...) {}\n ...\n};\n</code></pre>\n<h1>Avoid unnecessary <code>std::shared_ptr</code>s</h1>\n<p>You make everything a <code>std::shared_ptr</code>, but this is often not necessary. Shared pointers should be used when ownership of an object has to be shared, but if there is a unique owner then you don't need it, and a <code>std::shared_ptr</code> would then only add unnecessary overhead.</p>\n<p>For example, you only generate a <code>Monster</code> in <code>checkFieldAndPerfAction()</code>, and after the fight the monster is gone. So you could have just declared <code>monster</code> as a regular variable:</p>\n<pre><code>case MONSTER: {\n Monster monster = ...;\n if (initiateFight(monster)) {\n ...\n</code></pre>\n<p>Of course this will require other changes: <code>Monster::generateMonster()</code> should return a <code>Monster</code> by value, <code>View::initiateFight()</code> should take a reference to a <code>Monster</code>, and so on.</p>\n<p>It also looks like <code>class View</code> "owns" most things, like the player and the map, so those don't have to be held by <code>std::shared_ptr</code>s either. It's likely that you don't need any <code>std::shared_ptr</code>s at all.</p>\n<h1>Avoid macros</h1>\n<p>In C++ you almost never need to use macros. For example, <code>PRINT_STAT()</code> can be replaced by a lambda function:</p>\n<pre><code>auto print_stat = [](const auto &description, const auto &var){\n std::stringstream ss;\n ss << description << var;\n ...\n};\n\nprint_stat("Health: ", health);\n...\n</code></pre>\n<h1>Use raw string literals for the ASCII art</h1>\n<p>C++11 introduced raw <a href=\"https://en.cppreference.com/w/cpp/language/string_literal\" rel=\"nofollow noreferrer\">string literals</a> that make it much nicer to write (long) strings that contain characters that you would normally have to escape. For example:</p>\n<pre><code>creature_t Monster::centaur = {\nR"( <=======]}======)",\nR"( --. /| )",\nR"( _"/_.'/ )",\nR"( .'._._,.' )",\nR"( :/ \\{}/ )",\nR"((L /--',----._ )",\nR"( | \\\\ )",\nR"( : /-\\ .'-'\\ / |)",\nR"( \\\\, || \\| )",\nR"( \\/ || || )"\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T05:57:23.680",
"Id": "502491",
"Score": "0",
"body": "Thanks for great insights! I wasn't aware of the raw string literals and I tend to mix snake_case and camelCase because i work with some libraries that use both."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T23:22:23.823",
"Id": "254768",
"ParentId": "254731",
"Score": "4"
}
},
{
"body": "<p>You’ve got some exceptional answers to this question; they’re so good there’s no point to me repeating all the stuff they cover. So I won’t be doing a code review. I’ll just focus on some high-level design review issues.</p>\n<h1>Avoiding dynamic allocation (especially strings!)</h1>\n<p><code>Armor.cpp</code> has this:</p>\n<pre><code>std::vector<std::string> Armor::armor_names = { \n "Edge of Patience", \n "Defense of Twilight",\n "Armor of Absorption",\n "Armor of Dominance",\n "Adamantite Cuirass",\n "Golden Armor",\n "Armor of Illusions",\n "Chestplate of Soul",\n "Mail Chestplate",\n "Vengeful Adamantite",\n "Tunic of Fury",\n "Protector of Souls",\n "Chestguard of Time"\n };\n</code></pre>\n<p>Now, as G. Sliepen mentioned, this shouldn’t really be a static data member of the <code>Armour</code> class; it should be in an anonymous namespace in <code>Armor.cpp</code>.</p>\n<p>But more importantly from a performance perspective, consider what’s really happening here.</p>\n<ol>\n<li>All that character data is stored in the executable’s (possibly read-only) data section, and loaded into memory when the program starts.</li>\n<li>Space for (at least) 13 strings is dynamically allocated for the vector.</li>\n<li>Then 13 individual strings are allocated (assuming no small-string optimization, but those strings look too large for that anyway).</li>\n<li>Then the character data is copied from the data section into those 13 strings.</li>\n</ol>\n<p>Go back to step 1 there: all the data you actually need is already right there in memory when the program starts. All that dynamic allocation just to eventually <em>copy</em> that data into newly-allocated strings seems… a little wasteful. Couldn’t we just use the character data already there in memory?</p>\n<p>Indeed we can, by doing something like this:</p>\n<pre><code>// in Armor.cpp:\n\nnamespace {\n\n// normally you should never do "using namespace ___;"\n//\n// but the literals namespaces are specially designed specifically for the\n// purpose of being used like that.\nusing namespace std::string_view_literals;\n\n// in c++20, you could use constinit instead of constexpr\nconstexpr auto armor_names = std::array{\n "Edge of Patience"sv, \n "Defense of Twilight"sv,\n "Armor of Absorption"sv,\n // etc....\n};\n\n} // anonymous namespace\n</code></pre>\n<p>Instead of constructing strings that dynamically allocate memory and copy constant character data into it, you can use <code>std::string_view</code>, which is only a lightweight reference to character data—internally, it’s basically just a pointer and a size. So <code>armor_names</code> just becomes an array of pointers to already-loaded character data… which means no allocation is done, and no copying.</p>\n<p>This idea applies to <em>all</em> data in your program that you want stored within the program’s data; not just string data. If it’s already going to be in memory, there’s no need to dynamically allocate new memory for it and copy it over.</p>\n<p>Obviously if you intend to load the armour names from configuration files, or if you intend to do localization, then you <em>do</em> need vectors and strings, but that’s not that big a deal. If you need ’em, you need ’em. This is just about avoiding wasteful allocation or copying that you <em>don’t</em> need.</p>\n<p>If you <em>just</em> make this change, nothing about the rest of your code needs to change. (Well, you might need to explicitly convert the armour name to a string in <code>generateArmor()</code>, but we’ll get back to that.) You can make pretty much identical changes in <code>Monster.cpp</code>, <code>Player.cpp</code>, and <code>Weapon.cpp</code>.</p>\n<p>Not bad, but can we do any better?</p>\n<p>Here’s a design question: Do armours actually <em>need</em> their own, personal copy of the armour name?</p>\n<p>This is based on a general design question you should always be asking about your classes. Objects should only be forced to truck around data that is unique to them. For example, imagine you made a <code>Human</code> class… would it make sense for that class to have a <code>int number_of_heads;</code> data member? It’s always going to be 1 (presumably). It’s a waste to have <em>every single instance</em> of a <code>Human</code> class keeping track of how many heads a human has. That should be a static data member, if at all.</p>\n<p>That example may sound silly, but this is actually a very deep and subtle idea. Consider a set of animal classes used to keep track of animals in groups:</p>\n<pre><code>class animal\n{\npublic:\n virtual ~animal() = default;\n\n virtual auto name() const -> std::string = 0;\n virtual auto type_plural() const -> std::string = 0;\n virtual auto grouping() const -> std::string = 0;\n};\n\nclass sheep : public animal\n{\n std::string _name;\n std::string _type_plural = "sheep";\n std::string _grouping = "flock";\n\npublic:\n explicit sheep(std::string name) : _name(std::move(name)) {}\n\n auto name() const -> std::string override { return _name; }\n auto type_plural() const -> std::string override { return _type_plural; }\n auto grouping() const -> std::string override { return _grouping; }\n};\n\nclass cow : public animal\n{\n std::string _name;\n std::string _type_plural = "cows";\n std::string _grouping = "herd";\n\npublic:\n explicit cow(std::string name) : _name(std::move(name)) {}\n\n auto name() const -> std::string override { return _name; }\n auto type_plural() const -> std::string override { return _type_plural; }\n auto grouping() const -> std::string override { return _grouping; }\n};\n\nauto animals = std::vector<std::unique_ptr<animal>>{};\n\nanimals.emplace_back(std::unique_ptr{new sheep{"Shaun"}};\n// and so on...\n\nfor (auto&& p_animal : animals)\n std::cout << p_animal->name() << " is part of a " << p_animal->grouping() << " of " << p_animal->type_plural() << '\\n';\n</code></pre>\n<p>Now, the <em>name</em> of each animal is going to be unique to the animal, so each object <em>has</em> to have a string data member to hold that name. <em>BUT!</em> The animal type and the grouping is going to be the same for all animals of the same type. The grouping is going to be "flock" for <em>ALL</em> sheep. So it doesn’t make sense for each sheep object to remember that individually.</p>\n<p>Instead you could do this:</p>\n<pre><code>class sheep : public animal\n{\n static std::string const _type_plural = "sheep";\n static std::string const _grouping = "flock";\n\n std::string _name;\n\npublic:\n explicit sheep(std::string name) : _name(std::move(name)) {}\n\n auto name() const -> std::string override { return _name; }\n auto type_plural() const -> std::string override { return _type_plural; }\n auto grouping() const -> std::string override { return _grouping; }\n};\n</code></pre>\n<p>Now each <code>sheep</code> object is <em>one third</em> the size of before. You’ve also eliminated a whole class of errors and bugs, where somehow the grouping string gets accidentally changed in some member function.</p>\n<p>So how does this apply to <code>Armor</code>? Well, consider this design:</p>\n<pre><code>// Item.hpp\n\n// Note that Item now has no data members at all. This is how it should be.\n// Abstract base classes should generally have no data members. And this\n// example actually illustrates why: by letting derived classes decide what\n// data members they need, you open up the possibility for optimizations.\nclass Item\n{\npublic:\n virtual ~Item() = default;\n\n virtual auto toString() const -> std::string = 0;\n};\n\n// Armor.hpp\n\nclass Armor : public Item\n{\n // If you want to be clever and save even more space, you can decide\n // that the max number of possible armour names is 128 or 255, and use\n // only a single byte to store the index. If you also use a single byte\n // for the DEF, then this whole class will be only 2 bytes large (well,\n // ignoring the vtable pointer).\n std::size_t _name_idx = 0;\n int _def = 0;\n\n Armor(std::size_t _name, int def) : _name_idx{_name}, _def{def} {}\n\npublic:\n static auto generateArmor(RandomEngine&) -> Armor;\n\n auto toString() const -> std::string override;\n\n auto get_defense() const noexcept -> int { return _def; }\n};\n\n// Armor.cpp\n\nnamespace {\n\nusing namespace std::string_view_literals;\n\nconstexpr auto armor_names = std::array{\n "Edge of Patience"sv, \n "Defense of Twilight"sv,\n "Armor of Absorption"sv,\n // etc....\n};\n\nauto name_dist = std::uniform_int_distribution<std::size_t>{0, armor_names.size() - 1};\n\nauto def_dist = std::uniform_int_distribution{0, 200};\n\n} // anonymous namespace\n\nauto Armor::generateArmor(RandomEngine& rng) -> Armor\n{\n auto name = name_dist(rng);\n auto def = def_dist(rng);\n\n return Armor{name, def};\n}\n\nauto Armor::toString() const -> std::string\n{\n return "[A] " + std::string{armor_names[_name_idx]} + " (+" + std::to_string(_def) + " def)";\n\n // OR, a much more efficient implementation:\n using namespace std::string_view_literals;\n\n constexpr auto s1 = "[A] "sv;\n constexpr auto s2 = " (+"sv;\n constexpr auto s3 = " def)"sv;\n\n auto buffer = std::array<char, number_of_chars_needed>{};\n auto const [p, _] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), _def);\n\n auto res = std::string{};\n res.reserve(s1.size() + armor_names[_name_idx].size() + s2.size()\n + (p - buffer.data()) + s3.size());\n\n res.append(s1);\n res.append(armor_names[_name_idx]);\n res.append(s2);\n res.append(buffer.data(), p);\n res.append(s3);\n\n return res;\n}\n</code></pre>\n<p>This makes the armour class several times smaller (possibly, if you optimize it aggressively enough, just a couple bytes!), and <em>MUCH</em> faster to pass around (because now you’re just copying an index, not a string).</p>\n<p>The same idea could be applied all over the code: <code>Consumable</code>, <code>Monster</code>, and <code>Weapon</code> at least.</p>\n<p>And once you’ve started down this road, you can start looking for other ways to avoid creating strings—especially temporary strings that just exist to be read and then thrown away immediately. For example, do you really need a <code>toString()</code> function for items at all? The only place I see it used is when rendering inventories or character stats. What if you did something like this instead:</p>\n<pre><code>class Item\n{\npublic:\n // for simplicity i'm limiting the description length, but there are ways\n // you could do this where you don't need this limit\n static constexpr auto max_description_length = std::size_t{63};\n\n virtual ~Item() = default;\n\n template <std::output_iterator O, std::sentinel_for<O> S>\n auto write_desciption_to(O out, S sen) const -> O\n {\n auto buffer = std::array<char, max_description_length + 1>{};\n\n auto const end = buffer.data() + buffer.size();\n auto p = do_write_description(buffer.data(), end);\n\n while (out != sen and p != end)\n *out++ = *p++;\n\n return out;\n }\n\nprotected:\n virtual auto do_write_desciption(char*, char*) const -> char* = 0;\n};\n\nclass Armor : public Item\n{\n // ... [snip] ...\n\nprotected:\n // you'd probably actually put this in the cpp file:\n auto do_write_desciption(char* first, char* last) const -> char* override\n {\n using namespace std::string_view_literals;\n\n constexpr auto s1 = "[A] "sv;\n constexpr auto s2 = " (+"sv;\n constexpr auto s3 = " def)"sv;\n\n auto buffer = std::array<char, number_of_chars_needed>{};\n auto const [p, _] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), _def);\n\n auto next = first;\n auto append = [&next, last](auto&& rng)\n {\n auto const range_length = std::ranges::size(rng);\n auto const remaining = last - next;\n\n auto const to_copy = std::min<std::size_t>(range_length, remaining);\n\n if (to_copy)\n next = std::copy_n(std::ranges::begin(rng), to_copy, next);\n };\n\n append(s1);\n append(armor_names[_name_idx]);\n append(s2);\n append(std::ranges::subrange(buffer.data(), p));\n append(s3);\n\n return next;\n }\n};\n</code></pre>\n<p>With that, in <code>Inventory.cpp</code>, instead of:</p>\n<pre><code>for (int i = h_start, inv_cnt = 0; i < h_start + inv_height - spacing, inv_cnt < inventory.size(); i++, inv_cnt++) {\n std::string desc = (inv_cnt == 0) ? "*" : " ";\n desc += inventory[inv_cnt]->toString();\n\n int start_offset = w_start + spacing;\n for (int j = start_offset, k = 0; j < w_start + inv_width - spacing && k < desc.length(); j++, k++) {\n buffer[i][j] = desc[k];\n }\n}\n</code></pre>\n<p>You could do:</p>\n<pre><code>// note: bugs left intact; just illustrating how the above is a drop-in replacement\nfor (int i = h_start, inv_cnt = 0; i < h_start + inv_height - spacing, inv_cnt < inventory.size(); i++, inv_cnt++) {\n int start_offset = w_start + spacing;\n\n buffer[i][start_offset++] = (inv_cnt == 0) ? "*" : " ";\n\n auto const first = buffer[i].data() + start_offset;\n auto const last = first + std::min(buffer[i].size(), /* do that dance to calculate remaining space here */);\n\n inventory[inv_cnt]->write_desciption_to(first, last);\n}\n</code></pre>\n<p>Copying the description directly into the output buffer saves you not one, but <em>two</em> unnecessary strings, with all the allocation and copying that goes along with them. Obviously doing these kinds of optimizations does make the code more complex—it’s so much easier to just copy strings around, right? But if you’re gunning for max speed and min memory usage, this is how you get there. Depending on the cost of allocations, printing the inventory as shown above could be orders of magnitude faster.</p>\n<p>Now, let me be clear: this is not about saying “strings are bad”. Strings are <em>somewhat</em> expensive, but… if you need ’em, you need ’em.</p>\n<p>The point here is about asking: <em>do</em> you need ’em? When you do, use them. But… if you can avoid them—especially when they’re just throwaway temporaries—then it really is worthwhile to rethink your design and your interfaces to allow avoiding them. And this is a general truth for <em>all</em> expensive or somewhat-expensive types, not just strings.</p>\n<h1>Avoiding dynamic polymorphism</h1>\n<p>I know everybody learns in school about object-oriented programming and inheritance and how it’s bee’s knees… but here’s the ugly reality: dynamic polymorphism is the absolute <em>worst</em> design choice you can make in C++. Yeah, I said that.</p>\n<p>Allow me to back my position up. There are a number of reasons why you want to avoid designs based on dynamic polymorphism in C++:</p>\n<ul>\n<li>It requires reference semantics, and C++ is a value-semantic language, so you’re fighting against the language, which is never a good thing.</li>\n<li>It doesn’t work well with compile-time checking and <code>constexpr</code>, which is bad, because that’s where you get the maximum power of C++.</li>\n<li>It usually requires dynamic allocation, which is inefficient, cumbersome, and error-prone (though smart pointers do help a lot with the latter).</li>\n<li>It’s usually much less efficient because of the dynamic allocation, extra vtable pointers, and extra indirection in virtual calls.</li>\n<li>And there are a ton of nasty gotchas waiting to bite you in the ass, like slicing, if you’re not <em>very</em> careful (particularly with copying/moving/swapping).</li>\n</ul>\n<p>Now, don’t get me wrong: I’m not saying that object-oriented programming and dynamic polymorphism are <em>ALWAYS</em> bad. If you’re writing Java, that’s the default solution you should reach for… but C++ ain’t Java. And there <em>are</em> some situations in C++ where dynamic polymorphism is exactly the right solution. (I used it myself in my own game engine, for several things—for example, the game states are all derived from an abstract base class <code>state</code>, so the game’s state machine can switch between arbitrary states (like the world map state, the battle state, the menu state, and so on). This allows for an infinitely extensible amount of game modes, and the cost is negligible, because there’s only a few states active at a time at most, and there are only ~3 virtual calls each game loop.)</p>\n<p>I’m not saying <em>never</em> use dynamic polymorphism… I’m just saying to consider <em>every other possible alternative</em> before choosing it.</p>\n<p>And in fact, in your design, you’re not really using dynamic polymorphism all that well.</p>\n<p>For example, the fundamental reason why you’d create an abstract base class is to allow deriving arbitrary extension classes… including stuff the original base class designer never heard of. Like, when you create a <code>shape</code> base class, you’re leaving the door open for concrete classes for every shape you know (<code>circle</code>, <code>rectangle</code>, <code>triangle</code>)… but also for <em>every shape you’ve never heard of</em> (like <a href=\"https://en.wikipedia.org/wiki/Astroid\" rel=\"nofollow noreferrer\"><code>astroid</code></a>, <a href=\"https://en.wikipedia.org/wiki/Enneadecagon\" rel=\"nofollow noreferrer\"><code>enneadecagon</code></a>, or <a href=\"https://en.wikipedia.org/wiki/Tomoe\" rel=\"nofollow noreferrer\"><code>tomoe</code></a>).</p>\n<p>It defeats the whole purpose of dynamic polymorphism to have a fixed, closed set of possible derived types. For example, it would be silly to have a base class for the moves in rock-paper-scissors. There are only 3 possible moves: rock, paper, and scissors. You don’t need to allow for infinite possibilities when there are only 3.</p>\n<p>Which brings us to this:</p>\n<pre><code>enum class item_type {\n ITEM_TYPE_ARMOR = 0,\n ITEM_TYPE_WEAPON = 1,\n ITEM_TYPE_POTION = 2\n};\n</code></pre>\n<p>You already know, even before you start defining the <code>Item</code> class, that there are only 3 possibly types of item.</p>\n<p>Now, in their answer, Edward suggests using <code>dynamic_cast</code> for this purpose instead… and they’re right, that would be the smarter way to do it. <em>HOWEVER</em>… it’s still bad, and you can see why even in the improved code Edward offers:</p>\n<pre><code>int Entity::equipOrConsume(std::unique_ptr<Item> &&i)\n{\n auto old{std::move(i)};\n if (Weapon* new_weapon = dynamic_cast<Weapon*>(old.get())) {\n // ... [snip] ...\n }\n else if (Consumable* new_consumable = dynamic_cast<Consumable*>(old.get())) {\n // ... [snip] ...\n }\n else if (Armor* new_armor = dynamic_cast<Armor*>(old.get())) {\n // ... [snip] ...\n }\n return 0;\n}\n</code></pre>\n<p>What’s the point of having a polymorphic type if you’re just going to treat every derived type differently anyway?</p>\n<p>The problem here is that you have three completely unrelated types—things that really have nothing in common—except that you want to shoehorn them all into an inventory. So you search for a way to link them all together, and all you can come up with is, “well, they’re all ‘things’”. Or, rather, “items”. This isn’t good design; you are not modelling the actual, natural relationship between armour, weapons, and items, you are just creating an artificial connection because you need to store them all in an inventory.</p>\n<p>Indeed, look at what the <code>Item</code> base class actually looks like (if we remove the <code>item_type</code> stuff, and data members (abstract base classes should not have data members)):</p>\n<pre><code>class Item\n{\npublic:\n virtual ~Item() = default;\n\n virtual std::string toString() const = 0;\n};\n</code></pre>\n<p>The only thing that they all have in common is… you can print ’em. That’s kind of a weak relationship.</p>\n<p>So what’s the alternative here?</p>\n<p>Well, the most basic alternative is: since you already know what all the possible item types are… just put ’em all in the <code>Item</code> class:</p>\n<pre><code>class Item\n{\npublic:\n enum class Type\n {\n armor,\n weapon,\n potion\n };\n\nprivate:\n Type _type;\n std::size_t _name_idx; // used to look up name string in tables\n int _value; // has different meaning depending on type\n\n // private constructor, so you can only create items via the static funcs\n Item(Type, std::size_t, int);\n\npublic:\n // randomly generate various item types\n static auto generate_armor(RandomEngine&) -> Item;\n static auto generate_weapon(RandomEngine&) -> Item;\n static auto generate_potion(RandomEngine&) -> Item;\n\n auto type() const noexcept -> Type;\n auto value() const noexcept -> int;\n\n auto to_string() const -> std::string;\n};\n</code></pre>\n<p>And you might use it something like this:</p>\n<pre><code>int Entity::equipOrConsume(Item const& item)\n{\n switch (item.type())\n {\n case Item::Type::armor:\n defence += (armor ? -armor.value() : 0) + item.value();\n armor = item;\n break;\n case Item::Type::potion:\n health = std::clamp(health + item.value(), 0, 100);\n break;\n case Item::Type::weapon:\n attack += (weapon ? -weapon.value() : 0) + item.value();\n weapon = item;\n break;\n }\n\n return 0;\n}\n</code></pre>\n<p>Now, I’m <em>not</em> saying this is a <em>good</em> design. If you add more item types, things will get unwieldy <em>very</em> quickly. But it will be <em>thousands</em> of times more efficient than your current design, what with all the dynamic allocation and indirection and so on.</p>\n<p>So what would be a better design? Well, rather than <em>dynamic</em> polymorphism… you could use <em>static</em> polymorphism.</p>\n<p>It’ll be much easier to show than explain, but the basic idea is that it doesn’t make sense to shoehorn weapons, armour, and potions into some vague “item” type—they’re obviously completely unrelated things that you just happen to want to stick in the same inventory slots. So let’s make it so:</p>\n<pre><code>// for brevity, i'm not going to show the COMPLETE classes for the three\n// item types, but you should get the gist of it\n\nclass Armor\n{\n std::size_t _name_idx;\n int _def;\n\npublic:\n auto def() const noexcept -> int;\n\n auto to_string() const -> std::string;\n};\n\nclass Weapon\n{\n std::size_t _name_idx;\n int _atk;\n\npublic:\n auto atk() const noexcept -> int;\n\n auto to_string() const -> std::string;\n};\n\nclass Potion\n{\n std::size_t _name_idx;\n int _amount;\n\npublic:\n auto amount() const noexcept -> int;\n\n auto to_string() const -> std::string;\n};\n\n// and here's where the magic happens...\nusing Item = std::variant<Armor, Weapon, Potion>;\n\n// or, rather than an ad-hoc alias, you could create an actual item class that\n// has the variant as a data member, then rather than the free functions that\n// follow, you could make these member functions\n\n// for cases where the behaviour is the same for all item types, you can do\n// something like this:\nauto to_string(Item const& item)\n{\n return std::visit([](auto&& i) { return i.to_string(); }, item);\n}\n\n// for cases where the behaviour differs between types, you can do something\n// like this:\nauto equip_or_consume_item(Entity& entity, Item const& item)\n{\n struct\n {\n Entity& entity;\n \n auto operator()(Armor const& armor)\n {\n // adjust the entity's def, and change armour\n }\n\n auto operator()(Weapon const& weapon)\n {\n // adjust the entity's atk, and change weapon\n }\n\n auto operator()(Potion const& potion)\n {\n // adjust the entity's health\n }\n } entity_visitor{.entity = entity};\n\n // if you add a new item type, but forget to add something to handle it\n // in the visitor above, you will get a compile-time error\n //\n // that way you'll never fail to properly update everywhere you need to\n // consider a new item type\n //\n // you could also pull out the struct above, maybe call it select_item_handler,\n // and keep it closer to the entity class - you have design options\n\n std::visit(entity_visitor, item);\n}\n</code></pre>\n<p>As you can see, when the behaviour is the same (such as with <code>to_string()</code>) you can use <code>auto&&</code> as a catch-all default. When you need different behaviour, you can use a more complex visitor, as in <code>equip_or_consume_item()</code> above. Or you can use <code>std::holds_alternative()</code> to detect what type of item it is. Or <code>std::get_if()</code>. You have options. (But using a visitor with the types given, and with no <code>auto&&</code> catch-all, allows you to detect at compile time that you’ve covered all the possible item types.)</p>\n<p>This next bit is very advanced, but I want to show you just how powerful and flexible this technique is. You could get really clever, and use concepts to allow for a whole class of “things”, and operate on all them the same way. For example rather than having an armour class, you could have an armour <em>concept</em>, where anything that is armour adds DEF when worn:</p>\n<pre><code>// you could obviously make a *much* better concept than this, but i'm just\n// illustrating the idea\ntemplate <typename T>\nconcept armour = \n requires (T t)\n {\n {t.def()} -> std::same_as<int>;\n };\n\nclass shield\n{\n std::size_t _name_idx;\n int _def;\n\npublic:\n auto def() const noexcept -> int;\n\n auto to_string() const -> std::string;\n};\n\nclass helmet\n{\n std::size_t _name_idx;\n int _def;\n\npublic:\n auto def() const noexcept -> int;\n\n auto to_string() const -> std::string;\n};\n\n// etc. with more armour types\n\nusing item = std::variant<\n shield,\n helmet,\n // other armour types\n sword,\n axe,\n // other weapon types\n minor_potion,\n greater_potion,\n // other potion types\n>;\n\ntemplate <entity Entity>\nclass select_item_handler\n{\n Entity& _entity;\n\n template <armour Armour>\n auto operator()(Armor const& armor)\n {\n // adjust the entity's def, and change armour\n //\n // works with *ANY* entity type, and *ANY* armour type\n }\n\n // more operators for weapons, potions, and any other types\n //\n // you can special case specific types of armour, weapons, or whatever\n // simply by naming the type explicitly (that is, not using a function\n // template like above)\n //\n // and you can still add a catch-all default with an unconstrained\n // function template\n};\n</code></pre>\n<p>That would allow you to have all different kinds of armour, and you could use logic to make sure you only wear one of each type, but they all add to your defence.</p>\n<p>But back to the original design, using a variant to hold armour, weapons, and potions allows you to make an inventory without requiring smart pointers:</p>\n<pre><code>std::vector<Item> inventory;\n</code></pre>\n<p>That will just work, and it will be <em>much</em> smaller, and <em>much</em> faster to iterate over:</p>\n<pre><code>// there are many different ways to iterate over the inventory\n\n// an in-place visitor (good for simple stuff, or where the behaviour is the\n// same for all item types):\nfor (auto&& item : inventory)\n std::cout << std::visit([](auto&& i) { return i.to_string(); }, item) << '\\n';\n\n// a separate visitor (for more complex stuff, or where the behaviour has to\n// be different for different types):\nstruct\n{\n auto operator()(Potion const& potion)\n {\n using namespace std::string_literals;\n return "a potion"s;\n }\n\n // fallback function, used for anything that isn't a potion:\n template <typename T>\n auto operator()(T const& t)\n {\n return t.to_string();\n }\n} visitor;\n\nfor (auto&& item : inventory)\n std::cout << std::visit(visitor, item) << '\\n';\n\n// you can use holds_alternative to select specific types:\nfor (auto&& item : inventory)\n{\n // do something with only weapons\n if (std::holds_alternative<Weapon>(item))\n std::cout << "weapon found!\\n";\n}\n\n// or you can use get_if:\nfor (auto&& item : inventory)\n{\n // do something with only armour\n if (auto const p_armor = std::get_if<Armor>(&item); p_armour != nullptr)\n std::cout << "armour: " << p_armor->to_string() << '\\n';\n}\n</code></pre>\n<p><em>ALL</em> of these options are <em>MUCH</em> more efficient than iterating through a vector of smart pointers and either using <code>dynamic_cast</code> or calling virtual functions.</p>\n<p>The same way that variant collects all the item types into a compile-time sum type, you could make a variant that collects all the entity types.</p>\n<p>This is a completely different way of thinking about program design, and if all you know is classic OO with dynamic polymorphism, it can look weird and wrong. But if your set of types is closed—that is, if you know every type that’s ever going to be used, and you’re not leaving the door open for anything else (which is true for most programs)—then you can get <em>massive</em> performance, usability, and safety benefits from compile-time, static polymorphism. And there are many, many more benefits that I haven’t even been able to cover. Like, for example, with your current, classic-OO, runtime-polymorphic design, if you want to add a new capability to items—like a new function in the item interface, or a whole new interface (like <code>IDrawable</code>, maybe?)—then you will break <em>EVERYTHING</em>; <em>EVERY</em> class that derives from <code>Item</code> or that needs the new interface will have to be adjusted… but with a compile-time polymorphic design like the one illustrated above, it’s trivial to add more functions to the common item interface, or to add whole new interfaces—you can even add these new things bit-by-bit.</p>\n<h1>Getting smart with randomness</h1>\n<p>This is only a small additional suggestion. You have already had it suggested by all the other reviewers that you should use the C++ <code><random></code> library instead of <code>std::rand()</code>. I third that sentiment; <code>std::rand()</code> is <em>garbage</em>. <em>AND</em> you’re not even using it correctly (not totally your fault, because it is <em>INCREDIBLY</em> hard to use correctly, but doing <code>std::rand() % N</code> to get a random number between <code>0</code> and <code>N -1</code> is <em>wrong</em>).</p>\n<p>So okay, I’m going to assume you’re going to use a proper RNG library, and I’m going to assume it’s <code><random></code>. If so, then I can give you some advice on how to use it in a game.</p>\n<p>First, you <em>usually</em> only need a single random generator for a game. (For something like scientific or engineering simulations, it can be handy to have each “thing” being simulated to have its own RNG, but that’s <em>WAY</em> overkill for a game.) Or, at most, a single RNG per thread. (Having a per-thread RNG means you don’t need to worry about synchronizing your RNG, but it also means your game is now totally unpredictable. You may be thinking: “Good! Unpredictable is good!” No, unpredictable is bad, because it makes testing functionally impossible, and it means you can’t do things replays to debug or detect cheating.)</p>\n<p>So assuming you have only a single RNG, you should select a really good one—MT19937 is more than good enough. Then what you want to do is set it up and seed it right at the beginning of the game. The standard setup pattern for <code><random></code> engines works fine:</p>\n<pre><code>auto prng = std::mt19937{std::random_device{}()};\n</code></pre>\n<p>Probably the best design is to have a class or function that returns a reference to some static RNG object. That way you don’t have to keep passing it around through your entire game code, and if you need to you can mock it out for testing:</p>\n<pre><code>// random.hpp\n\n#ifndef THEGAME_RANDOM_HPP\n#define THEGAME_RANDOM_HPP\n\n#include <random>\n\n// you should always put your stuff in a namespace\nnamespace ns {\n\nusing random_engine_t = std::mt19937;\n\nauto random_engine() noexcept -> random_engine_t&;\n\n} // namespace ns\n\n#endif // include guard\n\n// random.cpp\n\n#include "random.hpp"\n\nnamespace {\n\nauto prng = std::mt19937{std::random_device{}()};\n\n} // anonymous namespace\n\nnamespace ns {\n\nauto random_engine() noexcept -> random_engine_t&\n{\n return prng;\n}\n\n} // namespace ns\n</code></pre>\n<p>Now here’s where the game-specific stuff really comes in. For games, I have found that you only need to think about 4 (well, 3½) distributions:</p>\n<ul>\n<li><code>std::uniform_int_distribution</code></li>\n<li><code>std::uniform_real_distribution</code></li>\n<li><code>std::bernoulli_distribution</code></li>\n<li><code>std::normal_distribution</code></li>\n</ul>\n<p>The first two are basically the same—just one for <code>int</code>s and one for <code>double</code>s. These are the ones you use when you want a number between <em>A</em> and <em>B</em>, and every value between those two numbers is equally likely. For example, rolling a die:</p>\n<pre><code>// returns a random value between 1 and 6 inclusive, with each value equally likely\nauto roll(random_engine_t& gen)\n{\n static auto dist = std::uniform_int_distribution{1, 6};\n\n return dist(gen);\n}\n</code></pre>\n<p>This is basically what you’d use for all your generate functions:</p>\n<pre><code>auto Consumable::generateConsumable() -> Consumable\n{\n constexpr auto hp_min = 0; // assuming you really want a potion that heals 0 hp\n constexpr auto hp_max = 100;\n\n constexpr auto hp_greater_min = 80;\n constexpr auto hp_great_min = 50;\n\n static auto hp_dist = std::uniform_int_distribution{hp_min, hp_max};\n\n auto const hp = hp_dist(random_engine());\n\n auto const name = [&] {\n if (hp > hp_greater_min)\n return name_greater_health_potion;\n if (hp > hp_great_min)\n return name_great_health_potion;\n return name_health_potion;\n }();\n\n return Consumable{name, hp};\n}\n</code></pre>\n<p><code>std::uniform_real_distribution</code> is the same idea, but for cases when you want a floating-point number.</p>\n<p><code>std::bernoulli_distribution</code> is what you’d use for win/lose or pass/fail situations. For example, if there’s a spell that will insta-kill 5% of the time, you could do:</p>\n<pre><code>constexpr auto death_spell_success_rate = 0.05;\n\nauto death_spell_success_dist = std::bernoulli_distribution{death_spell_success_rate};\n\n// when casting the spell\nif (death_spell_success_dist(random_engine()))\n std::cout << "insta-kill";\nelse\n std::cout << "spell has failed";\n</code></pre>\n<p><code>std::normal_distribution</code> is my favourite distribution for adding just a little bit of spice to a game. Let’s say you have a 150 ATK sword of smiting, and your enemy is wearing +50 DEF leather underwear… you do your damage calculation according to your game’s rules, and discover the effective damage from the attack is 100 HP. You’ve done your check for whether the attack is a miss or blocked or whatever (perhaps using <code>std::bernoulli_distribution</code>), and now it’s time to figure out the actual damage done from the attack.</p>\n<p>Now you <em>could</em> just say: “well, the damage is 100 HP,” and be done with it. But… that makes for a pretty static and uninteresting game. A player can simply sit there with a calculator and predict the outcome of a battle. Yawn.</p>\n<p>Instead what you could do is add a little bit of randomness to the damage. But, here’s the thing! You don’t want to add <em>too</em> much randomness! If the nominal damage from an attack is 100 HP, you don’t want to shock the player by saying it actually only did 2 HP of damage. Or 200 HP. That would just annoy the player.</p>\n<p>You want the damage to be <em>roughly</em> 100 HP. Like, 101 HP is fine. So is 99 HP. 105 HP is also ok. 70 HP is… unlikely. 180 HP is <em>very</em> unlikely. This is exactly what a normal distribution is for:</p>\n<pre><code>auto nominal_damage = 100;\nauto stddev = nominal_damage * 0.05; // ~70% of attacks will be with +/-5% of the nominal\n\nauto damage_dist = std::normal_distribution{nomimal_damage, stddev};\n\nauto const damage_d = damage_dist(random_engine());\nauto const damage = static_cast<int>(damage_d); // because you probably want the result as an int\n</code></pre>\n<p>Normal distributions make a game <em>much</em> more interesting. In the example above, I set the standard deviation at 5%… but you could even vary that. For example, you could have a berserker mode where the deviation is more like 30%: that means you <em>could</em> hit a <em>lot</em> harder… but you could also swing wild and hit a lot weaker.</p>\n<h1>Summary</h1>\n<p>I’ve tried to give a very high-level overview of design decisions in your code; for actual code reviews, I think the other answers you already have are excellent.</p>\n<p>The main problems with your existing design are:</p>\n<ul>\n<li><em>WAAAAY</em> too much dynamic allocation. A lot of that is a consequence of using dynamic polymorphism.</li>\n<li>Too much unnecessary copying of data. If you modify your interfaces to access data directly, or to copy data directly into output buffers, that will speed things up considerably.</li>\n</ul>\n<p>You should also consider moving away from a design based on dynamic polymorphism, and look into static (compile-time) polymorphism. That requires a <em>MASSIVE</em> re-imagining of your design and code, but it does also come with massive performance gains.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T07:16:47.140",
"Id": "502942",
"Score": "0",
"body": "Thank you very much for this detailed answer. I will mark it as accepted because it touches the architecture of the code and addresses the things I could do differently, which is what I was looking for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T05:19:47.560",
"Id": "254982",
"ParentId": "254731",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "254982",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T06:13:18.403",
"Id": "254731",
"Score": "5",
"Tags": [
"c++",
"game"
],
"Title": "Dwarf Fortress Clone - C++"
}
|
254731
|
<pre><code>typedef const bool* const TypeID;
template<typename>
TypeID TypeIdOf() noexcept {
static const bool idLoc(0);
return &idLoc;
}
</code></pre>
<p>I'm using this function to return from some derived classes to differentiate them at runtime, by returning from this function, templated as the class. ie:</p>
<pre><code>class Object
{
...
TypeID Type() const = 0;
template<typename T> bool IsType() const
{ return Type() == TypeIdOf<T>(); }
...
};
class DerivedObject:
public Object
{
...
TypeID Type() const override { return TypeIdOf<DerivedObject>(); }
...
};
</code></pre>
<p>It's worked so far, but it took me a while to decide to use it, and I'm still having some worries about using it in the long-term. So I'm asking my first question here: is this code OK? Is it thread safe? Could this throw any exceptions? Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T08:23:20.887",
"Id": "502402",
"Score": "0",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T08:27:00.267",
"Id": "502403",
"Score": "0",
"body": "@AryanParekh Should I edit my question and add the concrete code I'm working on? I wouldn't be able to do that right now, because of circumstance, but I could do that later. Or should I remove the question, and ask again with said code when I have time? Sorry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T08:28:28.753",
"Id": "502404",
"Score": "0",
"body": "That's alright, but do not post a new question, you can simply [edit] the existing one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T08:29:32.707",
"Id": "502405",
"Score": "0",
"body": "@AryanParekh Understood. I'll find some time later. Cheers."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T07:43:31.127",
"Id": "254733",
"Score": "1",
"Tags": [
"c++",
"template",
"pointers",
"polymorphism",
"static"
],
"Title": "Using (templated) function-scope static address as Unique ID"
}
|
254733
|
<p>I am a beginner in FPGAs, and I am studying Verilog HDL. Could you please check the quality of my code (a shift register)? Any comments are welcome.</p>
<p>The shift register serializes parallel from <code>wr_data_i</code> data to <code>serial_data_o</code> and has two variations of first serialized bit. It may be most significant bit or least significant bit, which is defined in parameters as <code>TRUE</code> or <code>FALSE</code>.</p>
<pre><code>`timescale 1ns / 1ps
module shift_reg #
(
parameter integer DATA_WIDTH = 16,
parameter integer DO_MSB_FIRST = "TRUE"
)
(
input wire clk_i,
input wire s_rst_n_i,
input wire enable,
input wire wr_enable,
input wire [DATA_WIDTH - 1 : 0] wr_data_i,
output wire serial_data_o
);
localparam integer MSB = DATA_WIDTH - 1;
localparam integer LSB = 0;
localparam integer XSB = ("TRUE" == DO_MSB_FIRST) ? MSB : LSB;
reg [DATA_WIDTH - 1 : 0] parallel_data;
assign serial_data_o = (1'h1 == enable) ? parallel_data[XSB] : 1'hz;
always @ (posedge clk_i)
begin
if (1'h0 == s_rst_n_i)
begin
parallel_data <= 'h0;
end
else if (1'h1 == wr_enable)
begin
parallel_data <= wr_data_i;
end
else if (1'h1 == enable)
begin
if ("TRUE" == DO_MSB_FIRST)
begin
parallel_data <= {parallel_data[MSB - 1 : 0], 1'h0};
end
else
begin
parallel_data <= {1'h0, parallel_data[MSB: 1]};
end
end
end
endmodule
</code></pre>
|
[] |
[
{
"body": "<p>I don't see any problems with the code functionally, and the layout follows good practices for the most part. You chose meaningful names for the signals and parameters, and the parameters make your design scalable to different data widths. It also follows good practices using nonblocking assignments for the sequential logic. This is excellent for a beginner.</p>\n<p>You should use a sized constant for the data reset value (<code>'h0</code>) in order to avoid synthesis lint warnings from some tools. I prefer the replicated concatenation style for this: <code>{DATA_WIDTH{1'h0}}</code>.</p>\n<p>I think it is more conventional to omit the <code>1'h1 ==</code> in comparisons to 1 for 1-bit signals. It makes the code a little cleaner, and all the tools do the right thing. For example: <code>(wr_enable)</code>.</p>\n<p>Similarly for comparisons to 0, omit the <code>1'h0 ==</code>, and use either <code>!</code> or <code>~</code> (they are equivalent for 1-bit signals): <code>(!s_rst_n_i)</code></p>\n<p>You did a fantastic job of using a consistent layout style. The following comments are my preferences, but you might consider using them as well.</p>\n<p>I use 4-space indentation because I think it is easier to see the different levels of your code's logic.</p>\n<p>I prefer to place the <code>begin</code> and <code>end</code> keywords on the same line as the <code>if/else</code> keywords in order to reduce vertical space and get more code on one screen. It also makes the branches of your code more evident.</p>\n<p>Here is the code with the above suggestions:</p>\n<pre><code>`timescale 1ns / 1ps\n\nmodule shift_reg # \n(\n parameter integer DATA_WIDTH = 16,\n parameter integer DO_MSB_FIRST = "TRUE"\n)\n(\n input wire clk_i,\n input wire s_rst_n_i,\n input wire enable,\n input wire wr_enable,\n\n input wire [DATA_WIDTH - 1 : 0] wr_data_i,\n\n output wire serial_data_o\n);\n localparam integer MSB = DATA_WIDTH - 1;\n localparam integer LSB = 0;\n localparam integer XSB = ("TRUE" == DO_MSB_FIRST) ? MSB : LSB;\n\n reg [DATA_WIDTH - 1 : 0] parallel_data;\n\n assign serial_data_o = (enable) ? parallel_data[XSB] : 1'hz;\n \n always @ (posedge clk_i) begin\n if (!s_rst_n_i) begin\n parallel_data <= {DATA_WIDTH{1'h0}};\n end else if (wr_enable) begin\n parallel_data <= wr_data_i;\n end else if (enable) begin\n if ("TRUE" == DO_MSB_FIRST) begin\n parallel_data <= {parallel_data[MSB - 1 : 0], 1'h0};\n end else begin\n parallel_data <= {1'h0, parallel_data[MSB : 1]};\n end \n end\n end\nendmodule\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:38:06.697",
"Id": "254743",
"ParentId": "254737",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254743",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T09:29:05.597",
"Id": "254737",
"Score": "3",
"Tags": [
"beginner",
"verilog",
"hdl"
],
"Title": "Parameterized Verilog shift register code"
}
|
254737
|
<p>The Plain vanilla JS needs to converted in to advanced ECMA. The below 3 snippets shown yields the correct result. Need to identify which among them is performance oriented</p>
<pre><code>this.allUserDetails.forEach((el, indx) => {
if (type === 0 && flagResumeAll === false) {
if (el.extensionTime === time && el.userProctorSignal === 0) {
this.toggleButtonDisplayType = 0;
} else {
flagResumeAll = true;
}
} else if (type === 1 && flagPauseAll === false) {
if (el.extensionTime === time && el.userProctorSignal === 1) {
this.toggleButtonDisplayType = 1;
} else {
flagPauseAll = true;
}
}
});
</code></pre>
<p>The above code could be repaced with Code I and Code II</p>
<p><strong>Code I</strong></p>
<pre><code>if (type === 0 && flagResumeAll === false) {
this.allUserDetails.filter(el => {
if(el.extensionTime === time && el.userProctorSignal === 0) {
this.toggleButtonDisplayType = 0;
} else {
flagResumeAll = true;
}
})
} else if (type === 1 && flagPauseAll === false) {
this.allUserDetails.filter(el => {
if(el.extensionTime === time && el.userProctorSignal === 1) {
this.toggleButtonDisplayType = 1;
} else {
flagPauseAll = true;
}
})
</code></pre>
<p><strong>Code II</strong></p>
<pre><code>this.allUserDetails.filter(el => {
if(type === 0 && flagResumeAll === false && el.extensionTime === time && el.userProctorSignal === 0) {
this.toggleButtonDisplayType = 0;
} else if (type === 0 && flagResumeAll === false){
flagResumeAll = true;
} else if (type === 1 && flagPauseAll === false && el.extensionTime === time && el.userProctorSignal === 1) {
this.toggleButtonDisplayType = 1;
} else if(type === 1 && flagPauseAll === false) {
flagPauseAll = true;
}
})
</code></pre>
<p>Which among them is yields better in performance replacing from plain/vanilla JS to Code I/II.
Will this be further simplified..</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T16:14:52.677",
"Id": "502528",
"Score": "0",
"body": "is flagResumeAll used elsewhere in the code?"
}
] |
[
{
"body": "<p>It looks like the main difference between your original code snippet and the two revisions is that you're using <code>.filter()</code> instead of <code>.forEach()</code> - both of which came out around the same time, and both of which came out a while ago (IE 9 supports both).</p>\n<p>It looks like you aren't doing any significant changes to the code that would improve speed, so you will only see marginal improvements to performance, if any. But, you can always benchmark each of them and find out for yourself how fast each version is.</p>\n<p>The original solution is actually the best one among the three shown. There seems to be a big misunderstanding about what the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">filter()</a> function is and how to use it. filter() is supposed to take an array and return a new array with some values filtered out. The values that get filtered out is decided by the function passed in. For example, if you want the even numbers in a list of numbers, you could do this:</p>\n<pre><code>const numbers = [1, 3, 4, 6, 7, 9]\nconst isEven = n => n % 2 === 0\nconsole.log(numbers.filter(isEven)) // [ 4, 6 ]\n</code></pre>\n<p>You are not using filter() this way - you're just using is like an alternative forEach() function, which is a big no-no. You can just change the <code>.filter()</code> for <code>.forEach()</code> in each of your revisions. Once you have done that, both your original code and your first revision would work just fine. I wouldn't go with the second one though, there's too much inside the if conditions.</p>\n<p>I don't really have any newer javascript feature to suggest for these code snippets, except that I generally recommend using the newer <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\">for of</a> loop instead of forEach() - it's more powerful than .forEach(), and it fixes the issues that for-in loops had.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T05:06:18.437",
"Id": "254780",
"ParentId": "254738",
"Score": "2"
}
},
{
"body": "<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Array.some\">Array.some</a></h2>\n<p>In the loop when <code>flagResumeAll</code> becomes <code>true</code> nothing more will change thus it is best to exit the loop.</p>\n<p>If <code>flagResumeAll</code> is already <code>true</code> then nothing can be done inside the loop so you should not even start it. The same with <code>type</code> if not <code>0</code> or <code>1</code> then the loop will do nothing.</p>\n<p>Using the first example as a guide to what your code should do you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array\">Array</a> function <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Array.some\">Array.some</a> to set <code>flagResumeAll</code></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Array.some\">Array.some</a> will exit the iteration when "some" of the items returns true, Or think of it as <em>"if any"</em> of the items returns true (JavaScript's built in bad naming <code>some</code> implies more than one)</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global object reference. Array.some\">Array.some</a> exits when the callback returns <code>true</code> and returns <code>true</code>, or when there is no match it iterates all items then returns <code>false</code>.</p>\n<h2>Rewrite</h2>\n<p>As a function as there is no context at all to guide naming. So the function is called <code>doThing</code></p>\n<pre><code>const doThing = (type, time) => {\n if (type === 0 || type === 1) {\n return this.allUserDetails.some(el => {\n if (el.extensionTime === time && el.userProctorSignal === type) {\n this.toggleButtonDisplayType = type;\n } else {\n return true;\n }\n });\n }\n return false;\n}\n\nflagResumeAll = flagResumeAll || doThing(type, time);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T18:12:38.617",
"Id": "254804",
"ParentId": "254738",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254804",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T09:39:27.957",
"Id": "254738",
"Score": "0",
"Tags": [
"javascript",
"performance",
"ecmascript-6",
"typescript",
"ecmascript-8"
],
"Title": "Looping Array object with conditions and comparison the performance with ECMA VS Vanilla JS"
}
|
254738
|
<p>The app when works fine, but people are saying that the code is not written with good code style and following OOP principles.</p>
<p>Can I improve on any parts of my code? Especially regarding:</p>
<ul>
<li>Code comments</li>
<li>Variable naming</li>
<li>Separation of concerns</li>
<li>Single responsibility principle</li>
<li>etc.</li>
</ul>
<pre class="lang-java prettyprint-override"><code>import javafx.application.Application;
import javafx.stage.Stage;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.util.Duration;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.application.Platform;
public class AnalogClockv2 extends Application {
@Override // Override the start method in the Application class
public void start(Stage primaryStage) {
ClockPane clock = new ClockPane(); // Create a clock
HBox hBox = new HBox(5);
Button btStop = new Button("Stop");
Button btStart = new Button("Start");
hBox.getChildren().addAll(btStop, btStart);
hBox.setAlignment(Pos.CENTER);
BorderPane pane = new BorderPane();
pane.setCenter(clock);
pane.setBottom(hBox);
// Create a scene and place it in the stage
Scene scene = new Scene(pane, 250, 300);
primaryStage.setTitle("Java Analog Clock Reloaded"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
clock.widthProperty().addListener(ov -> {
clock.setW(pane.getWidth());
});
clock.heightProperty().addListener(ov -> {
clock.setH(pane.getHeight());
});
}
/**
* The main method is only needed for the IDE with limited
* JavaFX support. Not needed for running from the command line.
*/
public static void main(String[] args) {
launch(args);
}
class ClockPane extends Pane {
private int hour;
private int minute;
private int second;
// Clock pane's width and height
private double w = 250, h = 250;
private int sleepTime = 50;
/**
* Construct a default clock with the current time
*/
public ClockPane() {
setCurrentTime();
}
/**
* Construct a clock with specified hour, minute, and second
*/
public ClockPane(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
paintClock();
}
/**
* Return hour
*/
public int getHour() {
return hour;
}
/**
* Set a new hour
*/
public void setHour(int hour) {
this.hour = hour;
paintClock();
}
/**
* Return minute
*/
public int getMinute() {
return minute;
}
/**
* Set a new minute
*/
public void setMinute(int minute) {
this.minute = minute;
paintClock();
}
/**
* Return second
*/
public int getSecond() {
return second;
}
/**
* Set a new second
*/
public void setSecond(int second) {
this.second = second;
paintClock();
}
/**
* Return clock pane's width
*/
public double getW() {
return w;
}
/**
* Set clock pane's width
*/
public void setW(double w) {
this.w = w;
paintClock();
}
/**
* Return clock pane's height
*/
public double getH() {
return h;
}
/**
* Set clock pane's height
*/
public void setH(double h) {
this.h = h;
paintClock();
}
/* Set the current time for the clock */
public void setCurrentTime() {
// Construct a calendar for the current date and time
Calendar calendar = new GregorianCalendar();
// Set current hour, minute and second
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
this.minute = calendar.get(Calendar.MINUTE);
this.second = calendar.get(Calendar.SECOND);
paintClock(); // Repaint the clock
}
/**
* Paint the clock
*/
private void paintClock() {
// Initialize clock parameters
double clockRadius = Math.min(w, h) * 0.8 * 0.5;
double centerX = w / 2;
double centerY = h / 2;
// Draw circle
Circle circle = new Circle(centerX, centerY, clockRadius);
circle.setFill(Color.WHITE);
circle.setStroke(Color.BLACK);
Text t1 = new Text(centerX - 5, centerY - clockRadius + 12, "12");
Text t2 = new Text(centerX - clockRadius + 3, centerY + 5, "9");
Text t3 = new Text(centerX + clockRadius - 10, centerY + 3, "3");
Text t4 = new Text(centerX - 3, centerY + clockRadius - 3, "6");
// Draw second hand
double sLength = clockRadius * 0.8;
double secondX = centerX + sLength
* Math.sin(second * (2 * Math.PI / 60));
double secondY = centerY - sLength
* Math.cos(second * (2 * Math.PI / 60));
Line sLine = new Line(centerX, centerY, secondX, secondY);
sLine.setStroke(Color.RED);
// Draw minute hand
double mLength = clockRadius * 0.65;
double xMinute = centerX + mLength
* Math.sin(minute * (2 * Math.PI / 60));
double minuteY = centerY - mLength
* Math.cos(minute * (2 * Math.PI / 60));
Line mLine = new Line(centerX, centerY, xMinute, minuteY);
mLine.setStroke(Color.BLUE);
// Draw hour hand
double hLength = clockRadius * 0.5;
double hourX = centerX + hLength
* Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12));
double hourY = centerY - hLength
* Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12));
Line hLine = new Line(centerX, centerY, hourX, hourY);
hLine.setStroke(Color.GREEN);
getChildren().clear();
getChildren().addAll(circle, t1, t2, t3, t4, sLine, mLine, hLine);
}
}
}
</code></pre>
<p>For more context, the code is used to teach the fundamentals of OOP, how to use Java, and JavaFX in a high school CS course.</p>
<p>Please ask for clarification if there are issues running the code if needed, this is my first time on this site. Thanks!</p>
|
[] |
[
{
"body": "<p>I will point out one thing as it relates to OOP. You can potentially run into issues when you extend <code>Pane</code>. If you are going to extend <code>Pane</code>, make the class final.</p>\n<pre><code>public final class ClockPane extends Pane\n</code></pre>\n<p>The other route is not to extend <code>Pane</code>. Using that route, you can create a method that returns the <code>Clock</code> as a <code>Pane</code>.</p>\n<pre><code>Clock clock = new Clock(..,..,..);\n...\n...\nclock.getAsPane();\n</code></pre>\n<p>For more information about this potential pitfall, go <a href=\"https://stackoverflow.com/questions/43877557/the-correct-way-to-handle-and-extend-node-in-javafx\">here</a>.</p>\n<p>I created similar apps a while back. You can get some pointers from <a href=\"https://stackoverflow.com/questions/50626831/how-to-set-up-two-timelines-to-one-app/50627639#50627639\">here</a> and <a href=\"https://stackoverflow.com/questions/44734430/memory-leak-in-javafx-indefinite-timeline/44838669#44838669\">here</a>.</p>\n<p>The only other thing I would point out is the use of <code>GregorianCalendar</code>. It is an old API. It is recommended that <code>LocalDate</code> or <code>LocalDateTime</code> be used.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T05:13:44.750",
"Id": "254934",
"ParentId": "254739",
"Score": "2"
}
},
{
"body": "<p>Whoever says your code is not following OOP principles should continue by explaining their opinion about the shortcomings. As I see, it's class room code and it's intention is to teach a certain thing (JavaFX I assume) so it is acceptable to skip certain OOP aspects if it makes teaching the subject matter easier. When you want to teach OOP concepts, don't mix the JavaFX in it. Doing UI code with pure OOP is quite tedious and it will consume a lot of time from the actual teaching.</p>\n<p>The code style needs some minor improvements. Technically, because the <code>ClockPane</code> is not public, it doesn't matter how it's properties are accessed as the class will not be extended, but for clarity it would be better if the property values were all set in a consistent manner, e.g. using the setter methods instead of direct access in <code>setCurrentTime()</code>.</p>\n<p>This change highlights the second problem: the scattering of <code>paintClock()</code> calls all over the class. Since <code>ClockPane</code> is not public, it makes very little sense to try to ensure the state is valid after each call since your own private code is the only thing that calls it. However, it the <code>ClockPane</code> was public, it would be better to provide a public user interface update method and document the update policy instead of forcing the clock to be painted three times if the caller tries to set the time using the setter methods.</p>\n<p>Your coments look like they are generated by a bot and they are completely redundant. :) A setter method is well known to set a value given in the name so there is no need to repeat that in the comment unless the method does something else (which it does). If you added the important part to the comments it might highlight the problem with the paint calls:</p>\n<pre><code>/**\n * Set new hour and paint the clock.\n */\n\n/**\n * Set new minute and paint the clock.\n */\n\n/**\n * Set clock pane's height and paint the clock.\n */\n\n...\n</code></pre>\n<p>Also, since you know about the single responsibility principle, the <em>and</em> words in the comments now should ring the alarm for the methods having two responsibilities.</p>\n<p>There is no need to abbreviate width and height. So use <code>getWidth()</code> instead of <code>getW()</code>.</p>\n<p>Do not use end of line comments. They are very hard to maintain and the limited space forces them to be short which reduces their usefulness.</p>\n<p>The comments should not desribe what the code does but why it is done. The code itself tells what it does in much greater detail than the comments can but the code cannot convey the reasoning for why it exists.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T05:51:36.440",
"Id": "254936",
"ParentId": "254739",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254936",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T11:42:55.160",
"Id": "254739",
"Score": "4",
"Tags": [
"java",
"javafx"
],
"Title": "Create an analogue clock interface in Java using JavaFX"
}
|
254739
|
<p>For my game engine that I'm trying to write without using STL I implemented dynamic array class(some kind of std::vector). I would like to know whether this code suits best practices. I'm also not enough knowledged about move semantics and all that stuff, so please tell if I should add them somewhere in my code. My engine does not use C++ exceptions, so <code>noexcept</code> is skipped even in places where it should be.</p>
<pre><code>#pragma once
#include "Core/Engine/Core.h"
#include "Math/MathCommon.h"
#include "Core/Container/Iterator.h"
#include <initializer_list>
namespace Hermes
{
/**
* Templated dynamic array
* Assumes that elements are reallocate-able, e.g. we don't need to call anybody when moving object in memory
* Basically that means that object MUST NOT have pointers to themselves and/or other elements of array
* NOTE : currently this implementation will never shrink allocated memory itself,
* so you have to do it manually for better memory usage
*/
template<typename ElementType>
struct TArray
{
public:
FORCEINLINE TArray() : Data(0), ElementCount(0), AllocatedCount(0)
{
}
FORCEINLINE TArray(size_t InitialCount) : Data(0), ElementCount(0), AllocatedCount(0)
{
Resize(InitialCount);
}
FORCEINLINE TArray(size_t InitialCount, const ElementType& Filler) : Data(0), ElementCount(0), AllocatedCount(0)
{
Fill(0, InitialCount, Filler);
}
FORCEINLINE TArray(const TArray<ElementType>& Other) : Data(0), ElementCount(0), AllocatedCount(0)
{
Copy(0, Other.ElementCount, Other.GetData());
}
FORCEINLINE TArray(TArray<ElementType>&& Other) : Data(Other.Data), ElementCount(Other.ElementCount), AllocatedCount(Other.AllocatedCount)
{
Other.Data = 0;
Other.ElementCount = 0;
Other.AllocatedCount = 0;
}
FORCEINLINE TArray(const std::initializer_list<ElementType>& List)
{
Copy(0, List.size(), List._First);
}
FORCEINLINE TArray(size_t Count, const ElementType* Source)
{
Copy(0, Count, Source);
}
FORCEINLINE TArray<ElementType>& operator=(const TArray<ElementType>& Other)
{
ElementCount = 0;
Copy(0, Other.ElementCount, Other.Data);
Resize(Other.ElementCount);
}
FORCEINLINE TArray<ElementType>& operator=(TArray<ElementType>&& Other)
{
MemoryOperations::Swap(ElementCount, Other.ElementCount);
MemoryOperations::Swap(AllocatedCount, Other.AllocatedCount);
MemoryOperations::Swap(Data, Other.Data);
return *this;
}
FORCEINLINE TArray<ElementType>& operator=(const std::initializer_list<ElementType> List)
{
Copy(0, List.size(), List._First);
}
FORCEINLINE ~TArray()
{
Resize(0);
}
FORCEINLINE bool RangeCheck(size_t Index) const
{
return (Index >= 0) && (Index < ElementCount);
}
FORCEINLINE ElementType* GetData()
{
return Data;
}
FORCEINLINE const ElementType* GetData() const
{
return Data;
}
FORCEINLINE ElementType& operator[](size_t Index)
{
return Data[Index];
}
FORCEINLINE const ElementType& operator[](size_t Index) const
{
return Data[Index];
}
FORCEINLINE size_t Size() const
{
return ElementCount;
}
FORCEINLINE size_t Capacity() const
{
return AllocatedCount;
}
FORCEINLINE size_t Slack() const
{
return AllocatedCount - ElementCount;
}
FORCEINLINE size_t AppendUnitialized(size_t Count)
{
size_t StartIndex = ElementCount;
Resize(ElementCount + Count);
ElementCount += Count;
return StartIndex;
}
FORCEINLINE size_t AppendDefaulted(size_t Count)
{
size_t StartIndex = AppendUnitialized(Count);
MemoryOperations::ConstructDefaultItems<ElementType>(&Data[StartIndex], Count);
return StartIndex;
}
FORCEINLINE size_t Append(const ElementType& Item, size_t Count = 1)
{
Fill(ElementCount, Count, Item);
return ElementCount;
}
FORCEINLINE size_t Append(const TArray<ElementType>& Other)
{
size_t StartIndex = ElementCount;
Copy(StartIndex, Other.ElementCount, Other.Data);
return StartIndex;
}
FORCEINLINE size_t Append(const std::initializer_list<ElementType>& List)
{
size_t StartIndex = ElementCount;
Copy(StartIndex, List.size(), List.begin());
return StartIndex;
}
FORCEINLINE size_t Append(size_t Count, const ElementType* Source)
{
size_t StartIndex = ElementCount;
Copy(StartIndex, Count, Source);
return StartIndex;
}
FORCEINLINE size_t InsertUninitialized(size_t Index, size_t Count)
{
HERMES_ASSERT(Index < ElementCount);
if (!Count) return -1;
Resize(ElementCount + Count);
Memory::Memmove(&Data[Index + Count], &Data[Index], Count * sizeof(ElementType));
ElementCount += Count;
return Index;
}
FORCEINLINE size_t InsertDefaulted(size_t Index, size_t Count)
{
InsertUninitialized(Index, Count);
MemoryOperations::ConstructDefaultItems<ElementType>(&Data[Index], Count);
return Index;
}
FORCEINLINE size_t Insert(size_t Index, const ElementType& Item, size_t Count = 1)
{
InsertUninitialized(Index, Count);
Fill(Index, Count, Item);
return Index;
}
FORCEINLINE size_t Insert(size_t Index, const TArray<ElementType&> Other)
{
InsertUninitialized(Index, Count);
Copy(Index, Count, Other.Data);
return Index;
}
FORCEINLINE size_t Insert(size_t Index, std::initializer_list<ElementType> Source)
{
InsertUninitialized(Index, Count);
Copy(Index, Source.size(), Source._First);
}
FORCEINLINE size_t Insert(size_t Index, size_t Count, const ElementType* Source)
{
InsertUninitialized(Index, Count);
Copy(Index, Count, Source);
return Index;
}
/**
* Appends elements to the end of array
*/
FORCEINLINE size_t Push(const ElementType& Item)
{
return Append(Item);
}
/**
* Appends element to the end of array constructing it with given args
*/
template<typename... ArgsType>
FORCEINLINE void Emplace(ArgsType&&... Args)
{
size_t Index = AppendUnitialized(1);
new (Data + Index) ElementType(MemoryOperations::Forward<ArgsType>(Args)...);
return Index;
}
template<typename... ArgsType>
FORCEINLINE ElementType& EmplaceAt(size_t Index, ArgsType&&... Args)
{
InsertUninitialized(Index, 1);
new (Data + Index) ElementType(MemoryOperations::Forward<ArgsType>(Args)...);
return Data[Index];
}
/**
* Returns copy of last element of array and removes it from array
*/
FORCEINLINE ElementType Pop()
{
HERMES_ASSERT(ElementCount > 0)
auto Result = Data[ElementCount - 1];
RemoveAt(ElementCount - 1);
return Result;
}
/**
* Resizes array to at least NewCount elements, but could allocate more to reduce memory fragmentation
* If NewCount < ElementCount last elements will be properly destroyed
*/
FORCEINLINE void Resize(size_t NewCount)
{
if (NewCount != AllocatedCount)
{
if (NewCount < ElementCount)
{
MemoryOperations::DestroyItems(&Data[NewCount], ElementCount - NewCount);
}
size_t EstimatedAllocationSize = sizeof(ElementType) * NewCount; //EngineGlobals::GAllocator().GetOptimalAllocationSize(sizeof(ElementType) * NewCount, alignof(ElementType));
Data = (ElementType*)realloc(Data, EstimatedAllocationSize); //EngineGlobals::GAllocator().Reallocate(Data, EstimatedAllocationSize, alignof(ElementType));
AllocatedCount = (EstimatedAllocationSize / sizeof(ElementType));
if (NewCount < ElementCount)
ElementCount = NewCount;
}
}
/**
* Destroys all elements and makes sure that array could fit at least NewCount elements
*/
FORCEINLINE void Reset(size_t NewCount)
{
Resize(NewCount);
MemoryOperations::DestroyItems(Data, NewCount);
}
/**
* Removes extra slack, although it still may exist to optimize memory allocation
*/
FORCEINLINE void Trim()
{
Resize(ElementCount);
}
/**
* Removes everything from array and leave extra slack as required
*/
FORCEINLINE void Empty(size_t ExtraSlack = 0)
{
// We need to manually destroy items placed at slack memory because Resize won't do that
MemoryOperations::DestroyItems(Data, ExtraSlack);
ElementCount = 0;
Resize(ExtraSlack);
}
FORCEINLINE void RemoveAt(size_t Index, size_t Count = 1)
{
MemoryOperations::DestroyItems(Data + Index, Count);
Memory::Memmove(Data + Index, Data + Index + Count, Count * sizeof(ElementType));
ElementCount -= Count;
}
typedef TRangedIterator<ElementType> Iterator;
typedef TRangedIterator<const ElementType> ConstIterator;
/**
* Functions required to allow this container to be used in ranged-for loops
*/
FORCEINLINE Iterator begin() { return Iterator(Data); }
FORCEINLINE Iterator end() { return Iterator(Data + ElementCount); }
FORCEINLINE ConstIterator cbegin() { return ConstIterator(Data); }
FORCEINLINE ConstIterator cend() { return ConstIterator(Data + ElementCount); }
private:
/**
* Fills range from Data[Start] to Data[Start + Count] with Filler using copy constructor
* This function properly destroys and overrides data stored at [Start; Start + Count] range and resize array if needed
*/
FORCEINLINE void Fill(size_t Start, size_t Count, const ElementType& Filler)
{
if (Start + Count > ElementCount)
Resize(Start + Count);
if (Start < ElementCount)
MemoryOperations::DestroyItems(&Data[Start], max(min(ElementCount - Start, Count), 0));
MemoryOperations::CopyConstructItem(&Data[Start], Filler, Count);
ElementCount = Math::Max(Start + Count, ElementCount);
}
/**
* Copies Count elements from Source to Data[Start]
* This function properly destroys and overrides data stored at [Start; Start + Count] range and resize array if needed
*/
FORCEINLINE void Copy(size_t Start, size_t Count, const ElementType* Source)
{
if (Start + Count > ElementCount)
Resize(Start + Count);
if (Start < ElementCount)
MemoryOperations::DestroyItems(&Data[Start], max(min(ElementCount - Start, Count), 0));
MemoryOperations::CopyConstructItems(&Data[Start], Source, Count);
ElementCount = Math::Max(Start + Count, ElementCount);
}
private:
ElementType* Data;
size_t ElementCount;
size_t AllocatedCount;
};
}
</code></pre>
<p><strong>EDIT:</strong>
Here's all header files required. I've also modified source code to use <code>realloc </code>instead of my custom-made allocator to reduce amount of source code. I know that <code>realloc</code> of 0 size and nullptr is implementation-dependent, but my implementation correctly handles it so no problems here.
<strong>Core/Engine/Core.h</strong></p>
<pre><code>#pragma once
#ifdef HERMES_PLATFORM_WINDOWS
#include <windows.h>
#define DLL_IMPORT __declspec(dllimport)
#define DLL_EXPORT __declspec(dllexport)
#define FORCEINLINE __forceinline
#define HERMES_ASSERT(Expression, ...) if (!(Expression)) DebugBreak();
#endif
#ifdef HERMES_BUILD_ENGINE
#define HERMES_API DLL_EXPORT
#define GAME_API DLL_IMPORT
#elif defined HERMES_BUILD_GAME
#define HERMES_API DLL_IMPORT
#define GAME_API DLL_EXPORT
#else
#error "Either HERMES_BUILD_ENGINE or HERMES_BUILD_GAME need to be specified"
#endif
#define CREATE_APP_INSTANCE_FUNCTION_NAME "CreateApplicationInstance"
#ifdef HERMES_PLATFORM_WINDOWS
typedef char int8 ;
typedef unsigned char uint8 ;
typedef short int int16 ;
typedef unsigned short int uint16;
typedef int int32 ;
typedef unsigned int uint32;
typedef long long int64 ;
typedef unsigned long long uint64;
typedef uint64 size_t; // We compile only 64 bit builds on Windows
#endif
</code></pre>
<p><strong>Math/MathCommon.h</strong></p>
<pre><code>#pragma once
#include "Core/Engine/Core.h"
namespace Hermes
{
namespace Math
{
// TODO : intrinsic versions
/**
* log2 for 32-bit numbers
*/
FORCEINLINE uint8 FloorLog2(uint32 Number)
{
uint32 Result = 0;
if (Number >= 1ull << 16) { Number >>= 16; Result += 16; }
if (Number >= 1ull << 8) { Number >>= 8; Result += 8; }
if (Number >= 1ull << 4) { Number >>= 4; Result += 4; }
if (Number >= 1ull << 2) { Number >>= 2; Result += 2; }
if (Number >= 1ull << 1) { Result += 1; }
return (Number == 0) ? 0 : Result;
}
/**
* log2 for 64-bit numbers
*/
FORCEINLINE uint8 FloorLog2_64(uint64 Number)
{
uint32 Result = 0;
if (Number >= 1ull << 32) { Number >>= 32; Result += 32; }
if (Number >= 1ull << 16) { Number >>= 16; Result += 16; }
if (Number >= 1ull << 8) { Number >>= 8; Result += 8; }
if (Number >= 1ull << 4) { Number >>= 4; Result += 4; }
if (Number >= 1ull << 2) { Number >>= 2; Result += 2; }
if (Number >= 1ull << 1) { Result += 1; }
return (Number == 0) ? 0 : Result;
}
FORCEINLINE bool IsPowerOf2(uint64 Number)
{
return !(Number & (Number - 1));
}
FORCEINLINE int64 CeilIntegerDivide(int64 Dividend, int64 Divisor)
{
return ((Dividend + Divisor - 1) / Divisor);
}
template<typename T>
FORCEINLINE T Max(T A, T B)
{
return (A > B ? A : B);
}
template<typename T>
FORCEINLINE T Min(T A, T B)
{
return (A < B ? A : B);
}
}
}
</code></pre>
<p><strong>Core/Container/Iterator.h</strong></p>
<pre><code>#pragma once
#include "Core/Engine/Core.h"
namespace Hermes
{
/**
* Very simple iterator that only defines functions required by ranged-for loop
*/
template<typename ElementType>
struct TRangedIterator
{
public:
FORCEINLINE TRangedIterator(ElementType* InPtr) : Ptr(InPtr) {}
FORCEINLINE bool operator!=(const TRangedIterator<ElementType>& Other) const { return Ptr != Other.Ptr; }
FORCEINLINE TRangedIterator<ElementType>& operator++() { Ptr++; return *this; }
FORCEINLINE ElementType& operator*() const { return *Ptr; }
private:
ElementType* Ptr;
};
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:53:45.163",
"Id": "502427",
"Score": "2",
"body": "Why are you writing without using the STL?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T15:52:56.413",
"Id": "502438",
"Score": "0",
"body": "@TobySpeight I do this project for learning purposes, so I try to implement as much as possible on my own. I've updated post so now everything should compile with VC, just add HERMES_PLATFORM_WINDOWS and HERMES_BUILD_GAME to preprocessor directives."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T17:22:57.850",
"Id": "502532",
"Score": "1",
"body": "I will say this `#define FORCEINLINE __forceinline` (and then using FORCEINLINE everywhere) is probably a bad idea. Forcing inline is probably going to make your code both slower and larger. The compiler is much better at deciding when to inline code than a human is (it can make intelligent decisions based on a lot of factors that could change over the lifetime of the code)."
}
] |
[
{
"body": "<h2>Overview</h2>\n<p>Couple of small bugs.</p>\n<p>You don't always seem to initialize the appropriate objects correctly. Overall I find it a bit confusing when objects are initialized and when they are not.</p>\n<p>The major missing part is that a lot of important functionality is another library and it I can check it is correct.</p>\n<p>A lot of functionality you use pass a pointer and a size. In the standard they normal use two iterators to specify ranges. I would change the functionality to match this more normal C++ patern.</p>\n<h2>Code Review</h2>\n<p>The <code>Resize()</code> is the center of this implementation so we need to look at that first to compare against where it is used.</p>\n<p>I assuming <code>MemoryOperations::DestroyItems()</code> calls the destructor on the elements in the range provided. I would note that normal arrays they will be destroyed in reverse order (you may want to implement the same way but I don't have the source to check). This reverse order of destruction will match normal object creation in that they are destroyed in reverse order of construction.</p>\n<p>I would also note this function does not resize (ElementCount does not expand) the array but rather expands the allocated size (ie the size available for the array to expand into (AllocatedCount grows). So this should really be called <code>Reserve()</code> rather than <code>Resize()</code>.</p>\n<p>We have bug in the use of <code>realloc()</code>. The standard pattern is:</p>\n<pre><code> ElementType* tmp = realloc(Data, newSize);\n if (tmp != nullptr) {\n Data = tmp;\n }\n</code></pre>\n<p>The reason to do this is because if the <code>realloc()</code> fails it will return <code>nullptr</code> and your statement above would override <code>Data</code> thus leaking the original value.</p>\n<pre><code> void Resize(size_t NewCount)\n {\n // I would do less (<) than rather than not euqal (!=)\n // That way if the allocation is smaller than the current size\n // you don't waste time making the size smaller.\n //\n // Though you use this for the destructor and need this feature.\n // I would change this behavior (to avoid smaller resizes) and\n // have an explicit function to deallocate that can be used by\n // the destructor.\n if (NewCount != AllocatedCount)\n {\n if (NewCount < ElementCount)\n {\n // Assume this calls the destructor.\n MemoryOperations::DestroyItems(&Data[NewCount], ElementCount - NewCount);\n }\n size_t EstimatedAllocationSize = sizeof(ElementType) * NewCount; //EngineGlobals::GAllocator().GetOptimalAllocationSize(sizeof(ElementType) * NewCount, alignof(ElementType));\n\n // This is a BUG see above.\n Data = (ElementType*)realloc(Data, EstimatedAllocationSize); //EngineGlobals::GAllocator().Reallocate(Data, EstimatedAllocationSize, alignof(ElementType));\n AllocatedCount = (EstimatedAllocationSize / sizeof(ElementType));\n if (NewCount < ElementCount)\n ElementCount = NewCount;\n }\n }\n</code></pre>\n<hr />\n<p>This is a BUG:</p>\n<p>This Allocates the space for <code>InitialCount</code> values. But none of these values are initialized. So anything that uses a constructor now has UB.</p>\n<pre><code> FORCEINLINE TArray(size_t InitialCount) : Data(0), ElementCount(0), AllocatedCount(0)\n {\n Resize(InitialCount);\n // Maybe this should be:\n Fill(0, InitialCount, ElementType{}); // Fill with a default value.\n }\n</code></pre>\n<hr />\n<p>This constructor is basically the same as the one above. The difference is that you provide a default value to fill the array with. You can collapse the two constructors by defaulting the <code>Filler</code> parameter`.</p>\n<pre><code> FORCEINLINE TArray(size_t InitialCount, const ElementType& Filler) : Data(0), ElementCount(0), AllocatedCount(0)\n {\n Fill(0, InitialCount, Filler);\n }\n</code></pre>\n<hr />\n<p>This is usually implemented by simply calling swap. But this works as well.</p>\n<pre><code> FORCEINLINE TArray(TArray<ElementType>&& Other) : Data(Other.Data), ElementCount(Other.ElementCount), AllocatedCount(Other.AllocatedCount)\n {\n Other.Data = 0;\n Other.ElementCount = 0;\n Other.AllocatedCount = 0;\n }\n</code></pre>\n<hr />\n<p>The type <code>initializer_list</code> does not have a member <code>_First</code>. If this compiles you must be using a non-standard implementation of the standard library.</p>\n<pre><code> FORCEINLINE TArray(const std::initializer_list<ElementType>& List)\n {\n Copy(0, List.size(), List._First);\n }\n</code></pre>\n<hr />\n<p>The previous constructor and this constructor could be collapsed into a single constructor that takes iterators (which is the standard pattern in C++, rather than pointer to first and length).</p>\n<pre><code> FORCEINLINE TArray(size_t Count, const ElementType* Source)\n {\n Copy(0, Count, Source);\n }\n</code></pre>\n<hr />\n<p>I would note that <code>Index</code> can never be smaller than zero (its unsigned).</p>\n<pre><code> FORCEINLINE bool RangeCheck(size_t Index) const\n {\n return (Index >= 0) && (Index < ElementCount);\n }\n</code></pre>\n<p>This sort of suggests you are not checking the warnings (or you don't have warnings set high enough). You should fix all warnings they are errors in your logical thinking.</p>\n<hr />\n<p>Don't like this.<br />\nYou are exposing the internal data.</p>\n<pre><code> FORCEINLINE ElementType* GetData()\n FORCEINLINE const ElementType* GetData() const\n</code></pre>\n<hr />\n<p>Interesting Name :-)</p>\n<pre><code> FORCEINLINE size_t Slack() const\n</code></pre>\n<hr />\n<p>Can't tell if this works.<br />\nI am assuming you know how placement new works.</p>\n<pre><code> FORCEINLINE size_t AppendDefaulted(size_t Count)\n {\n size_t StartIndex = AppendUnitialized(Count);\n //\n // I assumes this uses the placement new to construct\n // the elements into uninitialized memory.\n MemoryOperations::ConstructDefaultItems<ElementType>(&Data[StartIndex], Count);\n return StartIndex;\n }\n</code></pre>\n<hr />\n<p>Probable Bug.</p>\n<p>I can't tell if this works because the interesting part is in <code>Memory::Memmove()</code>!</p>\n<p>But you can't do a simple move on objects that have constructors/destructors. You must make sure that the appropriate methods are called. Things that use resources will potential break if you simply copy them.</p>\n<pre><code> FORCEINLINE size_t InsertUninitialized(size_t Index, size_t Count)\n {\n HERMES_ASSERT(Index < ElementCount);\n if (!Count) return -1;\n Resize(ElementCount + Count);\n Memory::Memmove(&Data[Index + Count], &Data[Index], Count * sizeof(ElementType));\n ElementCount += Count;\n return Index;\n }\n</code></pre>\n<hr />\n<p>Not sure I understand this:</p>\n<p>Do you just add a bunch of uninitalized elements then only initialize one?</p>\n<pre><code> template<typename... ArgsType>\n FORCEINLINE ElementType& EmplaceAt(size_t Index, ArgsType&&... Args)\n {\n InsertUninitialized(Index, 1);\n new (Data + Index) ElementType(MemoryOperations::Forward<ArgsType>(Args)...);\n return Data[Index];\n }\n</code></pre>\n<hr />\n<p>The standard library splits this function into two parts. A top() which returns a reference to the last value and a pop() which removes the top value (but does not return anything).</p>\n<p>This is because it is more efficient. Your causes multiple copies.</p>\n<pre><code> FORCEINLINE ElementType Pop()\n {\n HERMES_ASSERT(ElementCount > 0)\n auto Result = Data[ElementCount - 1];\n RemoveAt(ElementCount - 1);\n return Result;\n }\n</code></pre>\n<hr />\n<p>This is normally called <code>clear()</code>.</p>\n<pre><code> FORCEINLINE void Empty(size_t ExtraSlack = 0)\n</code></pre>\n<hr />\n<p>Can't use move on objects that have constructors.</p>\n<pre><code> FORCEINLINE void RemoveAt(size_t Index, size_t Count = 1)\n {\n MemoryOperations::DestroyItems(Data + Index, Count);\n Memory::Memmove(Data + Index, Data + Index + Count, Count * sizeof(ElementType));\n ElementCount -= Count;\n }\n</code></pre>\n<hr />\n<p>Good.<br />\nBut what about a const version of the object.</p>\n<pre><code> FORCEINLINE Iterator begin() { return Iterator(Data); }\n FORCEINLINE Iterator end() { return Iterator(Data + ElementCount); }\n\n FORCEINLINE ConstIterator cbegin() { return ConstIterator(Data); }\n FORCEINLINE ConstIterator cend() { return ConstIterator(Data + ElementCount); }\n</code></pre>\n<p>I would add this:</p>\n<pre><code> FORCEINLINE ConstIterator begin() const { return ConstIterator(Data); }\n FORCEINLINE ConstIterator end() const { return ConstIterator(Data + ElementCount); }\n</code></pre>\n<hr />\n<p>Self Plug: I wrote a lot about this here:</p>\n<p><a href=\"https://lokiastari.com/series/\" rel=\"nofollow noreferrer\">https://lokiastari.com/series/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T01:52:21.423",
"Id": "254774",
"ParentId": "254740",
"Score": "3"
}
},
{
"body": "<p>There's absolutely no reason to make this code platform-specific.</p>\n<p>Instead of guessing the size of the fundamental types, just use the standard types from the compiler-provided <code><cstdint></code> (we should only need <code>std::size_t</code>, I think). The whole reason that this header is provided is so we have a portable means of using information that the compiler knows much better than the programmer.</p>\n<p>The ugly <code>dllspec</code> stuff that sensible platforms don't need should all be conditional on a platform-provided macro (I think it's <code>#ifdef _WIN32</code>, but double-check that as I've never written any Windows-specific code).</p>\n<p>If you can't trust your compiler to decide when it should inline functions, then switch to a better one.</p>\n<p>Even if you want to implement your own log₂ function, don't do this:</p>\n<blockquote>\n<pre><code> FORCEINLINE uint8 FloorLog2(uint32 Number)\n FORCEINLINE uint8 FloorLog2_64(uint64 Number)\n</code></pre>\n</blockquote>\n<p>C++ has function overloading so that we don't have to change every function call when we change the type of a variable. And there are much faster and simpler implementations of this function.</p>\n<p>Not that any of this is used anywhere, so simpler just to remove it until/unless there's a need. It seems that the only thing used from the MathCommon header is <code>Max()</code>, which is so trivial that it could be added (with <code>static</code> linkage) directly into the Vector header, and not drag all of MathCommon into every program that uses Vector. I'd still recommend using <code>std::max()</code> unless you've done something so terrible in your life that you need a penance.</p>\n<p>The naming style looks alien - in C++, we normally use lower case for namespace and function names, Title Case for aggregate type names and template parameters, and UPPER CASE for macros (only).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T17:20:11.613",
"Id": "502531",
"Score": "1",
"body": "Forgot to mention the naming of functions. That bugged me the most."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T08:59:04.427",
"Id": "254787",
"ParentId": "254740",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254774",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:20:14.200",
"Id": "254740",
"Score": "3",
"Tags": [
"c++",
"array",
"reinventing-the-wheel",
"windows",
"vectors"
],
"Title": "Implementing dynamic array without STL"
}
|
254740
|
<p>I tried to create a .Net core API using Microsoft Documentation but I ran into some issues.</p>
<p>The app is working but only for a "single" table. The includes are empty.</p>
<pre><code> var contact = await _context.Contacts
.Include(c => c.ContactSkills)
.ThenInclude(cs => cs.Skill)
.AsNoTracking()
.FirstOrDefaultAsync(m => m.Id == id);
</code></pre>
<p>Also the Swagger documentation is not generating, I tried the attributes and swapping some settings but didn't managed to make it work.</p>
<p>Here's my repo git : <a href="https://github.com/AnthonyDaSilvaFe/OpenWebChallenge.API" rel="nofollow noreferrer">https://github.com/AnthonyDaSilvaFe/OpenWebChallenge.API</a></p>
<p>Any ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:35:43.110",
"Id": "502421",
"Score": "1",
"body": "Welcome to the Code Review Community, questions about code that is not working are off-topic on code review. Please read [How do I ask a good questio?](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:39:59.183",
"Id": "502423",
"Score": "0",
"body": "What do you mean \" for a \"single\" table\". Could you please explain what is not working properly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:44:25.407",
"Id": "502424",
"Score": "1",
"body": "Welcome to Code Review.I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T13:01:03.953",
"Id": "502430",
"Score": "0",
"body": "Sorry, I asked the question on stackoverflow with code sample and examples and people told me to come here for code review. So I guess I'll close both questions and stays with my problem ^^"
}
] |
[
{
"body": "<p>Your EF context is not properly configured. It doesn't have any primary keys and doesn't have any relations. EF doesn't work at all without primary keys or if you don't need them you have to include "NoPrimaryKey" statement. And no any query will run properly if your relations are not configured. You have to change your code to this:</p>\n<p>The class ContactSkill should show what table are foreign keys of:</p>\n<pre><code>public class ContactSkill\n{\n [Key]\n public int Id { get; set; }\n\n public int ContactId { get; set; }\n\n [ForeignKey(nameof(ContactId))]\n [InverseProperty(nameof(ContactSkill.Contact.ContactSkills))]\n public virtual Contact Contact { get; set; }\n\n public int SkillId { get; set; }\n\n [ForeignKey(nameof(SkillId))]\n [InverseProperty(nameof(ContactSkill.Contact.ContactSkills))]\n public virtual Skill Skill { get; set; }\n}\n</code></pre>\n<p>And configure many-to-many relations in if fluent-api EF core context:</p>\n<pre><code>public class ApiContext : DbContext\n{\n public ApiContext()\n {\n }\n\n public ApiContext(DbContextOptions<ApiContext> options)\n : base(options)\n {\n }\n public DbSet<Contact> Contacts { get; set; }\n public DbSet<Skill> Skills { get; set; }\n public DbSet<ContactSkill> ContactSkills { get; set; }\n\n protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)\n {\n if (!optionsBuilder.IsConfigured)\n {\n }\n\n }\n protected override void OnModelCreating(ModelBuilder modelBuilder)\n {\n modelBuilder.Entity<ContactSkill>(entity =>\n {\n entity.HasOne(d => d.Contact)\n .WithMany(p => p.ContactSkills)\n .HasForeignKey(d => d.ContactId)\n .OnDelete(DeleteBehavior.ClientSetNull)\n .HasConstraintName("FK_ContactSkill_Contact");\n\n entity.HasOne(d => d.Skill)\n .WithMany(p => p.ContactSkills)\n .HasForeignKey(d => d.SkillId)\n .HasConstraintName("FK_ContactSkill_Skill");\n });\n\n }\n</code></pre>\n<p>The class Contact should include primary key attribute and virual collection of ContactSkills:</p>\n<pre><code>public class Contact\n{\n public Contact()\n {\n ContactSkills = new HashSet<ContactSkill>();\n }\n [Key]\n public int Id { get; set; }\n [Required]\n public string LastName { get; set; }\n [Required]\n public string FirstName { get; set; }\n \n public string FullName { get; set; }\n public string Address { get; set; }\n public string Email { get; set; }\n public string MobilePhoneNumber { get; set; }\n [InverseProperty(nameof(ContactSkill.Contact))]\n public virtual ICollection<ContactSkill> ContactSkills { get; set; }\n}\n</code></pre>\n<p>The class Skill should include primary key attribute and virual collection of ContactSkills:</p>\n<pre><code>public class Skill\n{\n public Skill()\n {\n ContactSkills = new HashSet<ContactSkill>();\n }\n [Required]\n public int Id { get; set; }\n [Required]\n public string Name { get; set; }\n public int ExpertiseLevel { get; set; }\n [InverseProperty(nameof(ContactSkill.Skill))]\n public virtual ICollection<ContactSkill> ContactSkills { get; set; }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T13:36:05.473",
"Id": "502432",
"Score": "2",
"body": "Welcome to Code Review. Please refuse to answer off-topic questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T14:43:20.293",
"Id": "502434",
"Score": "0",
"body": "Thanks @Sergey will try asap. Sorry for breaking the rules of the forum ^^\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T13:29:06.333",
"Id": "254744",
"ParentId": "254742",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "254744",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T12:27:23.373",
"Id": "254742",
"Score": "-3",
"Tags": [
"asp.net-core",
"entity-framework-core"
],
"Title": "Swagger doc and Entity Framework include not working"
}
|
254742
|
<p>I have different function for different task below this function. To reduce the code, I have written following function.</p>
<p>Is this the best way to apply OOPs? or any better way to do?</p>
<p>Function</p>
<pre><code>def ML_algorithm(algo_name, y_train, y_test, y_pred_algoname, y_predtest_algoname):
print(algo_name)
print()
err=mean_squared_error(y_train, y_pred_algoname)
print("RMSE TRAIN : "+str(np.sqrt(err)))
err=mean_squared_error(y_test, y_predtest_algoname)
print("RMSE TEST : "+str(np.sqrt(err)))
err=explained_variance_score(y_train, y_pred_algoname)
print("EXPLAINED VARIANCE TRAIN : "+str(err))
err=explained_variance_score(y_test, y_predtest_algoname)
print("EXPLAINED VARIANCE TEST : "+str(err))
err=r2_score(y_train,y_pred_algoname)
print("R2 TRAIN : "+str(err))
err=r2_score(y_test,y_predtest_algoname)
print("R2 TEST : "+str(err))
print()
print()
</code></pre>
<p>Actual code</p>
<pre><code>print("LINEAR REGRESSION")
print()
err=mean_squared_error(y_train, y_predlr)
print("RMSE TRAIN : "+str(np.sqrt(err)))
err=mean_squared_error(y_test, y_predtestlr)
print("RMSE TEST : "+str(np.sqrt(err)))
err=explained_variance_score(y_train, y_predlr)
print("EXPLAINED VARIANCE TRAIN : "+str(err))
err=explained_variance_score(y_test, y_predtestlr)
print("EXPLAINED VARIANCE TEST : "+str(err))
err=r2_score(y_train,y_predlr)
print("R2 TRAIN : "+str(err))
err=r2_score(y_test,y_predtestlr)
print("R2 TEST : "+str(err))
print()
print()
print("RANDOM FOREST REGRESSION")
print()
err=mean_squared_error(y_train, y_predrfr)
print("RMSE TRAIN : "+str(np.sqrt(err)))
err=mean_squared_error(y_test, y_predrfrtest)
print("RMSE TEST : "+str(np.sqrt(err)))
err=explained_variance_score(y_train, y_predrfr)
print("EXPLAINED VARIANCE TRAIN : "+str(err))
err=explained_variance_score(y_test, y_predrfrtest)
print("EXPLAINED VARIANCE TEST : "+str(err))
err=r2_score(y_train, y_predrfr)
print("R2 TRAIN : "+str(err))
err=r2_score(y_test, y_predrfrtest)
print("R2 TEST : "+str(err))
print()
print()
print("RANDOM FOREST REGRESSION 2")
print()
err=mean_squared_error(y_train, y_predrfr2)
print("RMSE TRAIN : "+str(np.sqrt(err)))
err=mean_squared_error(y_test, y_predrfr2test)
print("RMSE TEST : "+str(np.sqrt(err)))
err=explained_variance_score(y_train, y_predrfr2)
print("EXPLAINED VARIANCE TRAIN : "+str(err))
err=explained_variance_score(y_test, y_predrfr2test)
print("EXPLAINED VARIANCE TEST : "+str(err))
err=r2_score(y_train, y_predrfr2)
print("R2 TRAIN : "+str(err))
err=r2_score(y_test, y_predrfr2test)
print("R2 TEST : "+str(err))
print()
print()
print("XGBOOST")
print()
err=mean_squared_error(y_train, y_predxgb)
print("RMSE TRAIN : "+str(np.sqrt(err)))
err=mean_squared_error(y_test, y_predxgbtest)
print("RMSE TEST : "+str(np.sqrt(err)))
err=explained_variance_score(y_train, y_predxgb)
print("EXPLAINED VARIANCE TRAIN : "+str(err))
err=explained_variance_score(y_test, y_predxgbtest)
print("EXPLAINED VARIANCE TEST : "+str(err))
err=r2_score(y_train, y_predxgb)
print("R2 TRAIN : "+str(err))
err=r2_score(y_test, y_predxgbtest)
print("R2 TEST : "+str(err))
print()
print()
print("SVM")
print()
err=mean_squared_error(y_train, ypredsvm)
print("RMSE TRAIN : "+str(np.sqrt(err)))
err=mean_squared_error(y_test, ypredsvmtest)
print("RMSE TEST : "+str(np.sqrt(err)))
err=explained_variance_score(y_train, ypredsvm)
print("EXPLAINED VARIANCE TRAIN : "+str(err))
err=explained_variance_score(y_test, ypredsvmtest)
print("EXPLAINED VARIANCE TEST : "+str(err))
err=r2_score(y_train, ypredsvm)
print("R2 TRAIN : "+str(err))
err=r2_score(y_test, ypredsvmtest)
print("R2 TEST : "+str(err))
print()
print()
print("Bayesian")
print()
err=mean_squared_error(y_train, ypredbayesian)
print("RMSE TRAIN : "+str(np.sqrt(err)))
err=mean_squared_error(y_test, ypredbayesiantest)
print("RMSE TEST : "+str(np.sqrt(err)))
err=explained_variance_score(y_train, ypredbayesian)
print("EXPLAINED VARIANCE TRAIN : "+str(err))
err=explained_variance_score(y_test, ypredbayesiantest)
print("EXPLAINED VARIANCE TEST : "+str(err))
err=r2_score(y_train, ypredbayesian)
print("R2 TRAIN : "+str(err))
err=r2_score(y_test, ypredbayesiantest)
print("R2 TEST : "+str(err))
print()
print()
print("SGD")
print()
err=mean_squared_error(y_train, ypredsgd)
print("RMSE TRAIN : "+str(np.sqrt(err)))
err=mean_squared_error(y_test, ypredsgdtest)
print("RMSE TEST : "+str(np.sqrt(err)))
err=explained_variance_score(y_train, ypredsgd)
print("EXPLAINED VARIANCE TRAIN : "+str(err))
err=explained_variance_score(y_test, ypredsgdtest)
print("EXPLAINED VARIANCE TEST : "+str(err))
err=r2_score(y_train, ypredsgd)
print("R2 TRAIN : "+str(err))
err=r2_score(y_test, ypredsgdtest)
print("R2 TEST : "+str(err))
print()
print()
print("Decision Tree")
print()
err=mean_squared_error(y_train, ypreddectree)
print("RMSE TRAIN : "+str(np.sqrt(err)))
err=mean_squared_error(y_test, ypreddectreetest)
print("RMSE TEST : "+str(np.sqrt(err)))
err=explained_variance_score(y_train, ypreddectree)
print("EXPLAINED VARIANCE TRAIN : "+str(err))
err=explained_variance_score(y_test, ypreddectreetest)
print("EXPLAINED VARIANCE TEST : "+str(err))
err=r2_score(y_train, ypreddectree)
print("R2 TRAIN : "+str(err))
err=r2_score(y_test, ypreddectreetest)
print("R2 TEST : "+str(err))
print()
print()
print("Neural Network")
print()
err=mean_squared_error(y_train, ypredneural)
print("RMSE TRAIN : "+str(np.sqrt(err)))
err=mean_squared_error(y_test, ypredneuraltest)
print("RMSE TEST : "+str(np.sqrt(err)))
err=explained_variance_score(y_train, ypredneural)
print("EXPLAINED VARIANCE TRAIN : "+str(err))
err=explained_variance_score(y_test, ypredneuraltest)
print("EXPLAINED VARIANCE TEST : "+str(err))
err=r2_score(y_train, ypredneural)
print("R2 TRAIN : "+str(err))
err=r2_score(y_test, ypredneuraltest)
print("R2 TEST : "+str(err))
print()
print()
print("Lasso")
print()
err=mean_squared_error(y_train, ypredlaso)
print("RMSE TRAIN : "+str(np.sqrt(err)))
err=mean_squared_error(y_test, ypredlasotest)
print("RMSE TEST : "+str(np.sqrt(err)))
err=explained_variance_score(y_train, ypredlaso)
print("EXPLAINED VARIANCE TRAIN : "+str(err))
err=explained_variance_score(y_test, ypredlasotest)
print("EXPLAINED VARIANCE TEST : "+str(err))
err=r2_score(y_train, ypredlaso)
print("R2 TRAIN : "+str(err))
err=r2_score(y_test, ypredlasotest)
print("R2 TEST : "+str(err))
print()
print()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T17:27:47.163",
"Id": "502448",
"Score": "3",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T12:42:07.230",
"Id": "502516",
"Score": "1",
"body": "What exactly does your code do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T19:12:25.917",
"Id": "502658",
"Score": "0",
"body": "Next time, please add a description of what the code is supposed to be doing to the question."
}
] |
[
{
"body": "<p>I would add some iteration to this, to reduce parts where you repeat yourself. Note that there are two things changing, the statistic you output (and its name) and whether you show it with the train or test results. The former is always constant, while the latter depends on your results, so I would pull the former into a global constant and build the latter within the function. Something like this:</p>\n<pre><code>STATISTICS = {"RMSE": sqrt_mean_squared_error,\n "EXPLAINED_VARIANCE": explained_variance_score,\n "R2": r2_score}\n\ndef sqrt_mean_squared_error(x):\n return np.sqrt(mean_squared_error(x))\n\ndef print_performance(algo_name, y_train, y_test, y_train_pred, y_test_pred):\n print(algo_name + '\\n')\n results = [("TRAIN", y_train, y_train_pred),\n ("TEST", y_test, y_test_pred)]\n for stat_name, stat in STATISTICS.items():\n for name, y, y_pred in results:\n print(f"{stat_name} {name} : {stat(y, y_pred)}")\n print('\\n')\n</code></pre>\n<p>Note that I used an f-string to concisely output, which in this case is equivalent to:</p>\n<pre><code>print(stat_name, name, ":", stat(y, y_pred))\n</code></pre>\n<p>Also, Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, recommends using four spaces as indentation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T07:08:31.687",
"Id": "502495",
"Score": "0",
"body": "thanks, very helpful"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T16:18:19.973",
"Id": "254755",
"ParentId": "254745",
"Score": "3"
}
},
{
"body": "<p>The thing you're doing isn't OOP (object-oriented programming), and that's probably ok. OOP is just one way of structuring complicated programs, and I don't personally like the pure form of it much anyway.</p>\n<p>Your idea of making a function to handle repetitive code is good, but you're still basically writing imperative code. The function you've <code>def</code>ined is a good example of what used to be called a <em>"subroutine"</em>; you can still make it into a <em>"function"</em>.</p>\n<ul>\n<li>Functions take arguments and <code>return</code> something that depended on those arguments.</li>\n<li>In their <em>pure</em> form they <em>don't do anything else</em>. As you'll see, there's a lot of room for grey here.</li>\n<li>Ideally, it should only be "possible" to call a function with <em>valid</em> arguments. (Scare quotes because this is python, which is basically php in a fancy suite.)</li>\n<li>Handle printing separately from computation. You're going to violate this all the time while you troubleshoot stuff, but remember to clean up after yourself.</li>\n<li>There's just plain a lot of detailed language features in any good language that can help you write better. Keep learning</li>\n</ul>\n<p>I'm using <code>NamedTuple</code> below because I haven't gotten around to learning the ins&outs of <code>dataclass</code>s yet, but I understand <code>dataclass</code> is actually better for most situations. <code>NamedTuple</code> requires introducing some type-hints, which are <em>good</em>, but which <em>only do anything if</em> you're using a type-checker like <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\">mypy</a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import NamedTuple\n\nclass ErrorScores(NamedTuple):\n root_mean_square: float # I assume?\n explained_variance: float\n r2: float\n\ndef error_scores(data, predicate):\n return ErrorScores(\n root_mean_square=np.sqrt(mean_squared_error(data, predicate)),\n explained_variance=explained_variance_score(data, predicate),\n r2=r2_score(data, predicate)\n )\n\nclass Algorithm(NamedTuple):\n name: str # I'm just assuming these are strings, IDK\n predicate_name: str\n predicate_test_name: str\n\n# There are a lot of variables here that IDK where they're coming from. It's suspiciously repetitive. \nLINEAR_REGRESSION = Algorithm("LINEAR REGRESSION", y_predlr, y_predtestlr)\nRANDOM_FOREST_REGRESSION = Algorithm("RANDOM FOREST REGRESSION", y_predrfr, y_predrfrtest)\nRANDOM_FOREST_REGRESSION 2 = Algorithm("RANDOM FOREST REGRESSION 2", y_predrfr2, y_predrfr2test)\nXGBOOST = Algorithm("XGBOOST", y_predxgb, y_predxgbtest)\nSVM = Algorithm("SVM", ypredsvm, ypredsvmtest)\nBAYESIAN = Algorithm("Bayesian", ypredbayesian, ypredbayesiantest)\nSGD = Algorithm("SGD", ypredsgd, ypredsgdtest)\nDECISION_TREE = Algorithm("Decision Tree", ypreddectree, ypreddectreetest)\nNEURAL_NETWORK = Algorithm("Neural Network", ypredneural, ypredneuraltest)\nLASSO = Algorithm("Lasso", ypredlaso, ypredlasotest)\n\ndef print_errors(algorithm: Algorithm, y_train, y_test):\n training_errors = error_scores(y_train, algorithm.predicate_name)\n testing_errors = error_scores(y_test, algorithm.predicate_test_name)\n print('\\n'.join((\n f'{algorithm.name}',\n f'RMSE TRAIN : {training_errors.root_mean_square}',\n f'RMSE TEST : {testing_errors.root_mean_square}',\n f'EXPLAINED VARIANCE TRAIN : {training_errors.explained_variance}',\n f'EXPLAINED VARIANCE TEST : {testing_errors.explained_variance}',\n f'R2 TRAIN : {training_errors.r2}',\n f'R2 TEST : {testing_errors.r2}'\n )))\n\ndef print_errors_for_all(y_train, y_test):\n algorithms = (LINEAR_REGRESSION,\n RANDOM_FOREST_REGRESSION,\n RANDOM_FOREST_REGRESSION_2,\n XGBOOST,\n SVM,\n BAYESIAN,\n SGD,\n DECISION_TREE,\n NEURAL_NETWORK,\n LASSO)\n for algorithm in algorithms:\n print_errors(algorithm, y_train, y_test)\n</code></pre>\n<p>Without knowing the surrounding context, this is probably good enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T07:08:00.570",
"Id": "502494",
"Score": "0",
"body": "Thanks @shapeofmatter very appreciated"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T20:46:38.030",
"Id": "254765",
"ParentId": "254745",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T13:41:20.903",
"Id": "254745",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"classes"
],
"Title": "How to convert traditional code to reusable function"
}
|
254745
|
<p>I've been searching for methods to convert a bitarray into integer. Now I'm using this code:</p>
<pre><code>def bin2int(bin_array):
int_ = 0
for bit in bin_array:
int_ = (int_ << 1) | bit
return int_
</code></pre>
<p>where bin_array is a bitarray randomly filled.
I'm curios about other methods that you know of, like functions from bitarray or numpy...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T16:36:33.473",
"Id": "502444",
"Score": "2",
"body": "Just out of interest: how do you know that this is the *quickest* way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T20:43:58.307",
"Id": "502546",
"Score": "0",
"body": "I don't, that's the point"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T23:05:27.490",
"Id": "502554",
"Score": "0",
"body": "Ah, in that case the title shouldn't make that claim. I've edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T02:11:56.933",
"Id": "502559",
"Score": "0",
"body": "Here's a numpy version https://stackoverflow.com/questions/49791312/numpy-packbits-pack-to-uint16-array"
}
] |
[
{
"body": "<p>There is a method in <a href=\"https://github.com/ilanschnell/bitarray#functions-defined-in-bitarrayutil-module\" rel=\"nofollow noreferrer\">bitarray.util</a> called <code>ba2int</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from bitarray import bitarray\nfrom bitarray.util import ba2int\n\nba = bitarray('1001') # 9\n\ni = ba2int(ba)\n\nprint(f'Value: {i} type: {type(i)}')\n# Output: Value: 9 type: <class 'int'>\n</code></pre>\n<p>From the doc:</p>\n<blockquote>\n<p>ba2int(bitarray, /, signed=False) -> int</p>\n<p>Convert the given bitarray into an integer. The bit-endianness of the\nbitarray is respected. signed indicates whether two's complement is\nused to represent the integer.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T15:29:53.870",
"Id": "254750",
"ParentId": "254746",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T14:06:00.433",
"Id": "254746",
"Score": "1",
"Tags": [
"python"
],
"Title": "Convert a bitarray to integer in Python"
}
|
254746
|
<p>Assume we are given a <code>number</code> and a <strong>prime</strong> <code>p</code>. The goal is to count all <em>subnumbers</em> of <code>number</code> that are divisible by <code>p</code>. A <em>subnumber</em> of <code>number</code> is formed of any number of consecutive digits in the decimal representation of <code>number</code>.</p>
<p>Following answers to <a href="https://codereview.stackexchange.com/questions/252811/counting-subnumbers-divisible-by-a-given-prime">my first question</a> about code to solve this problem, I improved my code as follows:</p>
<pre><code>from collections import Counter
number = input()
p = int(input())
ans = 0
if p != 2 and p != 5:
res = (int(number[i:]) % p for i in range(len(number)))
C = Counter(res)
for c in C:
if c == 0:
ans += (C[c] * (C[c] + 1)) // 2
else:
ans += ((C[c] - 1) * C[c]) // 2
elif p == 2:
for i in range(len(number)):
if number[i] in ('0', '2', '4', '6', '8'):
ans += i + 1
else:
for i in range(len(number)):
if number[i] in ('0', '5'):
ans += i + 1
print(ans)
</code></pre>
<p>Now, it passes more tests but yet there are several tests with <em>time limit exceeded</em> error.</p>
<p>Can this new solution be made faster?</p>
|
[] |
[
{
"body": "<p>It is a bit weird to have two special cases and start with the case that it is neither of those. I would re-arrange your cases to</p>\n<pre><code>if p == 2:\n ...\nelif p == 5:\n ...\nelse:\n ...\n</code></pre>\n<p>Unless you did this as a performance improvement, because a random prime is much more likely to be neither 2 nor 5, but in that case you should have some measurements to show that this is not a premature optimization and probably add a comment in the code.</p>\n<hr />\n<p>If you iterate over something and need both the index and the value, use <code>enumerate</code>:</p>\n<pre><code>if p == 2:\n ans = sum(i for i, digit in enumerate(number, 1)\n if digit in {'0', '2', '4', '6', '8'})\nelif p == 5:\n ans = sum(i for i, digit in enumerate(number, 1)\n if digit in {'0', '5'})\n</code></pre>\n<p>Note that I used the second (optional) argument of <code>enumerate</code> to start counting at one and I used a <code>set</code> instead of a tuple, because it has faster membership test (not a lot faster for small collections as this, but measurably faster). I also put it all into a generator expression and used <code>sum</code>.</p>\n<hr />\n<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which recommends using <code>lower_case</code> for variables, so your counter should be called <code>c</code>, or better yet, something readable like <code>digit_count</code>. You can also factor out the <code>0</code> case to avoid having to check for it up to nine times:</p>\n<pre><code>else:\n slices = (int(number[i:]) % p for i in range(len(number)))\n digit_count = Counter(slices)\n\n # get the count of zeroes, with a default value of zero\n zeroes = digit_count.pop(0, 0) \n ans = (zeroes * (zeroes + 1)) // 2 \n ans += sum((count * (count - 1)) // 2\n for count in digit_counts.values())\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T15:55:55.457",
"Id": "254751",
"ParentId": "254749",
"Score": "4"
}
},
{
"body": "<p>If you say you get a 'time limit exceeded' message it would be interesting how large the string and the prime number and the time limit is. It seems that the prime is about <span class=\"math-container\">\\$10^9\\$</span> , the string length is about <span class=\"math-container\">\\$10^6\\$</span> and the time limit is about 2 seconds. You should use a <a href=\"https://docs.python.org/3/library/profile.html\" rel=\"nofollow noreferrer\">profiler</a> to find out where you spent the time in your program. I did this for a string of length <span class=\"math-container\">\\$10^4\\$</span> . The program took about 11 seconds on my notebook and almost all of the time is spent for the calculation of <code>res</code>. The loop is executed <span class=\"math-container\">\\$10^4\\$</span> times, so each calculation took about 1 ms. What is done during this millisecond? From the string of length <span class=\"math-container\">\\$10^4\\$</span> a substring most of the time of length <span class=\"math-container\">\\$10^4\\$</span> is taken and converted to an integer. This <span class=\"math-container\">\\$10^4\\$</span> digit integer is divided by p to get the residue.</p>\n<p>Can the performance of such a step be improved by using the results of a previous step?</p>\n<p>Yes, I think so. The new substring differs from the old substring only by one character.\nSo you have to convert only this one character to integer. The new residuum can be calculated now based on this number and the previously calculated values like the previous residue.</p>\n<p>If you need the powers of <span class=\"math-container\">\\$10^i\\$</span> in your calculation modulo p you should keep them reduced modulo p, otherwise they will become rather big (<span class=\"math-container\">\\$10^6\\$</span> digit integers)</p>\n<p>So the following is bad because you calculate with 1000000-digit numbers</p>\n<pre><code>p= some prime number of size (not length) 10**9\npower=1\nfor _ in range(10**6):\n power=10*power\nresult=power % p\n</code></pre>\n<p>This one is much much better:</p>\n<pre><code>p= some prime number of size (not length) 10**9\npower=1\nfor _ in range(10**6):\n power=(10*power)%p\nresult=power % p\n</code></pre>\n<p>because you calculate with 9-digit numbers</p>\n<p>you can always measure the time your code needs with time.time</p>\n<pre><code>import time\nstarttime=time.time()\n\nmy code \n\nendtime=time.time()\nprint(endtime-starttime)\n</code></pre>\n<p>You will see the difference in the previous examples with the loops.</p>\n<p>To testthe performance of the code one needs a 9-digit prime number and a <span class=\"math-container\">\\$10^6\\$</span> digit string.</p>\n<pre><code>p=623456849\nrandom.seed(12345678)\nnumber=''.join(random.choices(string.digits, k=10**6))\n</code></pre>\n<p>The <code>random.seed</code> command guarantees that always the sam string is generated. The prime number p is from the internet. But for p one can use an arbitrary number that is not divisible by 2 or 5.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T13:10:02.073",
"Id": "502614",
"Score": "0",
"body": "Thank you. But the problem is that for the \\$i\\$-th step, the program should calculate `10**i `+previous residue and here, `i` is about \\$ 10^{6}\\$. Doesn't this take a long time?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T13:11:26.393",
"Id": "502616",
"Score": "0",
"body": "I think maybe I should think about another algorithm, but I don't know what?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T14:05:22.287",
"Id": "502617",
"Score": "0",
"body": "$10^i=10*10^(i-1)$, so you can calculate 10^i by a multiplication by 10 with the power of 10 of the previous step. And you only need the residue modulo p of $10^i$. I think the algorithm is ok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T14:34:02.823",
"Id": "502623",
"Score": "0",
"body": "You are right. I'll try that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T15:09:47.670",
"Id": "502625",
"Score": "0",
"body": "My code for the `slices` is now as follows: `slices = [int(number[-1]) % p]\n power = 1\n for i in range(len(number) - 2, -1, -1):\n power = 10 * power\n slices.append((power * int(number[i]) + slices[-1]) % p)`. Can it become faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:10:48.393",
"Id": "502640",
"Score": "0",
"body": "@MohammadAliNematollahi `power=10*power` why do you calculate with such large numbers. `power=(10*power)%p`. See my edit in my post. `slices.append`. why do you gather this slices?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:11:52.727",
"Id": "502641",
"Score": "0",
"body": "@MohammadAliNematollahi How did you embed Latex (10^6) in your comment?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:13:33.810",
"Id": "502652",
"Score": "0",
"body": "To embed Latex for math formula, use \\$ instead of $."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T11:01:03.367",
"Id": "254837",
"ParentId": "254749",
"Score": "2"
}
},
{
"body": "<p>One thing we're missing is that we only care whether any substring is a multiple of the prime. That means we don't need to carry any state bigger than that prime.</p>\n<p>Consider this algorithm:</p>\n<ol>\n<li>initialize accumulator <code>a</code> with the first digit</li>\n<li>reduce <code>a</code> modulo <code>p</code> (i.e, <code>a = a % p</code>)</li>\n<li>if the result is zero, we found a multiple</li>\n<li>append the next digit (<code>a = a * 10 + next</code>)</li>\n<li>repeat 2-4 until we run out of digits</li>\n</ol>\n<p>That still scales as <em>O(n²)</em> (as we need to run the loop once for each starting position), but we're now working with smaller intermediate numbers.</p>\n<p>In practice, we'd probably combine steps 4 and 2 - <code>a = (a * 10 + next) % p</code>.</p>\n<p>We can scale a little better by observing that any multiple (m1) directly followed by any other multiple (m2) also gives us a third one (m1m2), since multiplying 0 by a power of ten still gives 0. In general, a succession of <code>n</code> multiples will yield <code>½·n·(n-1)</code> for our count (be careful not to double-count them, though).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:15:11.843",
"Id": "502645",
"Score": "0",
"body": "the OP has already improved his initial O(n^2) algorithm to a linear time algorithm. You should not pursue him to use a worse algorithm again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T19:26:37.267",
"Id": "502663",
"Score": "0",
"body": "No, it's not linear-time. That's part of the problem. There's only one visible loop, but look at all those huge numbers that end up in the `Counter`!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T22:04:48.600",
"Id": "502677",
"Score": "0",
"body": "The dictionary access is O(n log n) (n is the length of the number string), so the algorithm is O(n log n). But not O(n^2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T07:50:10.573",
"Id": "502703",
"Score": "0",
"body": "Yes, but the `%` is _O(n)_ and that needs to be counted."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T15:34:49.030",
"Id": "254844",
"ParentId": "254749",
"Score": "0"
}
},
{
"body": "<p>The issue that you're running into is two-fold. One, you're using <code>bignum</code> math instead of the much faster integer math. Since the <a href=\"https://codereview.stackexchange.com/questions/254749/revised-counting-subnumbers-divisible-by-a-given-prime\">original problem</a> specifies that <code>2 <= p <= 10**9</code>, integer math is certainly enough to deal with this issue (as <a href=\"https://codereview.stackexchange.com/users/75307/toby-speight\">Toby Speight</a>'s <a href=\"https://codereview.stackexchange.com/a/254844/26190\">answer</a> points out). The second is that you're enumerating all the (up to one million) subnumbers at the end of <code>number</code>.</p>\n<p>I sign on to all of the comments in <a href=\"https://codereview.stackexchange.com/users/98493/graipher\">Graipher</a>'s <a href=\"https://codereview.stackexchange.com/a/254751/26190\">answer</a>, and add the following. Where he writes</p>\n<pre><code>slices = (int(number[i:]) % p for i in range(len(number)))\n</code></pre>\n<p>you should instead write</p>\n<pre><code>def generate_slices(number):\n mod = 0\n for digit in reversed(number):\n mod = (mod + int(digit)) % p\n yield mod\nslices = generate_slices(number)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:19:00.677",
"Id": "254851",
"ParentId": "254749",
"Score": "1"
}
},
{
"body": "<p>According to your guidances, I improved my code and it passed all tests.</p>\n<pre><code>from collections import Counter\n\nnumber = input()\np = int(input())\n\nans = 0\n\nif p == 2:\n ans = sum(i for i, digit in enumerate(number, 1)\n if digit in {'0', '2', '4', '6', '8'})\nelif p == 5:\n ans = sum(i for i, digit in enumerate(number, 1)\n if digit in {'0', '5'})\nelse:\n def generate_slices(number):\n mod = 0\n power = 1\n for i in range(len(number) - 1, -1, -1):\n mod = (mod + int(number[i]) * power) % p\n power = (power * 10) % p\n yield mod\n slices = generate_slices(number)\n digit_count = Counter(slices)\n\n zeroes = digit_count.pop(0, 0)\n ans = (zeroes * (zeroes + 1)) // 2\n ans += sum((count * (count - 1)) // 2\n for count in digit_count.values())\n\nprint(ans)\n</code></pre>\n<p>Thank you all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T02:55:37.580",
"Id": "502690",
"Score": "0",
"body": "The slice generator can be further improved. `power` is not needed. One can simply scan from left to right and do `for n in map(int, number): mod = (mod * 10 + n) % p; yield mod`. In Python 3.8+, this can be written without using a function: `slices = ((mod := (mod * 10 + n) % p) for n in map(int, number))`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:20:52.403",
"Id": "254855",
"ParentId": "254749",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254837",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T15:21:30.037",
"Id": "254749",
"Score": "2",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Revised: Counting subnumbers divisible by a given prime"
}
|
254749
|
<p>I have just started a course on C and wanted to test what I have learned so far. I did so by making a small program that tells you how much you should charge for a shot of a spirit you put in.</p>
<p>The code will ask if you want to do a calculation. It will follow up with a question about the name, price and size of a product and respond with the calculation.</p>
<p>I have just learned how to use a Struct and just worked on Arrays. My next step will be to try and implement arrays to store the Structs you made and have the option to return to previous input.
How did I do so far and what could I improve on?</p>
<pre><code>#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
//structs
typedef struct
{
string name;
float price;
int size;
} Bottles;
//prototypes
Bottles get_newBottle(void);
//main
int main(void)
{
string newBottles;
//Ask user for input, repeat untill answered correctly.
do
{
do
{
newBottles = get_string("Do you want to calculate a new shot y/n? ");
if (strcmp(newBottles, "y") == 0)
{
//Build struct
Bottles newBottle = get_newBottle();
int shotSize = get_int("What is the size of your pour of %s in ML? ", newBottle.name);
int bevCost = get_int("What percentage beverage cost do you want your drink to be? ");
float shotCost = (newBottle.price / newBottle.size) * shotSize;
float bevPrice = ((shotCost / bevCost) * 100) *1.21;
printf("The cost of your shot of %s is %.2f Euro. \n", newBottle.name, shotCost);
printf("At the cost of %.2f you will have to charge %.2f Euro including 21 percent VAT. \n", shotCost, bevPrice);
}
else if(strcmp(newBottles, "n") == 0)
{
printf("ok. doei!\n");
}
}
while (! (strcmp(newBottles, "y") == 0) && ! (strcmp(newBottles, "n") == 0));
}
while (strcmp(newBottles, "y") == 0);
return 0;
}
//extra functions
Bottles get_newBottle(void)
{
string name = get_string("What is the name of your product? ");
float price = get_float("What is the price of your product? ");
int size = get_int("What is the size in ML of your product? ");
Bottles newName = {name, price, size};
return newName;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T16:14:54.203",
"Id": "502439",
"Score": "0",
"body": "Is this C or C++? `std::string` is a C++ class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T16:15:29.667",
"Id": "502440",
"Score": "0",
"body": "And where is `get_string` defined? Probably in `cs50.h`; please show its contents."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T16:32:14.610",
"Id": "502443",
"Score": "2",
"body": "I think `string` is the awful CS50 typedef of `char *`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T17:19:07.920",
"Id": "502447",
"Score": "0",
"body": "I used the IDE from harvards CS50. They added the get_string. You can see it's contents here: https://manual.cs50.io/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T18:51:01.787",
"Id": "502457",
"Score": "0",
"body": "So, no, I can't; that's the manual and not the source. The source is [here](http://dkui3cmikz357.cloudfront.net/library50/c/cs50-library-c-3.0/cs50.c)."
}
] |
[
{
"body": "<h2>"Utility" libraries</h2>\n<p>It's time to take the training wheels off, so to speak. You need to stop using <code>cs50.h</code> and replace it with standard calls to the C libraries. The implementation for <code>get_string</code> has a careful, dynamically-allocated buffer algorithm that is really not necessary for most purposes and can be replaced with simpler calls that use a fixed-size buffer. Advantages of a fixed-size buffer, other than extremely reduced complexity, include that it can enforce "domain-specific limits" (i.e. your product name cannot exceed 128 characters, or whatever) where <code>get_string</code> cannot. <code>get_string</code> is especially overkill for your yes/no prompt.</p>\n<p>For an overrun-safe, simple method that is a fixed-buffer replacement for <code>get_string</code>, consider <a href=\"https://en.cppreference.com/w/c/io/fgets\" rel=\"nofollow noreferrer\"><code>fgets</code></a>.</p>\n<h2>Spelling</h2>\n<p><code>untill</code> -> <code>until</code></p>\n<h2>Memory leaks</h2>\n<p>You call <code>get_string</code> in a loop, which allocates a new buffer every time; and you never free it. So this will happily eat all of your RAM if you let it.</p>\n<h2>Comparisons</h2>\n<pre><code>! (strcmp(newBottles, "y") == 0)\n</code></pre>\n<p>should just be</p>\n<pre><code>strcmp(newBottles, "y") != 0\n</code></pre>\n<h2>New structure initialization</h2>\n<p>It's somewhat unusual to be returning a structure instance from <code>get_newBottle</code>, though it isn't the end of the world. More typical is to see either</p>\n<ol>\n<li>initialization of an existing structure passed by pointer, or</li>\n<li>allocation and initialization of a new structure via <code>malloc</code> then returning a pointer.</li>\n</ol>\n<p>This impacts performance more for huge structures, but it's still a good idea to learn.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T13:32:56.543",
"Id": "502520",
"Score": "0",
"body": "Thank you for taking the time to write all this out! I have changed the Comparison and the spelling error.\nHow would I bets go about removing the `get_string` from the loop?\nThis weeks subject of the course is memmory and working with malloc so I'll get back on changing that bit of code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T17:38:45.230",
"Id": "502534",
"Score": "1",
"body": "Read about `fgets`; edited."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T19:02:22.907",
"Id": "254761",
"ParentId": "254753",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254761",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T16:00:06.033",
"Id": "254753",
"Score": "2",
"Tags": [
"beginner",
"c"
],
"Title": "Drink price calculator"
}
|
254753
|
<p>The main idea is, I have a struct and I will get a struct field as a string from another function, which I shall increment its value by 1.<br />
Below is the code I used and I think it is memory consuming.<br />
How can I improve it? Is there a better way than the reflection from the start?<br />
Thanks</p>
<p>package main</p>
<pre><code>import (
"fmt"
"reflect"
)
func main() {
type chrinfo struct {
Size0_50 int
Size50_100 int
Size100_1000 int
Size1000_10000 int
Size10000 int
}
mychr := chrinfo{}
n := "Size1000_10000"
y := reflect.ValueOf(&mychr).Elem().FieldByName(n)
reflect.ValueOf(&mychr).Elem().FieldByName(n).SetInt(int64(y.Interface().(int))+1)
fmt.Println(mychr, y)
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T16:05:58.303",
"Id": "502902",
"Score": "0",
"body": "The first thing I think of looking at this is: \"Why?\"... Seriously, there's tons of alternative ways to do this, like using a map. If you really _have_ to use a struct and strings to access specific fields, then perhaps using tags on fields will make a difference, but reflection is only to be used as a last resort. A simpler way, without reflection, would be `m := map[string]*int{\"Size1000_10000\": &mychr.Size1000_10000}`, for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T20:53:03.007",
"Id": "502919",
"Score": "0",
"body": "I used struct cause I read that Maps are more memory consuming, plus I am new to Golang, So I asked here :)"
}
] |
[
{
"body": "<p>OK, after reading you're using a struct because maps use more memory, and that you posted this question here because you're new to go, let's dive in to this a bit more.</p>\n<h2>Do maps use more memory</h2>\n<p>The short answer is yes. However, things are a bit more complex than that. In essence, a map is a hash table, so of course, a map of type <code>map[string]int</code> will internally store all the strings, the buckets, hashes, data tables, etc... Whereas a struct is just a block of memory where fields point to an offset within that memory, it's pretty much the most efficient way to group values.</p>\n<p>That said, while a map with 5 keys does use more memory than a struct with 5 fields of type <code>int</code>, the difference on modern systems is quite negligible. There are a number of other factors to consider when it comes to choosing the type.</p>\n<h3>Runtime memory management</h3>\n<p>Once again, this may seem like a point where maps look like a terrible option, but it's just some background so you understand how maps, WRT memory management, work. Consider this:</p>\n<pre><code>foo := map[string]int{\n "one": 1,\n "two": 2,\n "three": 3,\n}\n</code></pre>\n<p>What happens here is that the runtime will allocate memory to hold the three strings, and the three values. The strings are passed through a hashing function, all memory required to store this map, the hashes, and its three values is allocated and assigned. Easy. Now compare this to:</p>\n<pre><code>bar := map[string]int{}\n// some code\nbar["one"] = 1\n// more core\nbar["two"] = 2\n// etc...\nbar["three"] = 3\n</code></pre>\n<p>In this scenario, the runtime creates an empty map and assigns it to <code>bar</code>. Some memory is allocated for the internal structures the map needs, but each time we assign a new key, the memory required to store the data for this map grows, and the runtime potentially has to reallocate memory, move stuff around, etc... this definitely is less efficient. We can, however, initialise a map with a certain size. I often do this if I know the map I'm populating will eventually hold at least 10, and at most 15 values. I'll just use <code>make</code> and specify the max size:</p>\n<pre><code>foobar := make(map[string]int, 3) // guarantees no realloc while adding the first 3 values\n</code></pre>\n<p>Another area where maps put some added strain on the runtime is when it comes to garbage collection. Remember: we need to allocate memory for the value, hash/buckets (map internals), and key, so doing something like:</p>\n<pre><code>delete(foo, "two")\n</code></pre>\n<p>affects 3 objects the runtime is having to manage. That's the reality of maps. The go implementation is fairly optimised, but if you run a heavy application that were to rely solely on maps, your pprof data after a while might show that the runtime is spending a lot of time on its GC cycles as a result.</p>\n<p>The latter is not really something you should be taken into consideration when comparing maps to structs, however. Structs don't support deleting fields to begin with. I just mentioned this for completeness sake. While it looks like a downside, you could equally argue that having the ability to delete keys from a map is a feature you might want to have. Indeed, sometimes you need to be able to do that.</p>\n<h2>Restrictions of a Struct</h2>\n<p>So far, we've established structs are more memory efficient, generally easier on the GC cycles (discounting nested structs, interfaces, embedding, etc...). They do have their limitations, however. The thing discussed earlier about memory management (adding more keys to a map causing reallocation) aren't an issue here. The memory is allocated all at once, and is nicely padded. On the flip side: the memory is allocated all at once. Even if I only were to need one field, a struct is an all or nothing type.</p>\n<h3>Dynamic access</h3>\n<p>Maps can use strings, ints, and really any comparable type. A struct has fields. This means the data contained stored in a map is a lot easier to access dynamically:</p>\n<pre><code>// given foo from earlier\nfunc get(k string) (int, error) {\n v, ok := foo[k]\n if !ok {\n return 0, fmt.Errorf("key '%s' not found", k)\n }\n return v, nil\n}\n</code></pre>\n<p>Whereas using a string to fetch the field of a struct requires a lot more code. The easiest way would be a receiver function on the struct type (method)</p>\n<pre><code>// assuming the chrinfo type from your code\nfunc (c chrinfo) get(k string) (int, error) {\n switch k {\n case "Size0_50", "size0_50": // accounting for capitalisation\n return c.Size0_50, nil\n case "Size50_100", "size50_100":\n return c.Size50_100, nil\n case "Size100_1000", "size100_1000":\n return c.Size100_1000, nil\n case "Size1000_10000", "size1000_10000":\n return c.Size1000_10000, nil\n case "Size10000", "size10000":\n return c.Size10000, nil\n }\n return 0, fmt.Errorf("field '%s' doesn't exist", k)\n}\n</code></pre>\n<p>This function will need to be updated for each field you add, and although capitalisation is something you may want to take into account, it's cumbersome. Typo's can lead to vague bug reports that cost hours to replicate, only to conclude there was no bug in the code you were looking at, but the person filing the issue didn't bother to check whether or not their input was correct...</p>\n<h3>Reflection</h3>\n<p>So obviously, one may conclude that using reflection at least takes away the burden of having to maintain this type of getter function. However, let's circle back to your original reason for not using a map: <strong>memory consumption</strong>.</p>\n<p>Compared to the runtime cost reflection incurs, the memory overhead of a map is laughable. It's akin to hopping on a plane to the arctic to cool a can of coke, instead of using an ice-cube, because using a freezer to freeze ice is wasting electricity, all the while burning literally tons of kerosine to fly your beverage around the globe instead.</p>\n<p>Reflection is crazy expensive. It uses a hell of a lot of CPU cycles, and if you look into <a href=\"https://golang.org/src/reflect/type.go\" rel=\"nofollow noreferrer\">the source code</a> every time you access something through reflection, you'll allocate the <code>reflect</code> types, like <a href=\"https://golang.org/src/reflect/value.go#L34\" rel=\"nofollow noreferrer\">the <code>reflect.Value</code> type</a>, which contains a <code>reflect.rtype</code>. These are just 2 structs you're allocating just to get access to a single field:</p>\n<pre><code>type Value struct {\n // typ holds the type of the value represented by a Value.\n typ *rtype\n\n // Pointer-valued data or, if flagIndir is set, pointer to data.\n // Valid when either flagIndir is set or typ.pointers() is true.\n ptr unsafe.Pointer\n\n // flag holds metadata about the value.\n // The lowest bits are flag bits:\n // - flagStickyRO: obtained via unexported not embedded field, so read-only\n // - flagEmbedRO: obtained via unexported embedded field, so read-only\n // - flagIndir: val holds a pointer to the data\n // - flagAddr: v.CanAddr is true (implies flagIndir)\n // - flagMethod: v is a method value.\n // The next five bits give the Kind of the value.\n // This repeats typ.Kind() except for method values.\n // The remaining 23+ bits give a method number for method values.\n // If flag.kind() != Func, code can assume that flagMethod is unset.\n // If ifaceIndir(typ), code can assume that flagIndir is set.\n flag\n\n // A method value represents a curried method invocation\n // like r.Read for some receiver r. The typ+val+flag bits describe\n // the receiver r, but the flag's Kind bits say Func (methods are\n // functions), and the top bits of the flag give the method number\n // in r's type's method table.\n}\n\ntype rtype struct {\n size uintptr\n ptrdata uintptr // number of bytes in the type that can contain pointers\n hash uint32 // hash of type; avoids computation in hash tables\n tflag tflag // extra type information flags\n align uint8 // alignment of variable with this type\n fieldAlign uint8 // alignment of struct field with this type\n kind uint8 // enumeration for C\n // function for comparing objects of this type\n // (ptr to object A, ptr to object B) -> ==?\n equal func(unsafe.Pointer, unsafe.Pointer) bool\n gcdata *byte // garbage collection data\n str nameOff // string form\n ptrToThis typeOff // type for pointer to this type, may be zero\n}\n</code></pre>\n<p>I'm not going to walk through the entirety of the <code>reflect</code> package, although you may want to take some time to do that yourself, just to see what using reflection actually implies. For now, let me assure you this:</p>\n<h1>Using reflection uses tons of CPU cycles and memory</h1>\n<hr />\n<p>So the question you had was: is there a better way? I'd say the answer to that is a resounding yes. A map will do just fine, in fact. The slightly higher memory consumption is nothing compared to the overhead you're creating using reflection.</p>\n<p>I touched on tags in my comment, which is something you can look into, but I wouldn't recommend it for this particular use-case (seeing as tags require reflection, too). You <em>could</em> use the combination of a map/struct as a field lookup table, like the one I mentioned. Assuming these calls don't happen concurrently, you can create a map statically (as in: as a field of a type, or a global variable if there is no other option), and do something like this:</p>\n<pre><code>var (\n mychr crinfo // your struct\n lookup map[string]*int // lookup map\n)\n\nfunc init() {\n lookup = map[string]*int{\n "Size0_50": &mych.Size0_50,\n "Size50_100": &mych.Size50_100,\n "Size100_1000": &mych.Size100_1000,\n "Size1000_10000": &mych.Size1000_10000,\n "Size10000": &mych.Size10000,\n }\n}\n</code></pre>\n<p>Then, to increment the corresponding field, it's quite simple:</p>\n<pre><code>func inc(k string) {\n if ptr, ok := lookup[k]; ok {\n *ptr += 1\n }\n}\n</code></pre>\n<p>The map contains pointers to each corresponding field, if the field exists, we increment its value. Job done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T02:11:20.813",
"Id": "503027",
"Score": "0",
"body": "Thank you for this detailed answer, that shed the light on different aspects of Golang. Silly question for function `func (c chrinfo) get(k string) (int, error)` should it be `func (c *chrinfo) get(k string) (int, error)` ? Thanks!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T10:09:15.963",
"Id": "503048",
"Score": "0",
"body": "@Medhat: If you're just getting a value, and not going to change any field, then using a value receiver, rather than a pointer is better. Using `func (c *chrinfo)` means you could be reading fields that are being reassigned elsewhere which leads to data races (race conditions). Getting the value from a copy ensures your type is safe for concurrent use"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T13:02:20.967",
"Id": "254998",
"ParentId": "254764",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254998",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T20:20:59.587",
"Id": "254764",
"Score": "0",
"Tags": [
"go",
"reflection"
],
"Title": "Increment struct value using reflection"
}
|
254764
|
<p>I created a deck of cards that I used in a BlackJack game. I stripped out my black jack logic and left just the Deck, card and minimum dealer.</p>
<p>The deck class is there because I want to create additional decks such as pinnacle or skip-bo.</p>
<p>I that about using an Enum class for card objects or a switch statement for creating cards.</p>
<p>I wasn't sure about <code>shuffle()</code> so I just use randomizeCards. Almost all tutorials use rand() with time(). I read that it's a weak generator and use another one. I've used my random in all kinds of projects.</p>
<p>I'm mainly worried about size and speed. Is it as small as it can be and using the RAM as efficiently as possible.</p>
<pre><code>#include<iostream>
#include<string>
#include<vector>
#include<random>
using namespace std;
class Card {
public:
Card() {}
~Card() {}
unsigned value=0;
string suit="";
string name="";
string rank="";
};
class Deck {
public:
Deck() {}
void makeDeck();
vector<Card> cards;
vector<Card> suit;
Card card;
};
void Deck::makeDeck() {
for(int i=0; i<4; i++) {
for(int j=1; j<14; j++) {
if(i==0)card.suit="HEARTS";
if(i==1)card.suit="DIAMONDS";
if(i==2)card.suit="CLUBS";
if(i==3)card.suit="SPADES";
if(j==1) {
card.name="ACE";
card.value=j;
card.rank=j;
cards.push_back(card);
}
else if(j==2) {
card.name="TWO";
card.value=j;
card.rank=j;
cards.push_back(card);
}
else if(j==3) {
card.name="THREE";
card.value=j;
card.rank=j;
cards.push_back(card);
}
else if(j==4) {
card.name="FOUR";
card.value=j;
card.rank=j;
cards.push_back(card);
}
else if(j==5) {
card.name="FIVE";
card.value=j;
card.rank=j;
cards.push_back(card);
}
else if(j==6) {
card.name="SIX";
card.value=j;
card.rank=j;
cards.push_back(card);
}
else if(j==7) {
card.name="SEVEN";
card.value=j;
card.rank=j;
cards.push_back(card);
}
else if(j==8) {
card.name="EIGHT";
card.value=j;
card.rank=j;
cards.push_back(card);
}
else if(j==9) {
card.name="NINE";
card.value=j;
card.rank=j;
cards.push_back(card);
}
else if(j==10) {
card.name="TEN";
card.value=10;
card.rank=j;
cards.push_back(card);
}
else if(j==11) {
card.name="JACK";
card.value=10;
card.rank=j;
cards.push_back(card);
}
else if(j==12) {
card.name="QUEEN";
card.value=10;
card.rank=j;
cards.push_back(card);
}
else if(j==13) {
card.name="KING";
card.value=10;
card.rank=j;
cards.push_back(card);
}
}
}
}
//end of deck class
class Dealer {
public:
Dealer() {}
void playAgain();
private:
void getCard(vector<Card> &hand);
void printHand(vector<Card> &hand);
int randomizeDeck(vector<Card> &cards);
Deck deck;
vector<Card> player;
vector<Card> house;
int credits=100;
int bet=0;
};
void Dealer::playAgain() {
deck.makeDeck();
printHand(deck.cards);
char choice='y';
cout<<endl<<endl<<"============================="<<endl<<endl;
cout<<endl<<"Would you like to play again?(y/n): ";
cin>>choice;
if(choice=='y') {
//deal21();
deck.makeDeck();
printHand(deck.cards);
} else {
cout<<"goodbye";
exit(0);
}
}
void Dealer::getCard(vector<Card> &hand) {
int pick=randomizeDeck(deck.cards);
hand.push_back(deck.cards[pick]);
deck.cards[pick]=deck.cards.back();
deck.cards.pop_back();
}
void Dealer::printHand(vector<Card> &hand) {
for(int i=0; i<hand.size(); i++) {
cout<<hand[i].name<<" of "<< hand[i].suit<<endl;
}
}
int Dealer::randomizeDeck(vector<Card> &cards) {
int max=cards.size()-1;
random_device rd;
mt19937 numGen(rd());
static uniform_int_distribution<int> roll(0,max);
return roll(numGen);
}
int main() {
Dealer dealer;
dealer.playAgain();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Design review</h1>\n<h2><code>Card</code></h2>\n<p>Let’s start by looking at the <code>Card</code> class. As designed, <code>Card</code> has 4 data members:</p>\n<ul>\n<li><code>value</code></li>\n<li><code>suit</code></li>\n<li><code>name</code></li>\n<li><code>rank</code></li>\n</ul>\n<p><code>value</code> is an <code>unsigned int</code>, while the others are all <code>std::string</code>s.</p>\n<p>This is <em>enormously</em> wasteful. A card really only has two properties: rank and suit. If you know the rank, you know the value and the name, so duplicating that data in the class is just wasting space.</p>\n<p>I don’t even see how your code even compiles, because <code>rank</code> is a string, but in <code>Deck::makeDeck()</code> you try to shove integer values into it.</p>\n<p>In addition, using the wrong types also wastes space. The suit doesn’t need to be a string. It can have only one of 4 possible values. You can fit the suit in a single byte. Using a string is not only ~20–50 times bigger, it might also require memory allocations, and <em>every</em> operation becomes more expensive (for example, comparing suits could be a simple byte value compare, rather than a <em>much</em> more expensive string comparison).</p>\n<p>I think the first thing you need to look at is <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"nofollow noreferrer\">enumerations</a>. Enumerations are <em>perfect</em> for when you have something that has a fixed, small number of values. Like a card suit, for example. You could do:</p>\n<pre><code>enum class suit_t\n{\n hearts,\n diamonds,\n clubs,\n spades\n};\n</code></pre>\n<p>That’s it! To make it even better, you can specify that it has to be a single byte in size:</p>\n<pre><code>enum class suit_t : unsigned char\n{\n hearts,\n diamonds,\n clubs,\n spades\n};\n</code></pre>\n<p>Then if you need things like conversion to a string for printing, you can add functions or stream inserters as needed:</p>\n<pre><code>enum class suit_t : unsigned char\n{\n hearts,\n diamonds,\n clubs,\n spades\n};\n\n// a to_string() function:\nauto to_string(suit_t s) -> std::string\n{\n switch (s)\n {\n case suit_t::hearts:\n return "hearts";\n case suit_t::diamonds:\n return "diamonds";\n case suit_t::clubs:\n return "clubs";\n case suit_t::spades:\n return "spades";\n }\n}\n\n// a stream inserter:\ntemplate <typename CharT, typename Traits>\nauto operator<<(std::basic_ostream<CharT, Traits>& out, suit_t s)\n -> std::basic_ostream<CharT, Traits>&\n{\n switch (s)\n {\n case suit_t::hearts:\n out << "hearts";\n break;\n case suit_t::diamonds:\n out << "diamonds";\n break;\n case suit_t::clubs:\n out << "clubs";\n break;\n case suit_t::spades:\n out << "spades";\n break;\n }\n\n return out;\n}\n</code></pre>\n<p>You can do the same thing for the rank:</p>\n<pre><code>enum class rank_t : unsigned char\n{\n ace = 1,\n two = 2,\n three = 3,\n four = 4,\n five = 5,\n six = 6,\n seven = 7,\n eight = 8,\n nine = 9,\n ten = 10,\n jack = 11,\n queen = 12,\n king = 13\n};\n</code></pre>\n<p>Then you can add whatever functions you need:</p>\n<pre><code>constexpr auto to_value(rank_t r) noexcept -> int\n{\n switch (r)\n {\n case rank_t::jack:\n [[fallthrough]];\n case rank_t::queen:\n [[fallthrough]];\n case rank_t::king:\n return 10;\n default:\n return static_cast<int>(r);\n }\n}\n</code></pre>\n<p>And with those, making a card type is trivial:</p>\n<pre><code>struct card_t\n{\n rank_t rank;\n suit_t suit;\n};\n</code></pre>\n<p>That’s about all you need! Then of course you can add useful functions, like a stream inserter:</p>\n<pre><code>template <typename CharT, typename Traits>\nauto operator<<(std::basic_ostream<CharT, Traits>& out, card_t c)\n -> std::basic_ostream<CharT, Traits>&\n{\n if (out)\n {\n auto oss = std::basic_ostringstream<CharT, Traits>{};\n oss << c.rank << " of " << c.suit;\n\n out << oss.view();\n }\n\n return out;\n}\n</code></pre>\n<p>And to really illustrate how big a difference makes, compare the sizes of your <code>Card</code> and my <code>card_t</code>. Using Clang and libc++:</p>\n<ul>\n<li><code>Card</code> : 80</li>\n<li><code>card_t</code>: 2</li>\n</ul>\n<p>Using GCC:</p>\n<ul>\n<li><code>Card</code> : 104</li>\n<li><code>card_t</code>: 2</li>\n</ul>\n<p>You see? By using enumerations, the card class is ~40–50 times smaller. Assuming a cache line size of 64 b, you can actually fit <em>an entire deck</em> of <code>card_t</code> in just two cache lines, whereas <em>not even a single <code>Card</code> would fit</em>. (And if you were <em>really</em> clever, you could get the size of <code>card_t</code> down to <em>a single byte</em>, so <em>a whole deck</em> could fit in a cache line.) And operations like comparing two cards will be <em>thousands</em> of times faster.</p>\n<p>If I were designing a card class, I would make both the suit and the rank inner types of that class, to keep everything clean:</p>\n<pre><code>struct card_t\n{\n enum class rank_t : unsigned char\n {\n ace = 1,\n two = 2,\n three = 3,\n four = 4,\n five = 5,\n six = 6,\n seven = 7,\n eight = 8,\n nine = 9,\n ten = 10,\n jack = 11,\n queen = 12,\n king = 13\n };\n\n enum class suit_t : unsigned char\n {\n hearts,\n diamonds,\n clubs,\n spades\n };\n\n rank_t rank = rank_t::ace;\n suit_t suit = suit_t::spades;\n\n constexpr auto operator==(card_t const&) const noexcept -> bool = default;\n};\n</code></pre>\n<p>If you want to support more deck types, like including <a href=\"https://en.wikipedia.org/wiki/Knight_(playing_card)\" rel=\"nofollow noreferrer\">the knight rank</a>, you can just add that into the <code>rank_t</code> enumeration (you could adjust the number values so the knight rank is 12, the queen is 13, and the king is 14). If you want more suits, like stars or waves, no problem, just add those to <code>suit_t</code>. If you want to add support for jokers, trumps, or the fool, things get a little more complicated, but not ridiculously so. You could add a “none” suit… or maybe special “white” and “black” suits for the jokers. Or you could use a variant to distinguish between suited cards, trumps, jokers, and the fool.</p>\n<h2><code>Deck</code></h2>\n<p>Once you’ve shrunk the size of the card class, the deck class will also be <em>much</em> more efficient.</p>\n<p>Your deck class has 3 data members, but I don’t see the point of <code>suit</code>, and <code>card</code> seems to be a misguided way to have a local variable in your <code>makeDeck()</code> function. The only data member you <em>actually</em> need is <code>cards</code>.</p>\n<p>Now, <code>cards</code> is a <code>vector</code>, and that’s not <em>bad</em>… but consider that you don’t really <em>need</em> the full power of a <code>vector</code>. You know in advance that there can never be more than 52 cards in your deck. Given that, you could use something like <a href=\"https://www.boost.org/doc/libs/release/doc/html/boost/container/static_vector.html\" rel=\"nofollow noreferrer\">Boost’s <code>static_vector</code></a>, and avoid any dynamic allocation at all.</p>\n<p>But for a start, <code>vector</code> is fine.</p>\n<p>However, what the deck class <em>really</em> needs is some member functions, because if you’re just going to expose the <code>cards</code> data member, you might as well not have a deck class at all: just use a vector of cards. Designing a good interface is an art and a science, but a decent deck class might look something like this:</p>\n<pre><code>class deck_t\n{\npublic:\n // creates a full deck of 52 cards\n static auto full_deck() -> deck_t;\n\n // creates an empty deck\n deck_t();\n\n // creates a deck with the cards given\n template <std::input_iterator It, std::sentinel_for<It> Sen>\n deck_t(It, Sen);\n template <std::input_range Rng>\n deck_t(Rng&&);\n\n // sort the deck\n auto sort() -> void;\n template <typename Cmp>\n auto sort(Cmp) -> void;\n\n // shuffle the deck\n template <std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\n auto shuffle(Gen&&) -> void;\n\n // draw cards from the top of the deck\n auto draw() -> card_t;\n auto draw(std::size_t) -> std::vector<card_t>;\n template <std::output_iterator O>\n auto draw(std::size_t, O) -> O;\n\n // draw cards randomly from the deck\n template <std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\n auto draw_randomly(Gen&&) -> card_t;\n template <std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\n auto draw_randomly(std::size_t, Gen&&) -> std::vector<card_t>;\n template <std::output_iterator O, std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\n auto draw_randomly(std::size_t, O, Gen&&) -> O;\n\n // place cards onto the top of deck\n auto replace(card_t) -> void;\n template <std::input_iterator It, std::sentinel_for<It> Sen>\n auto replace(It, Sen) -> It;\n template <std::input_range Rng>\n auto replace(Rng&&) -> std::borrowed_iterator_t<Rng>;\n\n // place cards at the bottom of the deck\n auto place_at_bottom(card_t) -> void;\n template <std::input_iterator It, std::sentinel_for<It> Sen>\n auto place_at_bottom(It, Sen) -> It;\n template <std::input_range Rng>\n auto place_at_bottom(Rng&&) -> std::borrowed_iterator_t<Rng>;\n\n // place cards randomly into the deck\n template <std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\n auto place_randomly(card_t, Gen&&) -> void;\n template <std::input_iterator It, std::sentinel_for<It> Sen, std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\n auto place_randomly(It, Sen, Gen&&) -> It;\n template <std::input_range Rng, std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\n auto place_randomly(Rng&&, Gen&&) -> std::borrowed_iterator_t<Rng>;\n\n // move some cards from the top of this deck to the top of another\n auto transfer_card_to(deck_t&) -> void;\n auto transfer_cards_to(deck_t&, std::size_t) -> void;\n auto transfer_all_cards_to(deck_t&) -> void;\n\n // create a new deck from some part of the top of this deck\n auto draw_deck(std::size_t) -> deck_t;\n\n // create a new deck by drawing randomly from this deck\n template <std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\n auto draw_deck_randomly(std::size_t, Gen&&) -> deck_t;\n\n // standard container functions //////////////////////////////////////////\n\n auto begin() const noexcept -> card_t const*;\n auto end() const noexcept -> card_t const*;\n auto cbegin() const noexcept -> card_t const*;\n auto cend() const noexcept -> card_t const*;\n\n auto rbegin() const noexcept -> std::reverse_iterator<card_t const*>;\n auto rend() const noexcept -> std::reverse_iterator<card_t const*>;\n auto crbegin() const noexcept -> std::reverse_iterator<card_t const*>;\n auto crend() const noexcept -> std::reverse_iterator<card_t const*>;\n\n auto front() const -> card_t const&;\n auto back() const -> card_t const&;\n\n auto operator[](std::size_t) const -> card_t const&;\n auto at(std::size_t) const -> card_t const&;\n\n auto empty() const noexcept -> bool;\n auto size() const noexcept -> std::size_t;\n auto max_size() const noexcept -> std::size_t; // should return 52\n};\n</code></pre>\n<p>You may not need <em>all</em> the functions in that interface, but some of them will sure come in handy. This is what a simple game might look like with this interface:</p>\n<pre><code>// start with a full deck, and shuffle it\nauto deck = deck_t::full_deck();\n\n// start a new game\nwhile (playing)\n{\n deck.shuffle(rng);\n\n // also need a discard pile\n // (though we could just "discard" by putting cards at the bottom of the deck)\n auto discard_pile = deck_t{};\n\n // let's say there are 4 players, each with their own hand\n // (we can reuse the deck class for a hand)\n constexpr auto player_count = std::size_t{4};\n auto player_hands = std::array<deck_t, player_count>{};\n\n // now each player draws 5 cards\n for (auto&& player_hand : player_hands)\n player_hand = deck.draw_deck(5);\n\n // now each player examines their hand\n std::ranges::for_each(player_hands, [](auto&& hand) { hand.sort(); });\n\n // now give each player a chance to exchange cards to get a better hand\n for (auto player = std::size_t{0}; player < player_count; ++player)\n {\n auto exchange_count = // ask player how many cards to exchange\n\n player_hands[player].transfer_cards_to(discard_pile, exchange_count);\n deck(player_hands[player], exchange_count);\n }\n\n // now sort by the score of the hand\n std::ranges::sort(player_hands, hand_score_func);\n\n // and print the results\n std::cout << "the results in order are:\\n";\n std::ranges::for_each(player_hands, [](auto&& hand) { std::cout << '\\t' << hand << '\\n'; });\n\n // restore all the cards back to the deck for another game\n discard_pile.transfer_all_cards_to(deck);\n std::ranges::for_each(player_hands, [&deck](auto&& hand) { hand.transfer_all_cards_to(deck); });\n}\n</code></pre>\n<h2><code>Dealer</code></h2>\n<p>The dealer class structure isn’t bad, but you could use the deck class for both the player and house hands. They are, in a way, decks, after all.</p>\n<p>The real problem with the dealer class is that it just does too much. It’s not just a dealer… it plays the whole game… <em>and</em> even handles asking if the player wants to replay… <em>and</em> shuffles the deck… and draws the cards….</p>\n<p>Strip it down. First of all, the proper name for this class probably isn’t “dealer”, but rather “game”. All the class should do is handle setting up and then playing through a game. Shuffling? Let the deck class handle that. Randomly drawing cards? Again, let the deck class handle that. Asking the user if they want to replay? Let something else handle that. The game class should be <em>just</em> about the game itself.</p>\n<pre><code>class game\n{\npublic:\n // play a game\n auto play() -> void;\n\nprivate:\n std::mt19937 _rng;\n};\n</code></pre>\n<p>And the play function could be something like:</p>\n<pre><code>auto game::play() -> void\n{\n auto deck = deck_t::full_deck();\n deck.shuffle(_rng);\n\n auto player = deck.draw_deck(N); // N is how many cards each player starts with\n auto house = deck.draw_deck(N);\n\n auto credits = 100;\n\n auto done = false;\n while (not done)\n {\n // player moves first\n auto choice = get_player_choice();\n switch (choice)\n {\n case 'd': // player wants to draw cards\n {\n auto count = get_player_draw_count();\n deck.transfer_cards_to(player, count);\n }\n break;\n case 'b': // player wants to make a bet\n // and so on\n }\n\n // now the house makes its move\n\n // check for whether someone won, and if so, print the result and\n // set done to true\n }\n}\n</code></pre>\n<p>After the game is done and <code>play()</code> returns, then you can have an external loop—in <code>main()</code>, for example—that asks “do you want to play again?”, and if the answer is yes, it will just call <code>play()</code> again.</p>\n<h2>Think like a game programmer</h2>\n<p>All games fundamentally have the same structure:</p>\n<pre><code>initialize();\n\nwhile (game_is_not_over())\n{\n input(); // get input from the user\n update(); // update the game state\n render(); // display the current state\n}\n</code></pre>\n<p>Even a game as simple as a console-only card game uses the same pattern. After initializing the game (setting up the deck and dealing hands to all the players), you start the loop where you first ask the user what they want to do… and then you update the game state, which includes giving the AI its turn and checking to see if there are an winners… then you output the current situation to the player, telling them what cards they’re holding, or whether the game is over (and who won).</p>\n<p>If you want to allow replaying, then you just need to wrap all that in a loop:</p>\n<pre><code>do\n{\n auto game = game_t{};\n\n while (game.running())\n {\n game.get_input();\n game.update();\n game.render(std::cout);\n }\n\n std::cout << "\\n\\n=============================\\n\\n\\n";\n\n} while (wants_to_play_again());\n\nstd::cout << "goodbye\\n";\n</code></pre>\n<p>Before starting any games, you could set up your random number generator:</p>\n<pre><code>auto main() -> int\n{\n auto prng = std::mt19937{std::random_device{}()};\n\n do\n {\n auto game = game_t{prng};\n\n while (game.running())\n {\n game.get_input();\n game.update();\n game.render(std::cout);\n }\n\n std::cout << "\\n\\n=============================\\n\\n\\n";\n\n } while (wants_to_play_again());\n\n std::cout << "goodbye\\n";\n}\n</code></pre>\n<p>Starting from that high-level design, you can fill in the functions you need. And by designing it this way, you will already have the general structure in place to convert to a graphical game if you like. (The differences would mostly be that you’re no longer getting input from <code>std::cin</code> or rendering text output to <code>std::cout</code>; the actual game logic in the update function should be unchanged.)</p>\n<h1>General issues</h1>\n<h2>Don’t use <code>std::endl</code></h2>\n<p>If you just want a newline, use <code>'\\n'</code>. <code>std::endl</code> doesn’t just print a newline, it flushes the stream, which can be expensive.</p>\n<p>So if you want a spacing of 2 lines, and you do something like <code>std::cout << std::endl << std::endl << "========" << std::endl << std::endl;</code>, you are flushing the stream <em>at least 4 times</em>. That’s ridiculous.</p>\n<p>All you need is: <code>std::cout << "\\n\\n========\\n\\n";</code>.</p>\n<h2>Don’t shuffle the deck every time a card is drawn</h2>\n<p>Shuffling over and over doesn’t actually improve randomness, and it costs.</p>\n<p>Instead, just shuffle once at the beginning of the game. That’s how it works in real life, after all.</p>\n<p>Shuffle once, and then just keep picking cards off the top of the deck.</p>\n<h1>Code review</h1>\n<pre><code>using namespace std;\n</code></pre>\n<p>Never, ever do this. Just put <code>std::</code> where it’s needed.</p>\n<pre><code>Card() {}\n~Card() {}\n</code></pre>\n<p>You don’t need to explicitly spell out these functions. Classes get default constructors and destructors by default. Actually writing out these functions causes three problems:</p>\n<ol>\n<li><p>It confuses developers.</p>\n<p>An experienced C++ coder who sees these functions will immediately be suspicious, because why would anyone waste time writing code that they don’t need to. If someone sat down and wrote these out, that must mean there’s some <em>reason</em> for it… right? Now the coder will waste time trying to hunt down the reason.</p>\n</li>\n<li><p>It creates a maintenance burden.</p>\n<p>Every line of code you write adds to the maintenance debt. It makes the code harder to read (because more code is harder to read than less code), harder to spot problems (because if you have a bunch of useless, noise code around the <em>important</em> stuff, the important stuff will be harder to see, and so will bugs), and harder to work with (because every time you want to make a change, you have to check more code to see if there will be any conflicts).</p>\n</li>\n<li><p>It actually slows down your program.</p>\n<p>When you define the default constructor or destructor like this, you are creating a non-trivial default constructor and non-trivial destructor. That’s bad. Trivial default constructors and trivial destructors are a good thing, because if they’re trivial, the compiler can optimize them away in most cases. This can give you huge performance gains.</p>\n</li>\n</ol>\n<p>So just don’t write functions you don’t need.</p>\n<pre><code>unsigned value=0;\n</code></pre>\n<p>Don’t use unsigned types for regular numbers. They cause surprises when doing calculations and comparisons. Just use an <code>int</code>.</p>\n<p>Other than that, I already showed how you can optimize the card class down to something only 2 bytes large, that will be <em>blazingly</em> fast.</p>\n<pre><code>Deck() {}\n</code></pre>\n<p>Again, you don’t need this, so don’t write it.</p>\n<pre><code>vector<Card> cards;\nvector<Card> suit;\nCard card;\n</code></pre>\n<p>I don’t understand the point of all these members. A deck shouldn’t be anything other than a bunch of cards. Why do you also need a bunch of suits, and a separate, single card?</p>\n<pre><code>void Deck::makeDeck() {\n for(int i=0; i<4; i++) {\n for(int j=1; j<14; j++) {\n</code></pre>\n<p>There are a lot magic numbers hidden in there. Magic numbers are a bad idea. You should always use named constants that explain what’s going on:</p>\n<pre><code>void Deck::makeDeck() {\n for (int i = suit_min; i < suit_max; ++i) {\n for (int j = rank_min; j < rank_max; ++j) {\n</code></pre>\n<p>You should also give your variables meaningful names. Names like <code>i</code> and <code>j</code> make sense when the loop counter is <em>just</em> an index, and serves no other purpose. But these values <em>do</em> have another meaning:</p>\n<pre><code>void Deck::makeDeck() {\n for (int suit = suit_min; suit < suit_max; ++suit) {\n for (int rank = rank_min; rank < rank_max; ++rank) {\n</code></pre>\n<p>The next problem with this function is that you use an outside variable for the card. That makes no sense. The card should be a local variable.</p>\n<p>And of course, the biggest and most obvious problem with the function is that it’s <em>incredibly</em> repetitive. You could simplify it considerably like this:</p>\n<pre><code>void Deck::makeDeck() {\n // you should really clear the deck first\n cards.clear();\n\n // to speed things up, you should reserve the memory needed beforehand\n cards.reserve(number_of_cards_in_deck);\n\n for (int suit = suit_min; i < suit_max; ++i) {\n for (int rank = rank_min; j < rank_max; ++j) {\n auto card = Card{};\n\n // set up some default values\n card.value = rank;\n // card.rank = rank; // this won't compile because your types are wrong!\n\n switch (suit)\n {\n case suit_hearts:\n card.suit = "HEARTS";\n break;\n case suit_diamonds:\n card.suit = "DIAMONDS";\n break;\n\n // and so on...\n\n }\n\n switch (rank)\n {\n case rank_ace:\n card.name = "ACE";\n break;\n case rank_two:\n card.name = "TWO";\n break;\n\n // and so on...\n\n // face cards are special because their value isn't the same as\n // their rank\n case rank_jack:\n card.name = "JACK";\n card.value = 10;\n break;\n case rank_queen:\n card.name = "QUEEN";\n card.value = 10;\n break;\n case rank_king:\n card.name = "KING";\n card.value = 10;\n break;\n }\n\n cards.push_back(std::move(card));\n }\n }\n}\n</code></pre>\n<p>But this is still an ugly function. A much better solution is to make a <em>proper</em> card class, with <em>proper</em> suit and rank classes. Then you can just do something like:</p>\n<pre><code>void Deck::makeDeck()\n{\n constexpr auto all_ranks = std::array{\n card_t::rank_t::ace,\n card_t::rank_t::two,\n // and so on...\n };\n\n constexpr auto all_suits = std::array{\n card_t::suit_t::hearts,\n card_t::suit_t::diamonds,\n card_t::suit_t::clubs,\n card_t::suit_t::spades\n };\n\n cards.clear();\n cards.reserve(all_ranks::size() * all_suits::size());\n\n for (auto&& rank : all_ranks)\n for (auto&& suit : all_suits)\n cards.emplace_back(rank, suit);\n}\n</code></pre>\n<p>For a different game type, with different suits or ranks, or with the addition of jokers or trumps, you just need to modify those arrays, and/or add a third array for specials.</p>\n<p>That’s how clean and simple C++ code gets when you make proper types. Get the types right, and everything else just magically falls into place.</p>\n<pre><code>Dealer() {}\n</code></pre>\n<p>Yet again, unnecessary code.</p>\n<pre><code>void Dealer::playAgain() {\n deck.makeDeck();\n printHand(deck.cards);\n char choice='y';\n cout<<endl<<endl<<"============================="<<endl<<endl;\n cout<<endl<<"Would you like to play again?(y/n): ";\n cin>>choice;\n if(choice=='y') {\n //deal21();\n deck.makeDeck();\n printHand(deck.cards);\n } else {\n cout<<"goodbye";\n exit(0);\n }\n}\n</code></pre>\n<p>The way this function is currently written, you only get two games and then the program quits. That’s because you’ve embedded the “play again” option in the middle of the same function that actually plays the game.</p>\n<p>I’d say before you consider the notion of “play again”, you first need to consider “play”. If you have a “play” function, then the “play again” function is just:</p>\n<pre><code>auto play_again()\n{\n auto done = false;\n\n while (not done)\n {\n play();\n\n std::cout << "\\n\\n=============================\\n\\n"\n "\\nWould you like to play again?(y/n): ";\n\n auto choice = '\\0';\n while (not (std::cin >> choice) or (choice != 'y' and choice != 'n'))\n {\n if (std::cin.eof())\n {\n // reached the end of the input, which pretty much means we're done\n done = true;\n break;\n }\n\n // clear any errors on cin\n std::cin.clear();\n if (not std::cin)\n throw std::runtime_error{"input is completely borked"};\n\n // note you could also ignore everything on cin up to the next newline\n\n std::cout << "Sorry, didn’t understand your answer.\\n"\n "Play again? (y/n): ";\n }\n\n if (choice == 'n')\n done = true;\n }\n\n std::cout << "goodbye\\n";\n}\n</code></pre>\n<p>Or, even better, separate all that query logic into its own function:</p>\n<pre><code>template <std::forward_range Rng>\nauto get_choice(std::istream& in, std::ostream& out, std::string_view query, Rng const& choices)\n{\n while (true)\n {\n out << query;\n out.flush();\n\n if (auto choice = '\\0'; in >> choice)\n {\n if (std::ranges::find(choices, choice) != std::ranges::end(choices))\n return choice;\n\n out << "Sorry, '" << choice << "' is not a valid choice.\\n";\n }\n else\n {\n throw std::runtime_error{"bad input"};\n }\n }\n}\n\nauto play_again()\n{\n while (true)\n {\n play();\n\n std::cout << "\\n\\n=============================\\n\\n\\n";\n\n if (auto const choice = get_choice(std::cin, std::cout, "Would you like to play again?(y/n): ", "yYnN"); choice == 'n' or choice == 'N')\n break;\n }\n\n std::cout << "goodbye\\n";\n}\n</code></pre>\n<p>With the “play” function separated, all the actual game logic can go there.</p>\n<pre><code> } else {\n cout<<"goodbye";\n exit(0);\n }\n</code></pre>\n<p>Never, ever use <code>std::exit()</code> in C++. It’s a C function; it doesn’t work properly in C++.</p>\n<pre><code>void Dealer::getCard(vector<Card> &hand) {\n int pick=randomizeDeck(deck.cards);\n hand.push_back(deck.cards[pick]);\n deck.cards[pick]=deck.cards.back();\n deck.cards.pop_back();\n}\n</code></pre>\n<p>This is a rather peculiar way to draw a card from a deck. First of all, it doesn’t make sense to pull a card randomly from out of the middle of the deck. That’s not how people play cards in real life. They shuffle the deck once at the beginning of the game, and then just draw from the top of the deck.</p>\n<p>But then you do something even more peculiar: you copy the card from the middle of the deck… then copy the card at the top of the deck over that first card… then remove the card at the top of the deck. That’s a lot of gymnastics just to draw a card from a deck. All that wouldn’t be necessary if the deck were shuffled.</p>\n<pre><code>void Dealer::printHand(vector<Card> &hand) {\n for(int i=0; i<hand.size(); i++) {\n cout<<hand[i].name<<" of "<< hand[i].suit<<endl;\n }\n}\n</code></pre>\n<p>You can take the hand as a <code>const</code> reference here, because you’re not modifying it. Also, I don’t see the logic in making this a member of <code>Dealer</code>. This is a useful function, generally, so why not make it a free function?</p>\n<p>In any case, you have a bug. <code>i</code> is an <code>int</code>… but <code>hand.size()</code> is a <code>vector<Card>::size_type</code>, which is an unsigned integer of some kind. Don’t use old-fashioned <code>for</code>-loops with ranges… but if you really must, get the types right. That loop should be:</p>\n<pre><code> for (auto i = decltype(hand.size())(0); i < hand.size(); ++i) {\n std::cout << hand[i].name << " of " << hand[i].suit << '\\n';\n }\n</code></pre>\n<p>But again, don’t use old-school <code>for</code> loops for this kind of thing. Use a range-<code>for</code>:</p>\n<pre><code> for (auto&& card : hand) {\n std::cout << card.name << " of " << card.suit << '\\n';\n }\n</code></pre>\n<p>or an algorithm:</p>\n<pre><code> std::ranges::for_each(hand, [](auto&& card) {\n std::cout << card.name << " of " << card.suit << '\\n';\n });\n</code></pre>\n<p>And even better would be if cards knew how to print themselves. Again, get the types right, and everything else just works. If cards did know how to print themselves, then this function could just be:</p>\n<pre><code>auto print_hand(std::ostream& out, std::vector<Card> const& hand)\n{\n std::ranges::for_each(hand, [&out](auto&& card) { out << card << '\\n'; });\n}\n</code></pre>\n<p>Even better still would be if you had a class for hands (which could also just reuse the deck class), because then you would’t need this function at all. You could just do <code>std::cout << hand;</code>. As always, spend a little time getting the low-level types right, and the high-level logic becomes trivial.</p>\n<pre><code>int Dealer::randomizeDeck(vector<Card> &cards) {\nint max=cards.size()-1;\n random_device rd;\n mt19937 numGen(rd());\n static uniform_int_distribution<int> roll(0,max);\n return roll(numGen);\n}\n</code></pre>\n<p>What you’re doing here is clever, but there are a lot of problems with how you’re doing it.</p>\n<p>First, <code>int</code> is the wrong type. If you are indexing a <code>vector</code>, the correct type to use is the <code>vector</code>’s <code>size_type</code>. <code>vector</code>’s <code>size_type</code> is going to be unsigned (which, yes, is not good, but it was a decision made long ago, before people realized the problems it would cause), and may also be much bigger than <code>int</code>. The net result is that if you try to cram the result of <code>cards.size() - 1</code> into an <code>int</code>… you could end up triggering undefined behaviour. That’s very bad.</p>\n<p>The fix here is so trivial it’s almost laughable. Just don’t say <code>int</code>. Just use <code>auto</code> (or nothing at all):</p>\n<pre><code>auto get_random_card_index(std::vector<Card> const& cards)\n{\n auto const max = cards.size() - 1;\n\n std::random_device rd;\n std::mt19937 numGen(rd());\n\n static std::uniform_int_distribution roll(0, max);\n return roll(numGen);\n}\n</code></pre>\n<p>Bug fixed.</p>\n<p>The next major problem with this function is that every time you ask for a random index into a set of cards, you’re constructing a new random number generator. That makes no sense, and it is remarkably wasteful. Much better would be just pass a random number generator into the function:</p>\n<pre><code>template <std::uniform_random_bit_generator<std::remove_reference_t<Gen>>\nauto get_random_card_index(std::vector<Card> const& cards, Gen&& gen)\n{\n auto dist = std::uniform_int_distribution{0, cards.size() - 1};\n\n return dist(gen);\n}\n</code></pre>\n<p>But this still isn't a great function, because it doesn’t take into account the case where the set of cards is empty.</p>\n<p>All these problems would evaporate if you just shuffled the deck once, and then picked from the top of the deck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T13:21:26.330",
"Id": "502519",
"Score": "3",
"body": "The only thing missing from this _tour de force_ is a mention that a proper shuffling algorithm is vital in a card game. The Fisher-Yates Shuffle an easily implemented and well known option: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle . Never try and roll your own shuffle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T16:09:55.493",
"Id": "502527",
"Score": "2",
"body": "@Jack good advice - I would add that you should just use `std::shuffle()` rather than reimplementing Fisher-Yates yourself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T18:09:15.570",
"Id": "502538",
"Score": "4",
"body": "Quite a dazzlingly thorough answer. But I would advocate for always using braces around if-blocks. The argument can be made from (1) stylistic consistency, (2) readability and (3) maintainability. (1) is obvious; (2) braces make it much easier to see the logical structure of the code when skimming quickly; (3) it's annoying if and when the time comes to add more logic to an if-block to add in braces (that really should have been there in the first place...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T19:02:51.270",
"Id": "502540",
"Score": "0",
"body": "Why never put `using namespace std;`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T20:13:56.870",
"Id": "502544",
"Score": "1",
"body": "Also, what are the problems caused by unsigned ints?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:32:40.270",
"Id": "502656",
"Score": "1",
"body": "@AnnoyinC RE: your first question: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:34:20.930",
"Id": "502657",
"Score": "1",
"body": "@AnnoyinC And for the second: https://stackoverflow.com/questions/30395205/why-are-unsigned-integers-error-prone"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T21:03:44.353",
"Id": "502673",
"Score": "0",
"body": "I got home and noticed that rank was a string and not an int, also missing semicolon. Rank and value need to be defined because in BlackJack a king is worth 10 points but in poker a king is higher than a queen. I'm Still trying to define ace to be hi or low. My random function should not be static.Thank you for your input. I get no I tenet a home so I bring my phone out and copy web pages and pdf's to take home and read. That was a good answer and will consider this as answered.I am just super stoked that I made a BlackJack game that worKS.Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-05T09:27:57.173",
"Id": "520821",
"Score": "0",
"body": "Instead of boost static vector, you should use `std::array`. Also, most likely this application is going to run in an interactive shell so `'\\n'` is also an implicit flush so the whole section about `std::endl` is moot, see: https://stackoverflow.com/a/25569849/2498188. `std::endl` clearly denotes the system specific new line sequence (instead of quietly converting `'\\n'` to CRLF on eg Windows) and imho is more readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T20:55:47.877",
"Id": "520940",
"Score": "1",
"body": "@EmilyL. 1) You can’t use `std::array` here. The size of the deck changes. If you use `std::array`, then there will be 52 cards in the deck… there will **ALWAYS** be 52 cards in the deck, which makes it pretty useless; you can’t remove any cards from it when you deal. The whole point of using `std::vector` or `boost::container::static_vector` is that your deck will never have *more* than 52 cards (when no cards have been dealt and all are in the deck), but it can have *less* as you deal cards out to the players. The deck size changes. `array.size()` is fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T20:56:16.013",
"Id": "520941",
"Score": "0",
"body": "@EmilyL. 2a) Basically everything you said about `std::endl` is wrong. `std::endl` has absolutely nothing to do with system specific newline sequences. `os << endl;` is [is literally defined in the standard](https://timsong-cpp.github.io/cppwp/ostream.manip#lib:endl) as just `os.put('\\n'); os.flush();` (except that `'\\n'` is widened with `os.widen()` to handle non-`char` streams). Newline translation is done by the stream buffer—usually `basic_filebuf` in text mode. *All* newlines will be translated by the stream buffer, not just the newlines `endl` puts in there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T20:57:25.910",
"Id": "520942",
"Score": "0",
"body": "@EmilyL. 2b) And since `endl` is literally `'\\n'` then a flush, it is absolutely *not* “moot” that you use it, whether line-buffered or not. If your output is line-buffered, then `cout << '\\n'` does *one* flush (when it writes the line), while `cout << endl` does *two* flushes (when it writes the line, and then the call to `flush()`). If your output is *not* line-buffered, `cout << '\\n'` does *zero* flushes (unless the buffer is full, of course), while `cout << endl` does at least *one*. `endl` *always* causes an extra, usually unnecessary flush… which is why it’s pretty much always wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-06T21:01:08.760",
"Id": "520943",
"Score": "0",
"body": "@EmilyL. 2c) Finally, that StackOverflow answer is just plain wrong. `sync_with_stdio()` has *nothing* to do with line buffering. It just turns off the interlock between `<iostream>` stuff and `<stdio>` stuff. When `cout` is line-buffered and you do `sync_with_stdio(false)`, `cout << '\\n'` will still trigger a flush… but *only* `cout` will be flushed, not the C stream buffer `stdout`. With `printf('a'); cout << 'b'; cout << '\\n';`, *normally* `'n'` will trigger a flush that prints “ab”. But with `sync_with_stdio(false)`, the `'n'` will trigger a flush that just *probably* prints just “b”."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-07T21:42:32.367",
"Id": "521007",
"Score": "0",
"body": "@ahazybellcord I would advocate the opposite: I heard someone talking about this at one of the major conferences, but I don't recall the exact talk. _Instead, ask \"why isn't it one line\"?_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T19:26:39.667",
"Id": "521057",
"Score": "0",
"body": "@JDługosz ...but you've provided zero counter-arguments. I've asked that question and given *three* separate arguments for why you _should_ always use braces around if-statements even if the conditionally-executed code is a single line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-08T21:39:24.613",
"Id": "521069",
"Score": "0",
"body": "@ahazybellcord OK, #2 is subjective; removing distracting visual noise is more readable and more fits on the screen, #1 different things should look different. If you need more than one line, it's a \"dive into\" more detail rather than a simple thing. Maybe you have not decomposed enough. #3 no, it's not. Or, maybe the extra work will make you consider that the addition should be put into the function call instead or that the statement ought to be refactored."
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T05:15:30.710",
"Id": "254782",
"ParentId": "254769",
"Score": "28"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-15T23:41:53.677",
"Id": "254769",
"Score": "9",
"Tags": [
"c++",
"c++11",
"playing-cards"
],
"Title": "Deck of Cards written in C++"
}
|
254769
|
<p>Here is a (reduced version of) a module for Bsplines, which I have used multiple times for my work on Atomic, Molecular, and Optical physics (AMO, in the trade lingo, a.k.a. "I love", in Italian). I wrote it more than a decade ago, with the occasional tweak, and it would benefit from a review. It is a bit long, but it is quite useful: it can compute arbitrary matrix elements between B-splines of the form</p>
<p><span class="math-container">$$ \int dx [D^n B_i(x)] f(x;\mathbf{Y}) [D^m B_j(x)] $$</span></p>
<p>where <span class="math-container">\$B_i(x)\$</span> and <span class="math-container">\$B_j(x)\$</span> are Bspline functions, <span class="math-container">\$D^n\$</span> represents the n-th derivative, and <span class="math-container">\$f(x;\mathbf{Y})\$</span> is an arbitrary real function of real variable that takes an optional array of parameters <span class="math-container">\$\mathbf{Y}\$</span>. I illustrate some of the capabilities of the module with a short test at the end that computes the eigenvalues of a quantum harmonic oscillator.
The code can arguably be improved here and there, but otherwise it works fine and I hope it can be interesting to some.</p>
<p>The main question that I have is on how to pass the function in the integral. At the moment, I pass it as a pointer to a pure function with a specified interface, and I have to explicitly define that function in the code, which is extremely annoying. I would rather like to be able to define arbitrary anonymous functions (lambdas) at run time, but I am not aware of how this could be done in Fortran. Any suggestion?</p>
<p>Note: the code require blas and lapack to be linked. If you have ifort and mkl, you can compile it with the options <code>-O2 -mkl</code>.
For folks not familiar with the simple syntax of modern Fortran, I suggest the following <a href="https://fortran-lang.org/learn/quickstart" rel="nofollow noreferrer">quick modern Fortran tutorial</a>.</p>
<pre class="lang-fortran prettyprint-override"><code>!! ModuleBSplines, Copyright (C) 2020 Luca Argenti, PhD - Some Rights Reserved
!! ModuleBSplines is licensed under a
!! Creative Commons Attribution-ShareAlike 4.0 International License.
!! A copy of the license is available at <http://creativecommons.org/licenses/by-nd/4.0/>.
!!
!! Luca Argenti is Associate Professor of Physics, Optics and Photonics
!! Department of Physics and the College of Optics
!! University of Central Florida
!! 4111 Libra Drive, Orlando, Florida 32816, USA
!! email: luca.argenti@ucf.edu
module ModuleBSpline
use, intrinsic :: ISO_FORTRAN_ENV
implicit none
private
interface
Pure DoublePrecision function D2DFun( x, parvec )
DoublePrecision , intent(in) :: x
DoublePrecision, optional, intent(in) :: parvec(*)
end function D2DFun
end interface
public D2DFun
! {{{ Private Attributes
!
logical :: INITIALIZED = .FALSE.
!
integer , parameter :: IOMSG_LENGTH= 100
!.. Local Gaussian weights
DoublePrecision, parameter :: PI = 3.14159265358979323846d0
DoublePrecision, parameter :: GAUSS_POINTS_CONVERGENCE_THRESHOLD = 2.d-15
integer , parameter :: NGAUSS = 64
DoublePrecision :: Gauss_points(NGAUSS)
DoublePrecision :: Gauss_weight(NGAUSS)
!
!.. Local Factorial Parameters and variables
integer, parameter :: DIMFACT = 127
DoublePrecision :: fact(0:DIMFACT)
DoublePrecision :: tar(0:((DIMFACT+1)*(DIMFACT+2)/2-1))
DoublePrecision :: parfactMat(0:DIMFACT,0:DIMFACT)
!
!.. B-spline parameters
integer , parameter :: MAX_NUMBER_NODES = 10000
DoublePrecision, parameter :: NOD_THRESHOLD = 1.d-15
integer , parameter :: MAXNR = 20
!
! }}}
!> Set of B-splines (spline basis functions)
!!
! {{{ Detailed Description
!> The spline are defined as piecewise polynomials of order \f$k\f$
!! (maximum degree \f$k-1\f$), \f$\mathcal{C}^\infty\f$ everywhere, except at a fixed set of knots \f$\{t_i\}\f$
!! where they are at least \f$\mathcal{C}^{k_i-2}\f$, with \f$k \geq k_i\geq 1\f$.
!! \f$\nu_i=k-k_i+1\f$ is called the knot multiplicity because the same spline basis can be obtained
!! from a basis with \f$\sum_i \nu_i\f$ maximally regular knots in the limit where sets of \f$\nu_i\f$
!! contiguous knots coalesce to \f$i\f$-th knots. In other terms, the spline space is specified by an order
!! \f$k\f$ and a non-decreasing set of knots. The total dimension of spline space is \f$n+k\f$, but if
!! we specialize to the subset which is zero below the lowest and above the highest knots we are left
!! with a space of dimension \f$n-k\f$. As a consequence every spline extends at least over \f$k\f$ adjacent
!! intervals (\f$k+1\f$ consecutive knots, when counted with their multiplicity). The \f$n-k\f$ independent
!! splines restricted to \f$k\f$ intervals, clearly a basis of the spline space, are commonly called B-splines.
!! Following deBoor\cite{deBoor}, we define the \f$i\f$-th B-spline \f$B_i^k(x)\f$ of order \f$k\f$ and which
!! extends from the knot \f$t_i\f$ to the knot \f$t_{i+k}\f$, as follows:
!! \f{eqnarray}
!! B_i^1(x)&=&\theta(x-t_i)\,\cdot\,\theta(t_{i+1}-x)\\
!! B_i^k(x)&=&\frac{x-t_i}{t_{i+k-1}-t_i}\,\,
!! B_i^{k-1}(x)+\frac{t_{i+k}-x}{t_{i+k}-t_{i+1}}\,\,
!! B_{i+1}^{k-1}(x).
!! \f}
!! In the following, unless otherwise stated, we shall refer to standard set of knots where the
!! first and last breakpoints are \f$k\f$ times degenerate, while the other nodes are non degenerate:
!! \f[
!! t_1=t_2=\ldots=t_k\leq t_{k+1}\leq\ldots\leq t_{n-k}\leq t_{n-k+1}=t_{n-k+2}=\ldots=t_{n}
!! \f]
!! The use of B-splines in atomic and molecular physics calculations is reviewed in
!! [\cite{rpp.64.1815}](http://iopscience.iop.org/0034-4885/64/12/205/).
!!
!! B-splines are invariant upon affine transformations: that is, if
!! \f{equation}
!! \mathrm{if}\quad x\to x'=a\,x +b,\quad t_i\to t_i'=a\,t_i+b\quad\mathrm{then}
!! \quad{B_i^{k}}'(x')=B_i^k(x).
!! \f}
!!
!! It is useful to define the \f$L^2\f$-normalized B-splines as
!! \f{equation}
!! \bar{B}_i(x)\equiv B_i(x)/\|B_i\|_{L^2}
!! \f}
!!
! }}}
type, public :: ClassBSpline
!
private
!> Number of non-degenerate nodes.
integer :: NNodes
!
!> Spline order.
!! A B-spline of order \f$ k\f$ is a piecewise polynomials
!! of order \f$k-1\f$ which extends over \f$k\f$ intervals (including
!! degenerate intervals, i.e., those with zero length).
!! The quality of the Bspline evaluation is severely compromised
!! for high order. At order around 35, in the case of just two nodes
!! (which is the most demanding condition), the numerical error starts
!! being of the same order of magnitude of the function itself.
!! For order \f$\sim\f$20, there are occasional points of irregularity
!! for a reasonable number of intervals (e.g.,\f$\geq 10\f$). Anyhow,
!! these caveats arise only in cases which already lie outside
!! the range of applicability of the BSplines as a variational basis,
!! which is above order 12 or so.
integer :: Order
!
!> Total number of B-spline.
!! \f[
!! NBsplines = NNodes + Order - 2
!!\f]
integer :: NBSplines
!
!> grid which contains the node positions.
!! - \f$g_{-k+1}\,=\,g_{-k+2}\,=\,\cdots\,=\,g_{-1}\,=\,g_0\f$
!! is the first \f$ k\f$ times degenerate node.
!! - \f$g_{n-1}\,=\,g_{n}\,=\,\cdots\,=\,g_{n+k-2}\f$ is the
!! last \f$ k\f$ times degenerate node.
!! The set of distinct nodes is mapped to the positions [0:n-1] of grid;
!! and hence, the upper bound of the i-th BSpline support is grid(i)
real(kind(1d0)), allocatable :: grid(:)
!
!> Normalization constants.
!! \f[
!! \mathrm{f}_i=\|B_i\|_{L^2}^{-1}=\frac{1}{ \sqrt{ \langle B_i | B_i \rangle } }
!! \f]
real(kind(1d0)), private, allocatable :: f(:)
!
!
!> Matrix of polynomial coefficients.
!! The support $\mathcal{D}_i$ of the \f$i\f$-th B-spline comprises \f$k\f$ consecutive intervals:
!! \f[
!! \mathcal{D}_i = [g_{i-k},g_i] = [g_{i-k+1},g_{i-k+1}] \cup \cdots \cup [g_{i-1}:g_i].
!! \f]
!! If we enumerate the individual intervals from \f$0\f$ to \f$k-1\f$, the explicit expression of
!! the \f$i\f$-th B-spline in interval $j$ is
!! \f[
!! B_i(x) = \sum_{m=0}^{k-1}
!! \left(
!! \frac{x-g_{i-k+j}}{g_{i-k+j+1}-g_{i-k+j}}
!! \right)^m \,\, c(m,j,i)
!! \f]
real(kind(1d0)), private, allocatable :: c(:,:,:)
!
!> Indicates whether ClassBSpline has been initialized or not.
logical, private :: INITIALIZED=.FALSE.
!
contains
!.. Basics
generic :: Init => BSplineInit
procedure :: Free => BSplineFree
procedure :: Save => ClassBSpline_Save
procedure :: Load => ClassBSpline_Load
!.. Accessors
!> Gets the number of nodes.
procedure :: GetNNodes => BSplineGetNNodes
!> Gets the B-splines order.
procedure :: GetOrder => BSplineGetOrder
!> Gets the number of B-splines.
procedure :: GetNBSplines => BSplineGetNBSplines
!> Gets the position of a requested node.
procedure :: GetNodePosition => BSplineNodePosition
!> Gets the normalization factor of a requested B-spline.
procedure :: GetNormFactor => BSplineNormalizationFactor
!> Evaluates either a choosen B-spline function,
!! or a linear combination of B-splines, both evaluated in certain position.
generic :: Eval => BSplineEval, BSplineFunctionEval
!> Tabulates in a slected domain either a choosen B-spline function,
!! or a linear combination of B-splines.
generic :: Tabulate => BSplineTabulate, BSplineFunctionTabulate
!> Computes the integral
!! \f[
!! \int_{a}^{b} r^{2}dr
!! \frac{d^{n_{1}}Bs_{i}(r)}{dr^{n_{1}}} f(r)
!! \frac{d^{n_{2}}Bs_{j}(r)}{dr^{n_{2}}}
!!\f]
!! Where \f$f(r)\f$ is a local operator, and if a break point \f$BP\f$ is introduced,
!! then the integral is splitted in two parts
!! \f[
!! \int_{a}^{BP} r^{2}dr
!! \frac{d^{n_{1}}Bs_{i}(r)}{dr^{n_{1}}} f(r)
!! \frac{d^{n_{2}}Bs_{j}(r)}{dr^{n_{2}}} +
!! \int_{BP}^{b} r^{2}dr
!! \frac{d^{n_{1}}Bs_{i}(r)}{dr^{n_{1}}} f(r)
!! \frac{d^{n_{2}}Bs_{j}(r)}{dr^{n_{2}}}
!! \f]
generic :: Integral => BSplineIntegral
procedure :: BSplineIntegral
!.. Assignment
!> Copies the B-spline set from one ClassBSpline to another.
generic, public :: ASSIGNMENT(=) => CopyBSplineSet
!.. Private Interface
procedure, private :: BSplineInit
procedure, private :: CopyBSplineSet
procedure, private :: BSplineEval
procedure, private :: BSplineFunctionEval
procedure, private :: BSplineTabulate
procedure, private :: BSplineFunctionTabulate
end type ClassBSpline
contains
subroutine ClassBspline_Save( self, uid )
class(ClassBspline), intent(in) :: self
integer , intent(in) :: uid
integer :: i
write(uid,"(*(x,i0))") &
self%Nnodes, self%Order, self%NBsplines, &
size(self%grid), size(self%f), &
(size(self%c,i),i=1,3)
write(uid,"(*(x,e24.16))") self%grid
write(uid,"(*(x,e24.16))") self%f
write(uid,"(*(x,e24.16))") self%c
end subroutine ClassBspline_Save
subroutine ClassBspline_Load( self, uid )
class(ClassBspline), intent(out) :: self
integer , intent(in) :: uid
integer :: ng, nf, nc1, nc2, nc3
call self%free()
read(uid,*) self%Nnodes, self%Order, self%NBsplines, &
ng, nf, nc1, nc2, nc3
allocate(self%grid(ng))
allocate(self%f (nf))
allocate(self%c(nc1,nc2,nc3))
read(uid,*) self%grid
read(uid,*) self%f
read(uid,*) self%c
end subroutine ClassBspline_Load
!> Initialize module basic constants
subroutine Init_Spline_Module()
call InitGaussPoints
call InitFactorials
INITIALIZED=.TRUE.
end subroutine Init_Spline_Module
subroutine CheckInitialization(s)
Class(ClassBSpline), intent(in) :: s
if(.not.s%INITIALIZED) error stop
end subroutine CheckInitialization
!> Initialize the points and weights for
!! Gauss integration
subroutine InitGaussPoints()
integer :: i,j
DoublePrecision :: p1, p2, p3, pp, z, z1
do i=1,floor((NGAUSS+1)/2.d0)
z=cos(PI*(i-.25d0)/(NGAUSS+.5d0))
inna : do
p1=1.d0
p2=0.d0
do j=1,NGAUSS
p3=p2
p2=p1
p1=((2.d0*j-1.d0)*z*p2-(j-1.d0)*p3)/j
enddo
pp=NGAUSS*(z*p1-p2)/(z*z-1.d0)
z1=z
z=z1-p1/pp
if(abs(z-z1)<=GAUSS_POINTS_CONVERGENCE_THRESHOLD)exit inna
enddo inna
Gauss_Points(i)=(1.d0-z)/2.d0
Gauss_Points(NGAUSS+1-i)=(1.d0+z)/2.d0
Gauss_Weight(i)=1.d0/((1.d0-z*z)*pp*pp)
Gauss_Weight(NGAUSS+1-i)=1.d0/((1.d0-z*z)*pp*pp)
enddo
end subroutine InitGaussPoints
subroutine InitFactorials()
integer :: i,j,k,n
!
!Initialize Factorials
fact(0)=1.d0
do i = 1, DIMFACT
fact(i)=fact(i-1)*dble(i)
enddo
!
!.. Initialize Binomials
k=0
tar=0.d0
do i = 0,DIMFACT
do j = 0,i
tar(k)=fact(i)/fact(i-j)/fact(j)
k=k+1
enddo
enddo
!
parfactmat=1.d0
do n=1,DIMFACT
do k=1,n
do i=n-k+1,n
parfactmat(n,k)=parfactmat(n,k)*dble(i)
enddo
enddo
enddo
!
end subroutine InitFactorials
integer function BSplineGetOrder(s) result(Order)
class(ClassBSpline), intent(in) :: s
Order=s%Order
end function BSplineGetOrder
integer function BSplineGetNNodes(s) result(NNodes)
class(ClassBSpline), intent(in) :: s
NNodes=s%NNodes
end function BSplineGetNNodes
integer function BSplineGetNBSplines(s) result(NBSplines)
class(ClassBSpline), intent(in) :: s
NBSplines=s%NBSplines
end function BSplineGetNBSplines
!> Return the position of a node
DoublePrecision function BSplineNodePosition(SplineSet,Node) result(Position)
Class(ClassBSpline), intent(in) :: SplineSet
integer , intent(in) :: Node
if( Node <= 1 )then
Position = SplineSet%Grid(0)
elseif( Node >= SplineSet%NNodes )then
Position = SplineSet%Grid( SplineSet%NNodes-1 )
else
Position = SplineSet%Grid( Node-1 )
endif
return
end function BSplineNodePosition
!> Return the position of a node
DoublePrecision function BSplineNormalizationFactor(SplineSet,Bs) &
result(Normalization)
Class(ClassBSpline), intent(in) :: SplineSet
integer , intent(in) :: Bs
Normalization = 0.d0
if(Bs<1.or.Bs>SplineSet%NBSplines)return
Normalization=SplineSet%f(Bs)
end function BSplineNormalizationFactor
!> Copies the B-spline set sOrigin to sDestination
subroutine CopyBSplineSet(sDestination,sOrigin)
Class(ClassBSpline), intent(inout):: sDestination
Class(ClassBSpline), intent(in) :: sOrigin
!
sDestination%NNodes=sOrigin%NNodes
sDestination%Order=sOrigin%Order
sDestination%NBSplines=sOrigin%NBSplines
!
if(allocated(sDestination%Grid))deallocate(sDestination%Grid)
allocate(sDestination%Grid(1-sDestination%Order:sDestination%NBSplines))
sDestination%Grid=sOrigin%Grid
!
if(allocated(sDestination%c))deallocate(sDestination%c)
allocate(sDestination%c(&
0:sDestination%Order-1 ,&
0:sDestination%Order-1 ,&
1:sDestination%NBSplines+sDestination%Order-2))
sDestination%c=sOrigin%c
!
if(allocated(sDestination%f))deallocate(sDestination%f)
allocate(sDestination%f(sDestination%NBSplines))
sDestination%f=sOrigin%f
!
sDestination%INITIALIZED=.TRUE.
end subroutine CopyBSplineSet
subroutine CheckNodesAndOrder(NumberOfNodes,Order,STAT)
integer, intent(in) :: NumberOfNodes, Order
integer, intent(out) :: STAT
STAT = -1; if ( NumberOfNodes < 2 ) return
STAT = -2; if ( order < 1 ) return
STAT = 0
end subroutine CheckNodesAndOrder
!> Initialize a BSpline set
Subroutine BSplineInit(s,NumberOfNodes,order,grid,IOSTAT)
!
!> Bspline basis set to be initialized
Class(ClassBSpline), intent(inout) :: s
!> Number of Nodes
integer , intent(in) :: NumberOfNodes
!> Spline order
integer , intent(in) :: order
!> Grid of nodes (without repetition of degenerate nodes)
DoublePrecision , intent(in) :: grid(1:NumberOfNodes)
!> IOSTAT = 0 on successful exit, IOSTAT/=0 otherwise
!! If IOSTAT is not specified, the programs terminates with
!! an error.
integer , intent(out), optional :: IOSTAT
!Local variables
integer :: i, Bs, Status
procedure(D2DFUN), pointer :: FunPtr
if(present(IOSTAT)) IOSTAT=0
if(.not.INITIALIZED)call Init_Spline_Module()
!.. Check input
call CheckNodesAndOrder(NumberOfNodes,Order,Status)
if(Status/=0)then
if(present(IOSTAT))then
IOSTAT=Status
return
endif
error stop
endif
s%NNodes = NumberOfNodes
s%Order = order
s%NBSplines = NumberOfNodes + order - 2
!.. Check Grid format
if( LBOUND(Grid,1) > 1 .or. &
UBOUND(Grid,1) < NumberOfNodes ) then
if(present(IOSTAT))then
IOSTAT=-4
return
endif
error stop
endif
do i=2,NumberOfNodes
if( Grid(i) < Grid(i-1) )then
if(present(IOSTAT))then
IOSTAT=1
return
else
error stop
endif
endif
enddo
!.. Maps the Grid to [0:n-1]; hence, the upper bound
! of the i-th BSpline support is g(i)
if( allocated( s%Grid ) ) deallocate( s%Grid )
allocate( s%Grid( -(order-1) : NumberOfNodes-1 + order-1 ) )
s%Grid( 1-order : -1 ) = Grid(1)
s%Grid( 0:NumberOfNodes-1 ) = Grid(1:NumberOfNodes)
s%Grid( NumberOfNodes:NumberOfNodes+order-2 ) = Grid(NumberOfNodes)
!.. Initializes the BSpline coefficients normalized
! so that the B-spline set is a partition of unity
!..
if( allocated( s%c ) ) deallocate( s%c )
allocate( s%c( 0:order-1, 0:order-1, 1:s%NBSplines ) )
s%c = 0.d0
do Bs=1,s%NBSplines
call ComputeCoefficientsSingleBSpline(s%Order,s%Grid(Bs-s%Order),s%c(0,0,Bs))
enddo
s%INITIALIZED=.TRUE.
!.. Initialize the normalization factors
! ||Bs_i(x)*s%f(i)||_L2=1.d0
!..
if( allocated( s%f ) ) deallocate( s%f )
allocate( s%f( 1 : s%NBSplines ) )
s%f = 0.d0
funPtr=>Unity
do i = 1, s%NBSplines
s%f(i)=1.d0/sqrt(s%Integral(FunPtr,i,i))
enddo
end Subroutine BSplineInit
Pure DoublePrecision function Unity(x,parvec) result(y)
DoublePrecision, intent(in) :: x
DoublePrecision, optional, intent(in) :: parvec(*)
y=1.d0
end function Unity
!> Given the order and a set of order+1 consecutive nodes,
!> builds the corresponding (uniquely defined) B-spline.
subroutine ComputeCoefficientsSingleBSpline(order,vec,Coefficients)
!
!> Order of the B-spline = number of (possibly degenerate)
!> intervals that form the B-spline support = Polynomials degree + 1
!> (e.g., order=4 means piecewise cubic polynomials, which require
!> four parameters: \f$ a_0 + a_1 x + a_2 * x^2 + a_3 * x^3 \f$.
integer , intent(in) :: order
!
!> vector of order+1 nodes. For Order = 5, for example, vec contains
!> the six bounds of the five consecutive intervals that form the
!> support of the B-spline, indexed from ONE to SIX.
!
! vec(1) vec(2) vec(3) vec(4) vec(5) vec(6)
! |-------|---------|-------|------|---------|
DoublePrecision, intent(in) :: vec(1:order+1)
!
!> Matrix of polynomial coefficients in each interval.
DoublePrecision, intent(out) :: Coefficients(0:order-1,0:order-1)
!
!Local variables
integer :: k, inter, tempBs
DoublePrecision :: SpanBSpline
DoublePrecision :: SpanCurrentInterval
DoublePrecision :: SpanPriorToInterval
DoublePrecision :: SpanToTheEnd
DoublePrecision :: FactorConstant
DoublePrecision :: FactorMonomial
DoublePrecision, allocatable :: coe(:,:,:,:)
!
!.. Computes the B-spline in each available
! sequence of order consecutive intervals
!
!
allocate( coe(0:order-1,0:order-1,order,order) )
coe=0.d0
coe(0,0,1,:)=1.d0
!
!.. Cycle over the spline order
!
do k = 2, order
!
!.. Cycle over the (temporary) Bsplines available
! for any given order, which must all be computed
!
do tempBs = 1, order - k + 1
!
!.. Each B-spline of order k is obtained as the sum of
! the contribution from the two B-splines of order k-1
! whose support is comprised in that of the final
! B-spline.
!
!.. Contribution of the first B-spline of order k-1
! counted only if the B-spline is not degenerate
!..
SpanBSpline = vec(tempBs+k-1) - vec(tempBs)
if( SpanBSpline > NOD_THRESHOLD )then
do inter=0,k-2
!
!.. Constant Component
SpanPriorToInterval = vec(tempBs+inter) - vec(tempBs)
FactorConstant = SpanPriorToInterval / SpanBSpline
coe(0:k-2,inter,k,tempBs) = coe(0:k-2,inter,k,tempBs) + &
coe(0:k-2,inter,k-1,tempBs) * FactorConstant
!
!.. Monomial Component
SpanCurrentInterval = vec(tempBs+inter+1) - vec(tempBs+inter)
FactorMonomial = SpanCurrentInterval / SpanBSpline
coe(1:k-1,inter,k,tempBs) = coe(1:k-1,inter,k,tempBs) + &
coe(0:k-2,inter,k-1,tempBs) * FactorMonomial
!
enddo
endif
!
!.. Contribution of the second B-spline of order k-1
! counted only if the B-spline is not degenerate
!..
SpanBSpline = vec(tempBs+k) - vec(tempBs+1)
if( SpanBSpline > NOD_THRESHOLD )then
do inter=1,k-1
!
!.. Constant Component
SpanToTheEnd = vec(tempBs+k)-vec(tempBs+inter)
FactorConstant = SpanToTheEnd / SpanBSpline
coe(0:k-2,inter,k,tempBs) = coe(0:k-2,inter,k,tempBs) + &
coe(0:k-2,inter-1,k-1,tempBs+1) * FactorConstant
!
!.. Monomial Component
SpanCurrentInterval = vec(tempBs+inter+1) - vec(tempBs+inter)
FactorMonomial = SpanCurrentInterval / SpanBSpline
coe(1:k-1,inter,k,tempBs) = coe(1:k-1,inter,k,tempBs) - &
coe(0:k-2,inter-1,k-1,tempBs+1) * FactorMonomial
!
enddo
endif
!
enddo
enddo
!
Coefficients=coe(:,:,order,1)
deallocate(coe)
!
end subroutine ComputeCoefficientsSingleBSpline
!> Deallocates a ClassBSpline variable
subroutine BSplineFree(s)
Class(ClassBSpline), intent(inout) :: s
if(allocated(s%Grid))deallocate(s%Grid)
if(allocated(s%f))deallocate(s%f)
if(allocated(s%c))deallocate(s%c)
s%NNodes=0
s%Order=0
s%NBSplines=0
s%INITIALIZED=.FALSE.
return
end subroutine BSplineFree
!> Returns n if x is in \f$(g_n,g_{n+1}]\f$.
integer function which_interval(x,s)
!
DoublePrecision , intent(in) :: x
type(ClassBSpline), intent(in) :: s
!
integer, save :: i1 = 0
integer :: i2
!
if(x>s%Grid(i1).and.x<=s%Grid(i1+1))then
which_interval=i1
return
endif
if(x>s%Grid(i1+1).and.x<=s%Grid(min(i1+2,s%NNodes+s%Order-1)))then
which_interval=i1+1
return
endif
i1=0
i2=0
!
if(x<s%Grid(0))then
which_interval=-1
return
elseif(x>s%Grid(s%NNodes-1))then
which_interval=s%NNodes!-1
return
endif
if(x<s%Grid(i1))i1=0
if(x>s%Grid(i2))i2=s%NNodes-1
do while(i2-i1>1)
if(x>s%Grid((i2+i1)/2))then
i1=(i1+i2)/2
else
i2=(i1+i2)/2
endif
enddo
which_interval=i1
return
end function which_interval
!> Computes the n-th derivative of B-spline Bs, \f$ n=0,1,2,\ldots\f$
!!
! {{{ Detailed Description:
!! ---------------------
!! B-splines are positive: expansion coefficients of represented functions are
!! akin to the functions themselves. Without rapid oscillations of coefficients,
!! the cancellation errors are kept at minimum.
!! In particular \cite{deBoor},
!! if \f$f=\sum_i B_ic_i\f$
!! \f{equation}
!! \left|c_i-\frac{M+m}{2}\right|\leq D_{k}\frac{M-m}{2},\quad m
!! =\min_{x\in[a,b]} f(x),\,\,M=\max_{x\in[a,b]}f(x)
!! \f}
!! where \f$D_k\f$ is a constant that depends only on \f$k\f$ and not on the
!! particular partition of the \f$[a,b]\f$ interval.
!! At any point, the evaluation of a linear combination of B-splines
!! requires the evaluation of \f$k\f$ basis functions only.
! }}}
DoublePrecision function BSplineEval(s,x,Bs,n_)
Class(ClassBSpline), intent(in) :: s
DoublePrecision , intent(in) :: x
integer , intent(in) :: Bs
integer, optional , intent(in) :: n_
!
integer :: i,j,k,n
DoublePrecision :: r,a,w,OneOverInterval,OneOverIntervalToTheN
!
call CheckInitialization(s)
!
BSplineEval=0.d0
if(Bs<1.or.Bs>s%NBSplines)return
!
n=0; if(present(n_)) n=n_
if(n<0) error stop
if(n>=s%Order)return
!
i=which_interval(x,s)
if( i<max(0,Bs-s%Order).or.&
i>min(s%NNodes-1,Bs-1))return
!
j=i-Bs+s%Order
OneOverInterval=1.d0/(s%Grid(i+1)-s%Grid(i))
r=(x-s%Grid(i))*OneOverInterval
!
a=1.d0
w=0.d0
do k=n,s%Order-1
w=w+a*parfactmat(k,n)*s%c(k,j,Bs)
a=a*r
enddo
!
OneOverIntervalToTheN=1.d0
do k=1,n
OneOverIntervalToTheN=OneOverIntervalToTheN*OneOverInterval
enddo
BSplineEval=w*OneOverIntervalToTheN
!
return
end function BSplineEval
!> Computes the k-th derivative of a function expressed in terms of B-splines.
DoublePrecision function BSplineFunctionEval(s,x,fc,k,SKIP_FIRST,Bsmin,Bsmax)
class(ClassBSpline), intent(in) :: s
DoublePrecision , intent(in) :: x
DoublePrecision , intent(in) :: fc(:)
integer, optional , intent(in) :: k
logical, optional , intent(in) :: SKIP_FIRST
integer, optional , intent(in) :: Bsmin,Bsmax
integer :: Bsmi, Bsma
integer :: Bs,i,nskip
call CheckInitialization(s)
BSplineFunctionEval=0.d0
i=which_interval(x,s)
if(i<0.or.i>s%NNodes-2)return
Bsmi=1
nskip=0
if(present(SKIP_FIRST))then
if(SKIP_FIRST)then
Bsmi=2
nskip=1
endif
endif
if(present(Bsmin))then
Bsmi = max(Bsmin,Bsmi)
nskip= max(Bsmi-1,nskip)
endif
Bsmi=max(Bsmi,i+1)
Bsma = min(s%NBSplines,i+s%Order)
if(present(Bsmax)) Bsma = min(Bsmax,Bsma)
do Bs=Bsmi,Bsma
BSplineFunctionEval=BSplineFunctionEval+s%Eval(x,Bs,k)*fc(Bs-nskip)
enddo
return
end function BSplineFunctionEval
!> Computes the k-th derivatives of a choosen B-spline evaluated in a position array.
subroutine BSplineTabulate(s,ndata,xvec,yvec,Bs,n_)
Class(ClassBSpline), intent(in) :: s
integer , intent(in) :: ndata
DoublePrecision , intent(in) :: xvec(1:ndata)
DoublePrecision , intent(out):: yvec(1:ndata)
integer , intent(in) :: Bs
integer, optional , intent(in) :: n_
!
integer :: i,n
n=0;if(present(n_))n=n_
do i=1,ndata
yvec(i)=s%Eval(xvec(i),Bs,n)
enddo
end subroutine BSplineTabulate
!> Computes the k-th derivatives of a function expressed in terms of B-splines and evaluated in an array of positions.
subroutine BSplineFunctionTabulate(s,ndata,xvec,yvec,FunVec,n_,SKIP_FIRST)
Class(ClassBSpline), intent(in) :: s
integer , intent(in) :: ndata
DoublePrecision , intent(in) :: xvec(1:ndata)
DoublePrecision , intent(out):: yvec(1:ndata)
DoublePrecision , intent(in) :: FunVec(:)
integer, optional , intent(in) :: n_
logical, optional , intent(in) :: SKIP_FIRST
logical :: SKIP_FIRST_LOC
!
integer :: i,n
SKIP_FIRST_LOC=.FALSE.
if(present(SKIP_FIRST))then
SKIP_FIRST_LOC=SKIP_FIRST
endif
n=0;if(present(n_))n=n_
do i=1,ndata
yvec(i)=s%Eval(xvec(i),FunVec,n,SKIP_FIRST=SKIP_FIRST_LOC)
enddo
end subroutine BSplineFunctionTabulate
!> Computes the integral
!! \f[
!! \int_{a}^{b} \frac{d^{n_{1}}Bs_{i}(r)}{dr^{n_{1}}} f(r)
!! \frac{d^{n_{2}}Bs_{j}(r)}{dr^{n_{2}}} r^{2}dr
!! \f]
!! Where \f$f(r)\f$ is a local operator, and if a break point \f$BP\f$
!! is introduced, then the integral is splitted in two parts
!! \f[
!! \int_{a}^{BP} \frac{d^{n_{1}}Bs_{i}(r)}{dr^{n_{1}}} f(r)
!! \frac{d^{n_{2}}Bs_{j}(r)}{dr^{n_{2}}} r^{2}dr +
!! \int_{BP}^{b} \frac{d^{n_{1}}Bs_{i}(r)}{dr^{n_{1}}} f(r)
!! \frac{d^{n_{2}}Bs_{j}(r)}{dr^{n_{2}}}r^{2}dr
!! \f]
DoublePrecision function BSplineIntegral( &
s , &
FunPtr , &
Bs1 , &
Bs2 , &
BraDerivativeOrder, &
KetDerivativeOrder, &
LowerBound , &
UpperBound , &
BreakPoint , &
parvec ) &
result( Integral )
!
Class(ClassBSpline) , intent(in) :: s
procedure(D2DFun) , pointer :: FunPtr
integer , intent(in) :: Bs1
integer , intent(in) :: Bs2
integer , optional, intent(in) :: BraDerivativeOrder
integer , optional, intent(in) :: KetDerivativeOrder
DoublePrecision, optional, intent(in) :: LowerBound
DoublePrecision, optional, intent(in) :: UpperBound
DoublePrecision, optional, intent(in) :: BreakPoint
DoublePrecision, optional, intent(in) :: Parvec(*)
!
integer :: n1, n2, iostat
DoublePrecision :: a, b
real(kind(1d0)) :: NewBreakPoint
!
Integral=0.d0
call CheckInitialization(s)
call CheckParameters( iostat )
if( iostat/=0 )return
if( present(BreakPoint) )then
!***
if ( BreakPoint < a ) then
NewBreakPoint = a + epsilon(1d0)
elseif ( BreakPoint > b ) then
NewBreakPoint = b - epsilon(1d0)
end if
!***
Integral = &
BSplineDriverIntegral(s,FunPtr,Bs1,Bs2,n1,n2, a, BreakPoint, Parvec ) + &
BSplineDriverIntegral(s,FunPtr,Bs1,Bs2,n1,n2, NewBreakPoint, b, Parvec )
else
Integral = BSplineDriverIntegral(s,FunPtr,Bs1,Bs2,n1,n2,a,b, Parvec )
endif
!
return
!
contains
!
subroutine CheckParameters( IOStat )
integer, intent(out) :: IOStat
call CheckBSplineIndexes( IOStat ); if( IOStat /= 0 ) return
call CheckIntegralBounds( IOStat ); if( IOStat /= 0 ) return
call CheckDerivativeOrder
end subroutine CheckParameters
!
subroutine CheckBSplineIndexes( IOStat )
integer, intent(out) :: IOStat
IOStat=1
if( min(Bs1,Bs2) < 1 ) return
if( max(Bs1,Bs2) > s%NBSplines ) return
if( abs(Bs1-Bs2) >= s%Order ) return
IOStat=0
end subroutine CheckBSplineIndexes
!
subroutine CheckIntegralBounds( IOStat )
integer, intent(out) :: IOStat
IOStat=1
a = s%Grid( max(Bs1,Bs2) - s%Order )
b = s%Grid( min(Bs1,Bs2) )
if(present(LowerBound))then
if( LowerBound >= b )return
a=max(a,LowerBound)
endif
if(present(UpperBound))then
if( UpperBound <= a )return
b=min(b,UpperBound)
endif
IOStat=0
end subroutine CheckIntegralBounds
!
subroutine CheckDerivativeOrder
n1=0; if(present(BraDerivativeOrder)) n1=BraDerivativeOrder
n2=0; if(present(KetDerivativeOrder)) n2=KetDerivativeOrder
end subroutine CheckDerivativeOrder
!
end function BSplineIntegral
! {{{ Detailed Description
!> Compute the integral
!! \f[
!! \int_a^b dr
!! \frac{d^{n_1}B_1(r)}{dr^{n_1}} f(r)
!! \frac{d^{n_2}B_2(r)}{dr^{n_2}},
!! \f]
!! where \f$f(r)\f$ is a *smooth* function in the
!! intersection of the supports of the two B-splines.
!! If the first (last) boundary of the integration
!! interval is not specified, then the value a=-oo
!! (b=+oo) is assumed.
!!
!!
!! Properties of B-spline integrals:
!! ---------------------------------
!! Since the support \f$D_i\f$ of the \f$i\f$-th B-spline is formed by
!! \f$k\f$ consecutive intervals, the integrals between two B-splines and a
!! local operator are zero unless their indices differ less than the order \f$k\f$:
!! \f{equation}
!! \langle B_i|O|B_j\rangle=\int_{D_i \cap D_j} B_i(x) o(x) B_j(x) dx.
!! \f}
!! As a consequence, matrices are sparse and often band-diagonal.
!! On uniform grids, matrices of translationally invariant operators, that
!! is with kernel \f$o(x,y)=o(x-y)\f$, are Toeplitz:
!! \f{eqnarray}
!! \langle B_i|O|B_j\rangle=\langle B_{i+n}|O|B_{j+n}\rangle.
!! \f}
!! If an hermitian operator \f$O\f$ is both local and translationally invariant,
!! like the identity and the kinetic energy, its matrix on a uniform grid
!! is Toeplitz and banded, in other terms it is defined by just \f$k\f$ numbers.
!!
!! With Gauss-type integration technique, the matrix elements of operators
!! with polynomial kernels are exact. The error \f$\epsilon\f$ in the approximation
!! of a \f$\mathcal{C}^k\f$ function \f$f\f$ with B-splines, is bounded by
!! \f[
!! \epsilon\leq \mathrm{const}_k|\mathbf{t}|^k\|D^kf\|,\quad |\mathbf{t}|=
!! \max_i(t_{i+1}-t_i),\quad \|f\|=\max_{x\in[a,b]}|f(x)|
!! \f]
!!
! }}}
DoublePrecision function BSplineDriverIntegral(s,FunPtr,Bs1,Bs2,n1,n2,a,b,parvec) &
result( Integral )
!
!.. Assumes that the input data have been sanitized
!
Class(ClassBSpline), intent(in) :: s
procedure(D2DFun) , pointer :: FunPtr
integer , intent(in) :: Bs1, Bs2
integer , intent(in) :: n1, n2
DoublePrecision , intent(in) :: a, b
DoublePrecision, optional, intent(in) :: parvec(*)
!
integer :: Interval, IntervalMin, IntervalMax
DoublePrecision :: LowerBound, UpperBound
!
DoublePrecision :: PartialIntegral
DoublePrecision :: IntervalWidth
DoublePrecision :: Radius
integer :: iGauss
!
DoublePrecision :: aPlus, bMinus
!
Integral=0.d0
!
aPlus = UpperLimitTo( a )
bMinus = LowerLimitTo( b )
IntervalMin = which_interval( aPlus, s )
IntervalMax = which_interval( bMinus, s )
!
do Interval = IntervalMin, IntervalMax
LowerBound = max( a, s%Grid( Interval ) )
UpperBound = min( b, s%Grid( Interval+1 ) )
!
IntervalWidth = UpperBound - LowerBound
if( IntervalWidth < NOD_THRESHOLD ) cycle
!
PartialIntegral = 0.d0
do iGauss=1,NGAUSS
!
Radius = LowerBound + IntervalWidth * Gauss_Points( iGauss )
PartialIntegral = PartialIntegral + &
FunPtr(Radius, Parvec) * &
s%Eval(Radius,Bs1,n1) * &
s%Eval(Radius,Bs2,n2) * &
Gauss_weight( iGauss )
!
enddo
PartialIntegral = PartialIntegral * IntervalWidth
!
Integral = Integral + PartialIntegral
!
enddo
!
end function BSplineDriverIntegral
Pure DoublePrecision function UpperLimitTo(x) result(xPlus)
DoublePrecision, intent(in) :: x
DoublePrecision :: tin,eps
eps=epsilon(1.d0)
tin=tiny(x)*(1.d0+eps)
xPlus=(x+tin)*(1.d0+eps)
end function UpperLimitTo
Pure DoublePrecision function LowerLimitTo(x) result(xMinus)
DoublePrecision, intent(in) :: x
DoublePrecision :: tin,eps
eps=epsilon(1.d0)
tin=tiny(x)*(1.d0+eps)
xMinus=(x-tin)*(1.d0-eps)
end function LowerLimitTo
end module ModuleBSpline
!> Computes the eigenvalues of a number of states of the quantum
!! harmonic oscillator, and compares them with the analytically
!! known result, <span class="math-container">\$ E_n = n + 1/2 \$</span> (when the parameters are chosen
!! such that hbar and the angular frequency are one.
Program TestModuleBSpline
use, intrinsic :: iso_fortran_env, only : ERROR_UNIT, OUTPUT_UNIT
use ModuleBSpline
implicit none
!.. Bspline parameters and variables
integer , parameter :: BS_NNODS = 501
integer , parameter :: BS_ORDER = 12
real(kind(1d0)), parameter :: BS_GRMIN = -20.d0
real(kind(1d0)), parameter :: BS_GRMAX = 20.d0
real(kind(1d0)), parameter :: BS_INTER = BS_GRMAX - BS_GRMIN
real(kind(1d0)) :: BS_GRID(BS_NNODS)
type(ClassBSpline) :: BSpline
!.. Hamiltonian, overlap, and spectral-decomposition arrays
real(kind(1d0)), allocatable :: Hmat(:,:), Smat(:,:)
integer :: iNode, nEn, info
!.. Initializes the BSpline set
do iNode=1,BS_NNODS
BS_GRID(iNode) = BS_GRMIN + &
BS_INTER * dble(iNode-1) / dble(BS_NNODS-1)
enddo
call BSpline%Init( &
BS_NNODS , &
BS_ORDER , &
BS_GRID , &
info )
if(info/=0) error stop
!.. Due to the continuity requirement on the wavefunction,
! the first and last BSplines, which do not vanish at the
! boundary of the interval, cannot be used
nEn = BSpline%GetNBsplines() - 2
BlockFillMatrices: block
integer :: iBs1, iBs2
real(kind(1d0)) :: Overlap, KineticEnergy, PotentialEnergy
real(kind(1d0)) :: parvec(1)
procedure(D2DFUN), pointer :: fPtrUni, fPtrPow
fPtrUni => Unity
fPtrPow => Power
allocate(Smat(BS_ORDER,nEn))
Smat=0.d0
allocate(Hmat,source=Smat)
parvec(1)=2.d0
do iBs2 = 2, nEn + 1
do iBs1 = max(2, iBs2-BS_ORDER+1), iBs2
Overlap = BSpline%Integral(fPtrUni,iBs1,iBs2)
KineticEnergy = BSpline%Integral(fPtrUni,iBs1,iBs2,1,1) / 2.d0
PotentialEnergy = Bspline%Integral(fPtrPow,iBs1,iBs2,parvec=parvec) / 2.d0
Smat(iBs1+BS_ORDER-iBs2,iBs2-1) = Overlap
Hmat(iBs1+BS_ORDER-iBs2,iBs2-1) = KineticEnergy + PotentialEnergy
enddo
enddo
end block BlockFillMatrices
BlockGeneralizedEigenproblem : Block
real(kind(1d0)), allocatable :: Eval(:), Evec(:,:), Work(:)
real(kind(1d0)), parameter :: ERROR_THRESHOLD = 1.d-10
real(kind(1d0)) :: EigenvalueError
integer :: iEn, info
allocate(work(3*nEn),Eval(nEn),Evec(1,1))
work=0.d0
Eval=0.d0
Evec=0.d0
call DSBGV( 'N', 'U', nEn, BS_ORDER-1, BS_ORDER-1, &
Hmat, BS_ORDER, Smat, BS_ORDER, Eval, Evec, 1, work, info )
if( info /= 0 )then
write(ERROR_UNIT,"(a,i0)") "DSBGV info : ", info
error stop
endif
deallocate(work)
do iEn = 1, nEn
EigenvalueError = Eval(iEn) - (iEn-0.5d0)
if( EigenvalueError > ERROR_THRESHOLD )exit
write(OUTPUT_UNIT,"(i4,x,e24.16)") iEn, EigenvalueError
enddo
write(OUTPUT_UNIT,"(a,i0)") "Number of Accurate Eigenvalues : ",iEn-1
end Block BlockGeneralizedEigenproblem
contains
!.. Lambdas would be so useful ...
Pure real(kind(1d0)) function Unity(x,parvec) result(y)
DoublePrecision, intent(in) :: x
DoublePrecision, optional, intent(in) :: parvec(*)
y=1.d0
end function Unity
Pure real(kind(1d0)) function Power(x,parvec) result(res)
real(kind(1d0)), intent(in) :: x
real(kind(1d0)), optional, intent(in) :: parvec(*)
res = x**parvec(1)
end function Power
end Program TestModuleBSpline
</code></pre>
<p>Those of you whose compiler does not recognize the block statement can use the following version of the main</p>
<pre class="lang-fortran prettyprint-override"><code>!> Computes the eigenvalues of a number of states of the quantum
!! harmonic oscillator, and compares them with the analytically
!! known result, <span class="math-container">\$ E_n = n + 1/2 \$</span> (when the parameters are chosen
!! such that hbar and the angular frequency are one.
program main
use, intrinsic :: iso_fortran_env, only : ERROR_UNIT, OUTPUT_UNIT
use ModuleBSpline
implicit none
!.. Bspline parameters and variables
integer , parameter :: BS_NNODS = 501
integer , parameter :: BS_ORDER = 12
real(kind(1d0)), parameter :: BS_GRMIN = -20.d0
real(kind(1d0)), parameter :: BS_GRMAX = 20.d0
real(kind(1d0)), parameter :: BS_INTER = BS_GRMAX - BS_GRMIN
real(kind(1d0)) :: BS_GRID(BS_NNODS)
type(ClassBSpline) :: BSpline
!.. Hamiltonian, overlap, and spectral-decomposition arrays
real(kind(1d0)), allocatable :: Hmat(:,:), Smat(:,:)
integer :: iNode, nEn, info
!.. Initializes the BSpline set
do iNode=1,BS_NNODS
BS_GRID(iNode) = BS_GRMIN + &
BS_INTER * dble(iNode-1) / dble(BS_NNODS-1)
enddo
call BSpline%Init( &
BS_NNODS , &
BS_ORDER , &
BS_GRID , &
info )
if(info/=0) error stop
!.. Due to the continuity requirement on the wavefunction,
! the first and last BSplines, which do not vanish at the
! boundary of the interval, cannot be used
nEn = BSpline%GetNBsplines() - 2
call FillMatrices()
call GeneralizedEigenproblem()
contains
subroutine FillMatrices()
integer :: iBs1, iBs2
real(kind(1d0)) :: Overlap, KineticEnergy, PotentialEnergy
real(kind(1d0)) :: parvec(1)
procedure(D2DFUN), pointer :: fPtrUni, fPtrPow
fPtrUni => Unity
fPtrPow => Power
allocate(Smat(BS_ORDER,nEn))
Smat=0.d0
allocate(Hmat,source=Smat)
parvec(1)=2.d0
do iBs2 = 2, nEn + 1
do iBs1 = max(2, iBs2-BS_ORDER+1), iBs2
Overlap = BSpline%Integral(fPtrUni,iBs1,iBs2)
KineticEnergy = BSpline%Integral(fPtrUni,iBs1,iBs2,1,1) / 2.d0
PotentialEnergy = Bspline%Integral(fPtrPow,iBs1,iBs2,parvec=parvec) / 2.d0
Smat(iBs1+BS_ORDER-iBs2,iBs2-1) = Overlap
Hmat(iBs1+BS_ORDER-iBs2,iBs2-1) = KineticEnergy + PotentialEnergy
enddo
enddo
end subroutine FillMatrices
subroutine GeneralizedEigenproblem()
real(kind(1d0)), allocatable :: Eval(:), Evec(:,:), Work(:)
real(kind(1d0)), parameter :: ERROR_THRESHOLD = 1.d-10
real(kind(1d0)) :: EigenvalueError
integer :: iEn, info
allocate(work(3*nEn),Eval(nEn),Evec(1,1))
work=0.d0
Eval=0.d0
Evec=0.d0
call DSBGV( 'N', 'U', nEn, BS_ORDER-1, BS_ORDER-1, &
Hmat, BS_ORDER, Smat, BS_ORDER, Eval, Evec, 1, work, info )
if( info /= 0 )then
write(ERROR_UNIT,"(a,i0)") "DSBGV info : ", info
error stop
endif
deallocate(work)
do iEn = 1, nEn
EigenvalueError = Eval(iEn) - (iEn-0.5d0)
if( EigenvalueError > ERROR_THRESHOLD )exit
write(OUTPUT_UNIT,"(i4,x,e24.16)") iEn, EigenvalueError
enddo
write(OUTPUT_UNIT,"(a,i0)") "Number of Accurate Eigenvalues : ",iEn-1
end subroutine GeneralizedEigenproblem
!.. Lambdas would be so useful ...
Pure real(kind(1d0)) function Unity(x,parvec) result(y)
DoublePrecision, intent(in) :: x
DoublePrecision, optional, intent(in) :: parvec(*)
y=1.d0
end function Unity
Pure real(kind(1d0)) function Power(x,parvec) result(res)
real(kind(1d0)), intent(in) :: x
real(kind(1d0)), optional, intent(in) :: parvec(*)
res = x**parvec(1)
end function Power
end program main
</code></pre>
<p>If you have gfortran/gcc compilers, lapack libraries can be downloaded from <a href="http://www.netlib.org/lapack/" rel="nofollow noreferrer">http://www.netlib.org/lapack/</a>
and compiled following the instructions. Finally, the program can be compiled by writing the module in a separate BSpline_m.f90 file, the main in a file BSpline_main.f90, and running the command</p>
<p><code>gfortran BSpline_m.f90 BSpline_main.f90 -L <LAPACK_INSTALL_DIR> -llapack -lrefblas</code></p>
<p>where <code>LAPACK_INSTALL_DIR</code> is wherever you have compiled the LAPACK libraries, which is also where the liblapack.a and librefblas.a static libraries will be automatically placed, after the compilation.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T17:45:48.783",
"Id": "502535",
"Score": "0",
"body": "The lambdas are really a topic for a separate question somewhere else. Maybe StackOverflow, maybe some discussion. Anyway, there are no lambdas in Fortran. The less runtime-definable ones. You would need some specialized library for that."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T01:04:32.323",
"Id": "254772",
"Score": "1",
"Tags": [
"numerical-methods",
"lambda",
"physics",
"fortran"
],
"Title": "A Bspline module for AMO"
}
|
254772
|
<p>My program takes input from the user in two ways:</p>
<ul>
<li>By passing input as an argument whilst calling the command</li>
<li>By taking any number of inputs after calling the command</li>
</ul>
<p>The program is a terminal calculator that recognizes parentheses, operators, and errors as soon as you pass an expression. If you happen to come across an (non-internal) error, it will always return a suitable error message. Optionally, the user may pass a number alongside the expression to round the answer to a certain number of digits.</p>
<p>The program mainly centers around the manipulation of strings. As far as I know, there aren't any bugs or memory leaks. However, I've been coding for a few months, and I am in no way an expert. Because of my limited knowledge of C, I'm afraid the methods used in my program are unnecessarily complex. Constructive criticism of any kind is welcome.</p>
<blockquote>
<p>Note: I used the <code>goto</code> keyword many times, mostly as a way to organize error handling. I know that use of such is frowned upon in most cases, but I thought this would be a good implementation of it.</p>
</blockquote>
<p><strong>main.c</strong></p>
<pre><code>#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "eval.h"
bool CMD_LINE; // Using command-line interface?
void print_help(void);
int main(int argc, char *argv[]) {
char *expr = NULL, *swap = NULL;
size_t bufsize = 999, // Maximum input size
ndec; // Number of decimal places
double result;
CMD_LINE = true;
if (argc == 1) {
CMD_LINE = false;
goto interactive;
}
command_line:
if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) { // Interpret help flag if present
if (argc == 2)
print_help();
else
fail("Incorrect flag usage");
}
if ((expr = simplify(argv[1], 0)) == NULL) {
putchar('\n');
exit(EXIT_FAILURE);
}
if (argc == 3) { // Interpret decimal count if present
if (strspn(argv[2], VAL_CHRS + 10) == strlen(argv[2])) /* Decimal count contains only digits */
ndec = atoi(argv[2]); /* VAL_CHRS[11->20] = '1', ..., '9', '0' */
else
goto invdec_err;
if (ndec > DBL_DIG)
goto invdec_err;
}
#ifdef DEBUG
puts("\n\e[4mresult\e[24m");
#endif
result = stod(expr);
free(expr);
puts(expr = dtos(result, argc == 3 ? ndec : 6)); // 6 = default number of decimals shown
free(expr);
return EXIT_SUCCESS;
interactive:
for (;;) {
printf("> ");
expr = calloc(bufsize + 1, sizeof(char));
getline(&expr, &bufsize, stdin);
if (!strcmp(expr, "\n")) {
free(expr);
break;
}
swap = expr; // Swap causes 'still reachable' error in valgrind
expr = simplify(expr, 0);
free(swap);
if (expr != NULL) {
result = stod(expr);
free(expr);
puts(expr = dtos(result, 6));
free(expr);
}
}
return EXIT_SUCCESS;
invdec_err:
fail("Invalid decimal count");
}
void print_help(void) {
printf("Usage: %s [EXPRESSION] [ROUND]\n", PROG_NAME);
puts("High-accuracy terminal calculator");
puts("Encapsulation within apostrophes (') is recommended");
puts("This software falls under the GNU Public License v3.0\n");
puts("++, -- ++x, --x Increment, decrement");
puts("!, !! !x, y!!x Square root, other root ↑ Higher precedence");
puts("^ x^y Exponent");
puts("*, /, % x*y, x/y, x%y Multiply, divide, remainder ↓ Lower Precedence");
puts("+, - x+y, x-y Add, subtract\n");
puts(" (x + y) Control precedence");
puts(" x(y) Multiply terms\n");
puts("GitHub repository: https://github.com/crypticcu/eval");
puts("Report bugs to: cryptic.cu@protonmail.com");
exit(EXIT_SUCCESS);
}
</code></pre>
<p><strong>eval.c</strong></p>
<pre><code>#include <ctype.h>
#include <float.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "eval.h"
/* NOTES **********************************************************
- Parameters contain a leading underscore
- Variables shared between files are uppercase
- Variables named "nchr" hold index positions
o Cannot be negative, so use size_t
- An "obstruction" is an invalid character found to be in between
operator and operand
- In terms of operation, a "limit" is the furthest right- or
left-hand index position, relative to an operator in which an
operation would take place
- stod() is used as a replacement to atof()
o Recognizes numbers that cannot computed accurately
o Number of accurate digits determined by __DBL_DIG__ (DBL_DIG)
- dtos() is used as a replacement to gcvt()
o Returns dynamically-allocated string
o Does not require buffer
******************************************************************/
void fail(const char *_desc) {
printf("%s\n", _desc);
if (CMD_LINE) // Exit program if using command-line
exit(EXIT_FAILURE);
}
void printu(const char *_s, size_t _hpos) {
for (int nchr = 0; nchr < strlen(_s); nchr++) {
if (nchr == _hpos)
printf("\e[4m"); // Underline
putchar(_s[nchr]);
if (nchr == _hpos)
printf("\e[24m"); // Reset underline
}
}
char *dtos(double _x, size_t _sig) { // Dynamic memory: numstr
size_t nwhole = nplaces(_x);
if (nwhole > DBL_DIG)
return STR_OVER;
if (nwhole + _sig > DBL_DIG)
_sig = DBL_DIG - nwhole;
if (_sig > DBL_DIG) // Decimal place exceeds accurate number allotted by system
_sig = DBL_DIG;
bool is_negative = _x < 0, is_decimal = _sig, only_decimal = _x < 1 && _x > -1, only_whole = isequal(_x, (int) _x);
size_t reqsize = nwhole + _sig + is_negative + is_decimal + only_decimal;
char *numstr = (char *) calloc(reqsize + 1, sizeof(char));
if (numstr == NULL) // Allocation fails
return NULL;
if (is_negative) { // Negative and decimal requirements
numstr[0] = '-';
if (only_decimal) {
numstr[1] = '0';
numstr[2] = '.';
}
} else if (only_decimal) {
numstr[0] = '0';
numstr[1] = '.';
}
for (int nchr = is_negative + only_decimal * 2, place = nplaces(_x) - !(nwhole == FLT_DIG && only_whole); nchr < reqsize; nchr++, place--) { // Skip characters reserved for negative sign and decimal point, if present
numstr[nchr] = getdigit(_x, place) + 48; // '0' = 48
if (place == 0) {
if (only_whole)
break;
else if (nchr + 1 != reqsize)
numstr[++nchr] = '.';
}
}
return numstr;
}
char *popsub(const char *_s, size_t _low, size_t _high) { // Dynamic memory: sub
char *sub; // Substring to be 'popped' from string
if (_low >= strlen(_s) || _high >= strlen(_s) || _low > _high || // Low/high indices exceed range of string || Low index is greater than high || Allocation fails
(sub = (char *) calloc(_high - _low + 2, sizeof(char))) == NULL)
return NULL;
for (size_t nchr_old = _low, nchr_new = 0; nchr_old <= _high; nchr_old++, nchr_new++)
sub[nchr_new] = _s[nchr_old];
return sub;
}
char *pushsub(char *_s, char *_sub, size_t _low, size_t _high) { // Dynamic memory: newstr
char *newstr = (char *) calloc(
strlen(_s) // Original length
- (_high - _low + 1) // Take away number of characters being removed
+ strlen(_sub) // Add size of substring
+ 1 // Add space for null character
, sizeof(char));
int nchr_new;
if (_low >= strlen(_s) || _high >= strlen(_s) || _low > _high || newstr == NULL) // Low/high indices exceed range of string || Low index is greater than high || Allocation fails
return NULL;
for (nchr_new = 0; nchr_new < _low; nchr_new++)
newstr[nchr_new] = _s[nchr_new]; // Add contents of old string up to point of integration
for (int nchr_sub = 0; nchr_sub < strlen(_sub); nchr_sub++, nchr_new++)
newstr[nchr_new] = _sub[nchr_sub]; // Integrate substring
for (int nchr_old = _high + 1; nchr_old < strlen(_s); nchr_old++, nchr_new++)
newstr[nchr_new] = _s[nchr_old]; // Add rest of old string
free(_s);
free(_sub);
return newstr;
}
char *simplify(const char *_expr, size_t _from) { // Dynamic memory: subA, subB, expr
bool read_parenth = false;
char chr, *subA = NULL, *subB = NULL,
*expr = (char *) calloc(strlen(_expr) + 1, sizeof(char)); // Modifiable expression
size_t par_low, par_high;
int invpos;
double result;
if (expr == NULL)
return NULL;
if (!_from) { // Check syntax and parenthesese only once (_from is always 0 on first call)
if ((invpos = chk_syntax(_expr)) != CHK_PASS) // Check for syntax errors
goto syntax_err;
if ((invpos = chk_parenth(_expr)) != CHK_PASS) // Check for parenthetical errors
goto syntax_err;
}
strcpy(expr, _expr); // Copy constant expression to modifiable one
for (int nchr = _from; (chr = expr[nchr]); nchr++) { // Go straight to evaluate() if '-p' is passed
if (chr == ')') {
par_high = nchr;
read_parenth = false;
if ((subA = popsub(expr, par_low, par_high)) == NULL)
goto popsub_err;
expr[par_low] = (toast(expr, par_low)) ? '*' : ' ';
expr[par_high] = (toast(expr, par_high)) ? '*' : ' ';
result = evaluate(subA); // Value passed to result to increase efficiency and improve debugging mode clarity
if (isequal(result, DBL_FAIL)) // evaluate() does not return heap address, so can be called without assignment
goto evaluate_err;
if ((subB = dtos(result, DBL_DIG)) == NULL)
goto dtos_err;
free(subA);
if ((expr = pushsub(expr, subB, par_low + 1, par_high - 1)) == NULL) // Do not overwite space where parentheses used to be
goto pushsub_err;
if (_from)
return expr;
}
else if (chr == '(') {
if (read_parenth) {
subA = expr; // Swap causes 'still reachable' error in valgrind
if ((expr = simplify(expr, nchr)) == NULL)
goto simplify_err;
free(subA);
} else {
read_parenth = true;
par_low = nchr;
}
}
}
subA = expr;
result = evaluate(expr);
if (isequal(result, DBL_FAIL))
goto evaluate_err;
if ((expr = dtos(result, DBL_DIG)) == NULL)
goto dtos_err;
free(subA);
return expr;
syntax_err:
printf("Syntax error: ");
printu(_expr, invpos);
free(expr);
return NULL;
evaluate_err:
free(subA); // Failure message not required; would have already been handled by evaluate()
return NULL;
dtos_err:
free(subA);
fail("Internal error (simplify.dtos)"); // Exits program if using command-line
return NULL;
popsub_err:
free(expr);
fail("Internal error (simplify.dtos)");
return NULL;
pushsub_err:
fail("Internal error (simplify.pushsub)");
return NULL;
simplify_err:
free(subA);
fail("Internal error (simplify.simplify)");
return NULL;
}
bool isequal(double _x, double _y) {
return fabs(_x - _y) < FLT_EPSILON;
}
bool isin(const char _x, const char *_y) {
for (int nchr = 0; nchr < strlen(_y); nchr++)
if (_x == _y[nchr])
return true;
return false;
}
bool isnumer(char _c) {
return (isdigit(_c) || _c == '-' || _c == '.');
}
bool toast(const char *_expr, size_t _parpos) { // To asterisk?
char chr = _expr[_parpos],
next, // Character after parenthesis
last; // Character before parenthesis
next = _parpos < strlen(_expr) - 1 ? _expr[_parpos + 1] : 0;
last = _parpos ? _expr[_parpos - 1] : 0;
return (isdigit(last) && isnumer(next) ||
chr == '(' && last == ')' ||
chr == ')' && next == '(') ? true : false;
}
size_t getdigit(double _x, int _place) {
size_t digit;
_x = fabs(_x);
if (abs(_place) > DBL_DIG || _x > LLONG_MAX) // Place cannot be over/under place limit; Any 'x' over max llong causes overflow on conversion
return 0; // Digits that cannot be printed
for (int nchr = 0; nchr <= abs(_place); _place > 0 ? (_x /= 10) : (_x *= 10), nchr++)
digit = ((long long int) _x - (long long int) (_x / 10) * 10);
return digit;
}
size_t nplaces(double _x) {
_x = fabs(_x); // log of negative is undefined
if (_x == 0) // log of zero is undefined
return 1;
return log(_x)/log(10) + 1;
}
int chk_parenth(const char *_expr) {
char chr;
int nopen = 0, nclosed = 0, nchr;
for (nchr = 0; (chr = _expr[nchr]); nchr++) // Get number of closed parentheses
if (chr == ')')
nclosed++;
for (nchr = 0; (chr = _expr[nchr]); nchr++) {
if (chr == '(')
nopen++;
else if (chr == ')')
nopen--;
if (nopen > nclosed) { // Extra open parenthesis?
while ((chr = _expr[--nchr]) != '('); // Find last instance of open parenthesis
return nchr;
}
if (nopen < 0) // Extra closed?
return nchr;
}
return CHK_PASS;
}
int chk_syntax(const char *_expr) {
char chr,
lead = 0, // Last non-space
trail = 0, // Next non-space
last = 0, // Immediate last
next = 1; // Immediate next
size_t nsingle = 0, // Single operators
ndouble = 0, // Double operators
npoint = 0, // Decimal points
nchr_err; // Index position of syntax error
#ifdef DEBUG
puts("\e[4mchk_syntax\e[24m");
#endif
for (size_t nchr = 0; (chr = _expr[nchr]); nchr++) {
#ifdef DEBUG
printf("single: %ld\tdouble: %ld\tchr: %c\n", nsingle, ndouble, chr);
#endif
if (nchr)
last = _expr[nchr - 1];
if (nchr != strlen(_expr))
next = _expr[nchr + 1];
if (next != 0)
for (int i = nchr + 1; _expr[i]; i++)
if(!isspace(_expr[i])) {
trail = _expr[i];
break;
}
if (isdigit(chr) || chr == '(' || chr == ')') // CHECK OPERATORS
nsingle = 0, ndouble = 0;
else if (isin(chr, DBLS) && (chr == last && isin(last, DBLS) || chr == next && isin(next, DBLS))) {
if (chr != '!' && isdigit(lead) || chr == '!' && trail == '!' && !isdigit(lead) && lead != '.') // Operator is obstruction
return nchr;
if (chr == '!' && lead == '!' && !isdigit(trail) && trail != '.') { // Operator isn't obstruction; find obstruction
for (nchr_err = nchr; (chr = _expr[nchr_err]) != trail; nchr_err++);
return nchr_err;
}
ndouble++;
}
else if (isin(chr, OPERS) && !(isin(chr, UNRY) && isin(lead, BNRY))) // Extra conditionals needed to prevent 'x + !y' from being a syntax error
nsingle++;
if (!isdigit(chr) && chr != '.') // CHECK DECIMAL POINTS
npoint = 0;
else if (chr == '.')
npoint++;
if (nsingle == 2 || ndouble == 3 || npoint == 2 || /* Extra operator or comma || */ // CHECK ERRORS
!isin(chr, VAL_CHRS) && !isspace(chr) || /* Is not a valid character nor a space || */
isdigit(chr) && isdigit(lead) && lead != last) /* Two numbers side-by-side w/o operator */
return nchr;
if (!isspace(chr))
lead = chr;
}
return CHK_PASS;
}
int getlim(char *_expr, size_t _operpos, char _dir) {
bool reading = false, read_digit;
char chr;
int lim = -1, nchr;
if (_dir != 'l' && _dir != 'r') // Left and right directions only
return INT_FAIL;
for (nchr = _dir == 'r' ? _operpos + 1 : _operpos - 1; (chr = _expr[nchr]) && nchr >= 0; _dir == 'r' ? nchr++ : nchr--) {
if (isnumer(chr) && !reading)
reading = true;
else if (!isnumer(chr) && reading) {
lim = _dir == 'r' ? nchr - 1 : nchr + 1;
break;
}
if (isdigit(chr))
read_digit = true;
}
if (!reading || !read_digit) // No value found
return INT_FAIL;
else {
if (nchr == -1) // Reached beginning of expression
lim = 0;
else if (chr == 0) // Reached end of expression
lim = strlen(_expr) - 1;
}
return lim;
}
size_t fobst(const char *_expr, size_t _operpos, size_t _llim, size_t _rlim) {
bool l_obstr = false, r_obstr = false;
char chr, oper = _expr[_operpos];
int nchr = _operpos,
off = 0; // Offset from operator position
if (_llim == INT_FAIL) // Left limit of unary operation is operator position
_llim = 0;
if (_rlim == INT_FAIL)
_rlim = strlen(_expr) - 1;
if (_llim >= strlen(_expr) || _rlim >= strlen(_expr) || _llim > _rlim)
return INT_FAIL;
while (off < (int) strlen(_expr)) {
if (nchr >= _llim && nchr <= _rlim) {
chr = _expr[nchr];
if (isin(chr, OPERS) && chr != oper && chr != '-')
off < 0 ? (l_obstr = true) : (r_obstr = true);
}
off <= 0 ? (off = -(off - 1)) : (off = -off);
nchr = _operpos + off;
}
if (l_obstr && r_obstr)
return LEFT | RIGHT;
else if (l_obstr && !r_obstr)
return LEFT;
else if (!l_obstr && r_obstr)
return RIGHT;
else
return 0;
}
double evaluate(const char *_expr) { // Dynamic memory: result_str, expr
char chr,
*result_str = NULL, // Operation result
*expr = (char *) calloc(strlen(_expr) + 1, sizeof(char)); // Modifiable expression
size_t llim, rlim; // Left- and right-hand limits of operation
int nchr;
double result, // Operation result; Final return value
lval, rval; // Left and right values of operation
#ifdef DEBUG
printf("\n\e[4mevaluate\e[24m\n%s\n", _expr);
#endif
if (expr == NULL)
return DBL_FAIL;
strcpy(expr, _expr); // Copy constant expression to modifiable one
for (nchr = 0; (chr = expr[nchr]); nchr++) {
if (isin(chr, OPERS))
goto evaluate;
}
goto reevaluate; // Skip main loop if no operators are found
evaluate:
for (nchr = 0; (chr = expr[nchr]); nchr++) { // INCREMENT/DECREMENT
if (chr == '+' && expr[nchr + 1] == '+' || chr == '-' && expr[nchr + 1] == '-') {
INIT_VALS(); // Retrieves rval, lval, rlim, and llim
if (fobst(expr, nchr, llim, rlim) & RIGHT) // Operation cannot continue if another operator is in the way
continue;
CHK_VALS(RIGHT); // Checks for overflow, getval() failure, and missing operand(s)
result = chr == '+' ? rval + 1 // '++x' -> '+(x + 1)'
: -rval - 1; // '--x' -> '-(-x + 1)'
llim = nchr; // Left limit of unary operation is operator position
INIT_EXPR(); // Retrieves new expression
#ifdef DEBUG
puts(expr);
#endif
}
}
for (nchr = 0; (chr = expr[nchr]); nchr++) { // SQUARE ROOT/OTHER ROOT
if (chr == '!') {
INIT_VALS();
if (expr[nchr + 1] == '!') {
if (fobst(expr, nchr, llim, rlim) & (LEFT & RIGHT)) // Needs both sides of operator
continue;
CHK_VALS(LEFT|RIGHT);
if (rval < 0 && (int) lval % 2 == 0)
goto evenroot_err;
if (lval == 0)
goto zeroroot_err;
result = rval < 0 ? -pow(-rval, 1 / lval) : pow(rval, 1 / lval); // Negative root workaround
} else {
if (fobst(expr, nchr, llim, rlim) & RIGHT) // Needs only the right side of operator
continue;
CHK_VALS(RIGHT);
if (rval < 0)
goto evenroot_err;
llim = nchr;
result = sqrt(rval);
}
INIT_EXPR();
#ifdef DEBUG
puts(expr);
#endif
}
}
for (nchr = 0; (chr = expr[nchr]); nchr++) { // EXPONENT
if (chr == '^') {
INIT_VALS();
if (fobst(expr, nchr, llim, rlim) & (LEFT & RIGHT))
continue;
CHK_VALS(LEFT|RIGHT);
result = pow(lval, rval);
INIT_EXPR();
#ifdef DEBUG
puts(expr);
#endif
}
}
for (nchr = 0; (chr = expr[nchr]); nchr++) { // MULTIPLICATION/DIVISION/REMAINDER
if (chr == '*' || chr == '/' || chr == '%') {
INIT_VALS();
if (fobst(expr, nchr, llim, rlim) & (LEFT & RIGHT))
continue;
CHK_VALS(LEFT|RIGHT);
if (rval == 0 && chr != '*')
goto divzero_err;
if (chr == '*')
result = lval * rval;
else if (chr == '/')
result = lval / rval;
else if (chr == '%') {
if (isequal(lval, (int) lval) && isequal(rval, (int) rval))
result = (int) lval % (int) rval;
else
goto modulus_err;
}
INIT_EXPR();
#ifdef DEBUG
puts(expr);
#endif
}
}
for (nchr = 0; (chr = expr[nchr]); nchr++) { // ADDITION/SUBTRACTION/UNARY PLUS/UNARY MINUS
if (chr == '+' || chr == '-') {
if (chr == '+' && expr[nchr + 1] == '+' || chr == '-' && expr[nchr + 1] == '-') // Increment/Decrement found
goto evaluate;
INIT_VALS();
if (fobst(expr, nchr, llim, rlim) & RIGHT)
continue;
CHK_VALS(RIGHT);
if (llim == INT_FAIL)
llim = nchr;
result = chr == '+' ? lval + rval : lval - rval;
INIT_EXPR();
#ifdef DEBUG
puts(expr);
#endif
}
}
reevaluate:
while (strcspn(expr, OPERS + 2) != strlen(expr)) {
if ((result_str = dtos(evaluate(expr), DBL_DIG)) == NULL)
goto dtos_err;
if ((result_str = dtos(evaluate(expr), DBL_DIG)) == STR_OVER)
goto overflow_err;
free(expr);
expr = result_str;
}
if (isequal(result = stod(expr), DBL_OVER))
goto overflow_err;
free(expr);
return result;
opermiss_err:
free(expr);
fail("Missing operand"); // Exits program if using command-line
return DBL_FAIL;
evenroot_err:
free(expr);
fail("Even root of negative number");
return DBL_FAIL;
zeroroot_err:
free(expr);
fail("Root cannot be zero");
return DBL_FAIL;
divzero_err:
free(expr);
fail("Divide by zero");
return DBL_FAIL;
modulus_err:
free(expr);
fail("Remainder takes integers only");
return DBL_FAIL;
getval_err:
free(expr);
fail("Internal error (evaluate.getval)");
return DBL_FAIL;
dtos_err:
free(expr);
fail("Internal error (evaluate.dtos)");
return DBL_FAIL;
overflow_err:
free(expr);
fail("Number too large");
return DBL_FAIL;
}
double getval(char *_expr, size_t _operpos, char _dir) { // Dynamic memory: val_str
bool reading = false;
char chr, *val_str = NULL;
size_t val_low, val_high; // Range of indices in which value is located
int nchr;
double num;
if (_dir != 'l' && _dir != 'r') // Left and right directions only
return DBL_FAIL;
for (nchr = _dir == 'r' ? _operpos + 1 : _operpos - 1; (chr = _expr[nchr]) && nchr >= 0; _dir == 'r' ? nchr++ : nchr--) { // Get size of value string
if (isnumer(chr) && !reading) {
reading = true;
_dir == 'r' ? (val_low = nchr) : (val_high = nchr);
} else if (!isnumer(chr) && reading) {
_dir == 'r' ? (val_high = nchr) : (val_low = nchr);
break;
}
}
if (!reading) // No value found
return 0; // Must return 0 in this case to ensure proper evaluate() functionality (used in unary + and -)
else if (nchr == -1) // Reached beginning of expression
val_low = 0;
else if (chr == 0) // Reached end of expression
val_high = strlen(_expr) - 1;
if ((val_str = popsub(_expr, val_low, val_high)) == NULL) {
free(_expr);
return DBL_FAIL;
}
if ((num = stod(val_str)) == DBL_FAIL) {
free(val_str);
return DBL_OVER;
}
free(val_str);
return num; // Convert value string to value
}
double stod(const char *_s) { // Equivalent to atof(), except that it does not print inaccurate numbers
bool read_decim = false, is_negative = false, reading = false;
char chr;
int nchr;
double num = 0, placeval = 0.1;
for (nchr = 0; (chr = _s[nchr]) && nchr <= DBL_DIG + is_negative + read_decim; nchr++) { // DBL_DIG is accurate digit limit
if (chr == '-' && !is_negative && !reading)
is_negative = true;
else if (chr == '.' && !read_decim && !reading)
read_decim = true;
if (!read_decim && isdigit(chr)) {
num *= 10;
num += chr - 48;
} else if (isdigit(chr)) {
reading = true;
num += placeval * (chr - 48); // '0' = 48
placeval /= 10;
}
}
if (nchr > DBL_DIG && !read_decim)
return DBL_OVER;
if (is_negative)
num *= -1;
return num;
}
</code></pre>
<p><strong>eval.h</strong></p>
<pre><code>#include <stdbool.h>
#ifndef PARSE_H
#define PARSE_H
#ifdef __GNU_LIBRARY__
#include <err.h>
#define PROG_NAME\
program_invocation_name[1] == '/' ?\
program_invocation_name + 2 :\
program_invocation_name // Ignore './' if included
extern char *program_invocation_name;
#else
#define PROG_NAME "eval"
#endif /* #ifdef __GNU_LIBRARY__ */
/* Initializes left- and right-hand values in evaluate() */
#define INIT_VALS()\
lval = getval(expr, nchr, 'l');\
rval = getval(expr, nchr, 'r');\
llim = getlim(expr, nchr, 'l');\
rlim = getlim(expr, nchr, 'r')
/* Initializes new expression string in evaluate() */
#define INIT_EXPR()\
if ((result_str = dtos(result, DBL_DIG)) == NULL) {\
free(expr);\
fail("Internal error (evaluate.dtos)");\
}\
if ((expr = pushsub(expr, result_str, llim, rlim)) == NULL) {\
free(result_str);\
fail("Internal error (evaluate.pushsub)");\
}
/* Checks for overflow, getval() failure, and missing operand(s) in evaluate()
* Requires needed values, LEFT or RIGHT */
#define CHK_VALS(reqval)\
if (isequal(rval, DBL_OVER) || isequal(lval, DBL_OVER))\
goto overflow_err;\
if (isequal(rval, DBL_FAIL) || isequal(lval, DBL_FAIL))\
goto getval_err;\
if (reqval & RIGHT && rlim == INT_FAIL)\
goto opermiss_err;\
if (reqval & LEFT && llim == INT_FAIL)\
goto opermiss_err
#define INT_FAIL INT_MAX // Passed by [type]-returning functions on failure
#define DBL_FAIL DBL_MAX
#define DBL_OVER FLT_EPSILON // Passed by [type]-returning functions on overflow
#define STR_OVER "..."
#define CHK_PASS -1 // Used by chk_parenth() and chk_syntax(); Indicates valid syntax
#define RIGHT 1
#define LEFT 2
// #define DEBUG // If defined, prints debug info
extern bool CMD_LINE;
static const char *VAL_CHRS = "+-!^*/%.()\n1234567890'",
*OPERS = "+-!^*/%",
*DBLS = "+-!", // Can be double
*UNRY = "+-!", // Can be unary
*BNRY = "^*/%"; // Can only be binary
/* Prints error message and exits program */
extern void fail(const char *_desc);
/* Prints string with character at given position underlined */
extern void printu(const char *_s, size_t _hpos);
/* Returns string representation of double
* Returns NULL on failure
* Returns OVERFLOW on overflow
* Resulting string must be freed */
extern char *dtos(double _x, size_t _sig);
/* Returns new, allocated substring spanning the given elements
* Returns NULL on failure */
extern char *popsub(const char *_s, size_t _low, size_t _high);
/* Returns new, allocated string where substring replaces given elements in old string
* Frees given string and substring while returning a newly allocated one
* Returns NULL on failure */
extern char *pushsub(char *_s, char *_sub, size_t _low, size_t _high);
/* Evaluates mathemetical expression starting from given index position
* Returns string representation of result depending on index
* Returns NULL on failure */
extern char *simplify(const char *_expr, size_t _from);
/* Returns true if floating-point numbers are equal */
extern bool isequal(double _x, double _y);
/* Returns true if character is in string */
extern bool isin(const char _x, const char *_y);
/* Returns true if character is numerical (digit || '-' || '.') */
extern bool isnumer(char _c);
/* Determines whether a parenthesis indicates multiplication */
extern bool toast(const char *_expr, size_t _parpos);
/* Get digit at given place */
extern size_t getdigit(double _x, int _place);
/* Returns number of whole places */
extern size_t nplaces(double _x);
/* Returns index position of first invalid parenthesis of expression
* Returns CHK_PASS if no invalid parentheses are found */
extern int chk_parenth(const char *_expr);
/* Returns index position of first invalid character of expression
* Returns CHK_PASS if no invalid characters are found */
extern int chk_syntax(const char *_expr);
/* Returns left- or right-hand limit of range of operation at given position in expression
* Returns INT_FAIL if invalid direction or operand is missing */
extern int getlim(char *_expr, size_t _operpos, char _dir);
/* Returns OBS_R or OBS_L depending on type of obstruction(s)
* If none are found, returns 0
* Returns INT_FAIL on failure */
extern size_t fobst(const char *_expr, size_t _operpos, size_t _llim, size_t _rlim);
/* Evaluates mathematical expression from index position 0
* Ignores parentheses and syntax errors
* Returns DBL_FAIL on failure */
extern double evaluate(const char *_expr);
/* Returns left- or right-hand value of the operand at given position in the expression
* Returns DBL_FAIL on failure */
extern double getval(char *_expr, size_t _operpos, char _dir);
/* Returns double representation of string
* Returns DBL_FAIL on overflow */
extern double stod(const char *_s);
#endif /* #ifndef PARSE_H */
</code></pre>
<p>GitHub: <a href="https://github.com/crypticcu/eval" rel="nofollow noreferrer">https://github.com/crypticcu/eval</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T09:23:10.563",
"Id": "502499",
"Score": "0",
"body": "Thanks for this great question - I hope you get some good reviews, and I hope to see more of your contributions here in future!"
}
] |
[
{
"body": "<h1>Naming</h1>\n<p>Please don't use ALL_CAPS identifiers for things that are not preprocessor macros:</p>\n<blockquote>\n<pre><code>extern bool CMD_LINE;\nstatic const char *VAL_CHRS = "+-!^*/%.()\\n1234567890'",\n *OPERS = "+-!^*/%",\n *DBLS = "+-!", // Can be double\n *UNRY = "+-!", // Can be unary\n *BNRY = "^*/%"; // Can only be binary\n</code></pre>\n</blockquote>\n<p>The usual naming convention helps alert us to names that don't obey the C rules of scope, and that expand arguments rather than evaluating them. When we name other things this way, it introduces confusion.</p>\n<pre><code>extern bool command_line_flag;\nstatic const char *const valid_chars = "+-!^*/%.()\\n1234567890'";\nstatic const char *const all_operators = "+-!^*/%";\nstatic const char *const unary_operators = "+-!"; // Can be unary\nstatic const char *const binary_operators = "^*/%"; // Can only be binary\n</code></pre>\n<h1>String conversion</h1>\n<blockquote>\n<pre><code>ndec = atoi(argv[2]);\n</code></pre>\n</blockquote>\n<p>Prefer <code>strtol()</code> or <code>sscanf()</code>, because <code>atoi()</code> has no way of reporting failure, and we need to distinguish that from actual entered zero.</p>\n<h1>Terminal escapes</h1>\n<blockquote>\n<pre><code> puts("\\n\\e[4mresult\\e[24m");\n</code></pre>\n</blockquote>\n<p>Don't assume that your output is going to a terminal, or that a connected terminal understands the control codes you expect. If you really want to do fancy terminal stuff, then (a) make it optional with a command-line flag and (b) use termcap or curses to abstract away the handling of different terminal types.</p>\n<h1>Know your tools</h1>\n<blockquote>\n<pre><code> swap = expr; // Swap causes 'still reachable' error in valgrind\n</code></pre>\n</blockquote>\n<p>I like this - it shows that you've been using Valgrind to exercise your program.</p>\n<p>Even better would be to unit-test as much as possible - occasionally run the tests under Valgrind, too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T18:48:05.803",
"Id": "502539",
"Score": "0",
"body": "Thank you for the review! Every practice you mentioned was helpful and to-the-point. Now I know to improve my program's handling of flags, so that I can implement your escape code suggestion along with some other features I had in mind."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T23:04:22.610",
"Id": "502553",
"Score": "0",
"body": "If you like the review, the Stack Exchange way to show that is to vote the answer (the ▲ at top left of the answer). You can also \"accept\" an answer when you feel your code is completely reviewed - don't do that just yet, because my review is fairly cursory and you may well get a better one if you wait."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T09:51:59.207",
"Id": "254790",
"ParentId": "254777",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T03:32:46.447",
"Id": "254777",
"Score": "2",
"Tags": [
"c",
"parsing",
"calculator"
],
"Title": "Terminal Calculator/Parser Inspired by gcalccmd"
}
|
254777
|
<p>I am trying to implement the data type LExpr as an instance of show.</p>
<pre><code>data LExpr = Var String
| App LExpr LExpr
| Lam String LExpr
</code></pre>
<p>This is my code:</p>
<pre><code> instance Show LExpr where
showsPrec d (Var str) = showString' str
showsPrec d (App e1 e2) = showParen (d>=6) $ showsPrec 6 e1 . showString " " . showsPrec 5 e2
showsPrec d (Lam str e) = showParen (d>=5) $ showString ("\\"++str++" -> ") . showsPrec 5 e
</code></pre>
<p>I am looking for some advice on how to further improve my code.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T09:18:48.280",
"Id": "254788",
"Score": "1",
"Tags": [
"haskell"
],
"Title": "Haskell: Implementing the data type LExpR as an instance of show"
}
|
254788
|
<p>This is not the typical debate in FizzBuzz code about how to handle repeated if statement. I believe that it is a matter of personal preference.</p>
<p>I am here to ask about the choice of repeated mathematical operation.</p>
<p>Usually the solution to a FizzBuzz code is to use the modulus operator on every iteration. However, I'm concerned with its performance impact.</p>
<p>From my knowledge, modulus operator is tightly connected with division operator, and has a considerable performance overhead compared to simple increment and decrement operator.</p>
<p>In addition, I don't believe compiler has the ability to analyse and optimise the use of modulus operator in a loop.</p>
<p>Hence, I give the alternative solution that uses only simple decrement operator. The following code are written in C++.</p>
<p>I seek insight on whether my approach will provide performance benefit, or if it is actually a horrible idea that worsen performance.</p>
<p>And if there are other ways I can optimize a FizzBuzz code even further. (I think in a modified FizzBuzz puzzle with lots of cases to compare against, a lookup table might be preferable)</p>
<hr />
<p>Typical FizzBuzz solution.</p>
<pre><code>for (unsigned int i = 1; i <= 1000000; ++i) {
if (!(i % 15))
std::cout << "FizzBuzz\n";
else if (!(i % 3))
std::cout << "Fizz\n";
else if (!(i % 5))
std::cout << "Buzz\n";
else
std::cout << i << '\n';
}
</code></pre>
<hr />
<p>My optimized code.</p>
<pre><code>static const unsigned int fa {3};
static const unsigned int fb {5};
unsigned int a {fa};
unsigned int b {fb};
for (unsigned int i = 1; i <= 1000000; ++i) {
--a, --b;
if (!a && !b) {
a = fa;
b = fb;
std::cout << "FizzBuzz\n";
} else if (!a) {
a = fa;
std::cout << "Fizz\n";
} else if (!b) {
b = fb;
std::cout << "Buzz\n";
} else {
std::cout << i << '\n';
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T11:35:51.643",
"Id": "502509",
"Score": "3",
"body": "\"I seek insight on whether my approach will provide performance benefit, or if it is actually a horrible idea that worsen performance.\" You have two horses. Race them. Do you know what a profiler is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T11:37:04.310",
"Id": "502510",
"Score": "0",
"body": "@Mast No. What's a profiler?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T11:40:22.093",
"Id": "502511",
"Score": "0",
"body": "Analysis of a program to find time/space complexity, frequency and duration of function calls and execution time. [Wiki](https://en.wikipedia.org/wiki/Profiling_(computer_programming))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T13:16:46.250",
"Id": "502518",
"Score": "1",
"body": "Fully agree with Mast, instead of speculating which is faster, test it! Write both pieces of code run then and measure the time it takes. Optimizing for performance without measuring is like painting your house blind."
}
] |
[
{
"body": "<p>Looks good - you're using only simple integer addition and subtraction.</p>\n<p>Except for the division hidden here:</p>\n<pre><code> std::cout << i << '\\n';\n</code></pre>\n<p>Note that division by a constant isn't necessarily as expensive as you think: it's always possible for an optimising compiler to implement it <a href=\"//en.wikipedia.org/wiki/Division_algorithm#Division_by_a_constant\" rel=\"nofollow noreferrer\">in terms of multiplication and bitwise operations</a>. And a test for being an exact multiple is often simpler (think of the well-known algorithms for testing divisibility by 9 or 11 in decimal).</p>\n<p>If you really want to drive up performance, consider storing the integer value as a string (any kind), and implement the <code>++</code> operation character by character.</p>\n<p>You may also be interested in <a href=\"//codegolf.stackexchange.com/q/215216/39490\">High throughput Fizz Buzz</a> over on the Programming Puzzles site.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T11:01:45.227",
"Id": "502506",
"Score": "0",
"body": "Thanks, the linked thread is crazy, and full of resources to read over."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T04:25:56.867",
"Id": "502562",
"Score": "0",
"body": "Can you please elaborate on how printing 'i' contain a hidden division? or link me to a resource to read in? Thanks in advance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T09:15:13.627",
"Id": "502590",
"Score": "1",
"body": "@a.Li - I'll turn that around into a challenge for you - convert an integer to a decimal string without library functions. Now do it without any `/` or `%`. It's not impossible, but not obvious either."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T10:52:45.987",
"Id": "254793",
"ParentId": "254791",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T10:38:36.713",
"Id": "254791",
"Score": "0",
"Tags": [
"c++",
"performance",
"fizzbuzz"
],
"Title": "FizzBuzz Optimisation | Modulus vs Decrement Operator Performance"
}
|
254791
|
<h2>Problem:</h2>
<p>Given an array <strong>A</strong> of <strong>N</strong> integers, you will be asked <strong>Q</strong> queries. Each query consists of two integers <strong>L</strong> and <strong>R</strong>. For each query, find whether bitwise OR of all the array elements <strong>between</strong> indices <strong>L</strong> and <strong>R</strong> is even or odd.</p>
<h2>My approach:</h2>
<p>Accept the array of <strong>N</strong> integers. For any query (<strong>Q<sub>i</sub></strong>) scan the array of integers between the given limit. If an odd number is found (x%2==1) then raise a flag and terminate scanning. If flag is found raised tell that the result is odd, else say that it's even.</p>
<p>On thinking further, I find myself at the dead end. I can't optimize the code anymore. Only thing I can think of is instead of doing <strong>mod 2</strong> I will check the last digit of each number and see if it is one of [0,2,4,6,8]. Upon trying that, the time limit still expired (in context to competitive programming <sup><a href="https://codeforces.com/group/0U62CQraSv/contest/312295/problem/B" rel="nofollow noreferrer">[1]</a></sup>; Note: the competition has ended a day ago and results declared). Anyways, <strong>my</strong> <strong>question</strong> is to find a better method if it exists or optimize the code below.</p>
<p>I assume that the time complexity is <strong>O(nQ)</strong> where <strong>n</strong> is the number of elements in the given range.</p>
<hr />
<h1>The code O(nq)</h1>
<p>Assume array is 1-indexed.
Input
First line consists of two space-separated integers N and Q.
Next line consists of N space-separated array elements.
Next Q lines consist of two space-separated integers L and R in each line.</p>
<pre><code>#include<stdio.h>
#pragma GCC optimize("O2")
int main()
{
long int c,d,j,N,Q;
int fagvar=0;
scanf("%ld %ld\n",&N,&Q);
int a[N];
int i=0;
while(N--)
{
scanf("%ld",&a[i]);
i++;
}
while(Q--)
{
scanf("%ld %ld",&c,&d);
for(j=c-1;j<d;j++)
{
if (a[j]%2==1)
{
fagvar=1;
break;
}
}
if (fagvar==1)
{
printf("%d\n",0);
fagvar=0;
}
else
{
printf("%d\n",1);
}
}
return 0;
}
</code></pre>
<hr />
<p>After 2 answers and a rethinking of algorithm, the final complexity falls at <strong>O(n+q)</strong>. Note: Since this was a competitive problem and I probably won't revisit the same program I haven't added any extra readability. The reader is free to edit my code as required. For the algorithm, visit Toby Speight's comment section.</p>
<p>Visit <a href="https://tio.run/##hVHLboMwEDzbX7EiagTCVEByqRp6yaE3qpxpD64hxA0vJZRKifh26jVxG1pVRVqzHmbG3kF4uRDDMJOVKN7TbHVsU1nf7h7orDnwvOTwuF5D3bSylKfMtp5CywEKVFYtlFxWtkPPlBR1lQNCgqXsjcVsw/bsta5P2T0liG953vFD5KvtUfBqa1s3RQqqniuLzWM23zgXJk/il0srNR@7Zq/bj50sMjv2PIeSM1DyfW6blY0iXJkrWwTRlvBEvkQ2bueBBlDS6WYLtjKPfOVI1CCEdBFPfLwBIc3edXWDLESjKEDeSCQawcW7w0czezpWVhwz4ziq5Q@1Tie6ko63xMXtXJPd6GbsJlL/X1Wnce8LRVDqkXqT5WbMcpIcjOkJNk8dkxFPhBeoCXiSqrczHQ0/rfyr2ZqDCliZ@ervOn9NYUjBhGTCA3PEL68er98PwxIWdAkBLCCkAQSqQhrC4hM" rel="nofollow noreferrer">here</a> for the code. For an amalgamation of spanning over even numbers and Toby's method, visit <a href="https://codereview.stackexchange.com/questions/254797/determine-whether-bitwise-or-of-sub-array-is-odd#comment502805_254801">here</a>.</p>
|
[] |
[
{
"body": "<h1>Code</h1>\n<blockquote>\n<pre><code>#pragma GCC optimize("O2")\n</code></pre>\n</blockquote>\n<p>Normally we just pass that as a compiler flag, so we don't get "unrecognised pragma" warnings from other compilers.</p>\n<blockquote>\n<pre><code> long int c,d,j,N,Q;\n</code></pre>\n</blockquote>\n<p>These are poor names - they tell us very little about what they are used for.</p>\n<p>The number of array elements and the number of queries can't be negative. I suggest <code>size_t</code> (from <code><stdint.h></code>) would be better than <code>long</code> for these. Also consider what range is required for the other values (the challenge should state these bounds). You might want to use the <code>int_fastX_t</code> and <code>int_leastX_t</code> families to ensure the required range.</p>\n<blockquote>\n<pre><code> scanf("%ld %ld\\n",&N,&Q);\n</code></pre>\n</blockquote>\n<p>Don't throw away the return value from <code>scanf()</code> like that. It's important to know how many conversions were successfully performed before attempting to use the assigned values.</p>\n<h1>Algorithm</h1>\n<p>This is on average, much less computation than the naive brute-force algorithm, since we stop examining the array once we find an odd number.</p>\n<p>Something to consider, especially for programming challenges, is that we often talk of average-case complexity using big-O notation, but it can be more helpful to think like an adversary: "<em>What's the worst-case input this algorithm could be given?</em>". The test cases are likely to include some arrays which are <em>all odd</em> or <em>all even</em> - the former being very expensive for this algorithm.</p>\n<p>If we have many queries, we can spend a little time creating a structure to make each query constant-time. The way I would approach this is probably to have an array of <code>size_t</code> that stores the running count of odd numbers. Then, given a query Q(m,n), look at <code>odd_count[n]</code>; if it's equal to <code>odd_count[m]</code>, we have only even numbers in the range, else we have at least one odd number. Note that we don't need to actually store the input array, as we'll only use the running total. Obviously, adjust <code>m</code> and <code>n</code> before lookup if these are inclusive in the challenge (it's a little unclear in your summary, but I assume more rigorously defined in the original).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T16:33:11.330",
"Id": "502529",
"Score": "1",
"body": "Good point about the `#pragma`. I somehow overlooked that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T17:59:38.163",
"Id": "502536",
"Score": "1",
"body": "Thank you for your answer. The new algorithm as far as I can understand means that I should compute and store remainders(0 or 1) of all the numbers and then take the cummulative. i.e. [0,1,1,0,0,0,0,1,0,1]---->[0,1,2,2,2,2,2,3,3,4] so that I would just need to check if the left input and right input are equal. This means the complexity is--> O(n)+O(q) which is a very big improvement. Aaaah thanks a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T22:40:01.473",
"Id": "502549",
"Score": "0",
"body": "That wasn't quite the solution I had in mind, but is probably better than what I was thinking. It's nice when I give a hint instead of spelling out in detail (because you're here to learn rather than be spoon-fed), and the result is that we both learn! I did mean to say that would be _O(n+q)_, but I'm pleased that you worked it out for yourself. Edward's answer is also good; his suggestion uses less storage, traded for a cost in lookup time (greatly dependent on the odd/even balance of the input)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T22:54:39.860",
"Id": "502550",
"Score": "0",
"body": "I've edited this answer to show the algorithm more like the one in your comment (the original is available in history for anyone interested)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T03:52:13.167",
"Id": "502561",
"Score": "1",
"body": "I realized there were some caveats to the cumulative. Although they can be fixed, but for anyone interested, instead of writing [0,1,2,2,2,2,2,3,3,4] one should write [0,1,2,3,4,4,4,4,5,6,7] now, the edge cases won't fail because the odd numbers are always at a different elevation than the even ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T06:28:51.283",
"Id": "502573",
"Score": "0",
"body": "I modified my code to implement the above idea and the time improvement was 50x ... i.e. 73ms for what would have taken ~4000 ms :) And the memory utilization is low too. Although @Edward 's method would take lower memory the time complexity seems roughly equal. Thanks to both of you! I have edited my answer to add my final code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T08:03:20.263",
"Id": "502587",
"Score": "0",
"body": "(First thing I checked was whether the question wasn't to be *XOR* - which *rank support* solves as easily.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:01:47.783",
"Id": "502650",
"Score": "0",
"body": "running total sounds like a bad idea, as for example a 1 and a -1 could cancel each other out and you'd think there were no odd numbers when there were two."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T19:15:47.400",
"Id": "502661",
"Score": "1",
"body": "@Kelly - there can't be -1, because we're counting numbers modulo two - we're adding either 0 or 1 at each step. I was loose with terminology: I should have said \"running count of odd numbers\"."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T15:51:15.933",
"Id": "254800",
"ParentId": "254797",
"Score": "5"
}
},
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Choose better variable names</h2>\n<p>I understand that <code>N</code> and <code>Q</code> are used within the problem description, but <code>c</code> and <code>d</code> are not and are very short and non-descriptive names.</p>\n<h2>Add comments</h2>\n<p>Comments do not add to compile time and help you (and others!) keep track of what is happening in the code.</p>\n<h2>Add error checking</h2>\n<p>One of the things I dislike about many of the programming contests is that they assume perfect input. In the real world, external data is not always formatted perfectly, so we would expect to do things like compensate for non-digit input or unexpected end of input. The obvious way to do this is to check the return value of <code>scanf</code> to make sure it actually read the values intended.</p>\n<h2>Rethink the algorithm</h2>\n<p>When we <code>or</code> numbers together the result is odd if <em>any</em> of the numbers was odd. Further, we can tell that a number is odd just by looking at the low bit of the number. In this problem, the result of a query can only be <code>1</code> (indicating that the result is even) if all of the values in the span are even. This suggests a much more elegant algorithm. Instead of storing all of the input numbers, just note the beginning and ending of each span of even numbers. Then for the queries, see if the values <code>L</code> and <code>R</code> lie completely within a single span. Here's one way to do that:</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n\nint main()\n{\n // N is number of input numbers\n // Q is number of input queries\n long N, Q;\n if (scanf("%ld %ld\\n", &N, &Q) != 2) {\n return EXIT_FAILURE;\n }\n typedef struct {\n long begin;\n long end;\n } span;\n span even_spans[(N+1)/2];\n long span_count = 0;\n long i;\n bool in_span = false;\n /*\n * Read each number from the input,\n * and only examine the low bit.\n */\n for (i = 0; N--; ++i) {\n long m;\n if (scanf("%ld", &m) != 1) {\n return EXIT_FAILURE;\n }\n if (m & 1) {\n if (in_span) {\n even_spans[span_count++].end = i;\n in_span = false;\n }\n } else { // it's even number\n if (!in_span) {\n even_spans[span_count].begin = i;\n in_span = true;\n }\n }\n }\n if (in_span) {\n even_spans[span_count++].end = i;\n }\n /* \n * Process Q queries each of \n * which is a pair of indices L, R\n */\n while (Q--) {\n long L, R;\n if (scanf("%ld %ld", &L, &R) != 2) {\n return EXIT_FAILURE;\n }\n // compensate for 1-based values\n --L;\n --R;\n for (i = 0; i < span_count && L > even_spans[i].end; ++i) {\n }\n // only even if L and R are in the same even span\n puts(i < span_count && L >= even_spans[i].begin \n && R < even_spans[i].end ? "1" : "0");\n }\n}\n</code></pre>\n<h2>How it works</h2>\n<p>To explain in a bit more detail how this works, first let's consider a short input file.</p>\n<h3>test.in</h3>\n<pre><code>11 5\n1 2 4 6 5 8 10 11 12 14 16\n1 5\n1 4\n2 3\n2 4\n2 5\n</code></pre>\n<p>Here's what the input looks like to this algorithm:</p>\n<p>Input array:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>index</th>\n<th>number</th>\n<th>odd/even</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n<td>odd</td>\n</tr>\n<tr>\n<td>1</td>\n<td>2</td>\n<td><strong>even</strong></td>\n</tr>\n<tr>\n<td>2</td>\n<td>4</td>\n<td><strong>even</strong></td>\n</tr>\n<tr>\n<td>3</td>\n<td>6</td>\n<td><strong>even</strong></td>\n</tr>\n<tr>\n<td>4</td>\n<td>5</td>\n<td>odd</td>\n</tr>\n<tr>\n<td>5</td>\n<td>8</td>\n<td><strong>even</strong></td>\n</tr>\n<tr>\n<td>6</td>\n<td>10</td>\n<td><strong>even</strong></td>\n</tr>\n<tr>\n<td>7</td>\n<td>11</td>\n<td>odd</td>\n</tr>\n<tr>\n<td>8</td>\n<td>12</td>\n<td><strong>even</strong></td>\n</tr>\n<tr>\n<td>9</td>\n<td>14</td>\n<td><strong>even</strong></td>\n</tr>\n<tr>\n<td>10</td>\n<td>16</td>\n<td><strong>even</strong></td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Here is the array of even spans that it creates:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>span number</th>\n<th>begin</th>\n<th>end</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0</td>\n<td>1</td>\n<td>4</td>\n</tr>\n<tr>\n<td>1</td>\n<td>5</td>\n<td>7</td>\n</tr>\n<tr>\n<td>2</td>\n<td>8</td>\n<td>11</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Note that each span begins with the index of the first even number in a span, and ends one index <em>after</em> the final even number in a span.</p>\n<p>Now for each of the query pairs <span class=\"math-container\">\\$L, R\\$</span> mathematically the query is this</p>\n<p><span class=\"math-container\">$$ \\exists s \\in S| ( L >= s_{\\text{begin}}) \\land (R < s_{\\text{end}}) $$</span></p>\n<p>Or in English, "there exists a span <span class=\"math-container\">\\$s\\$</span> in the set of all spans <span class=\"math-container\">\\$S\\$</span> such that <span class=\"math-container\">\\$L\\$</span> is greater than or equal to <span class=\"math-container\">\\$s_{\\text{begin}}\\$</span> and <span class=\"math-container\">\\$R\\$</span> is less than <span class=\"math-container\">\\$s_{\\text{end}}\\$</span>. This code does a simple linear search; for huge data sets a binary search might be used.</p>\n<h2>Epilogue</h2>\n<p>Although the code above works, in that it produces correct answers, it takes much more time than the original version. If we combine @TobySpeight's excellent insight of storing a count of odd numbers instead of the original input array with the observation expressed here that a span will only result in an even number if the <span class=\"math-container\">\\$L,R\\$</span> span lies completely within a span of even numbers, we can generate a much faster program at the expense of using more memory. Here's the code:</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n unsigned long N, Q;\n if (scanf("%lu %lu\\n", &N, &Q) != 2)\n return EXIT_FAILURE;\n unsigned odd[N+1];\n unsigned oddcount = 0;\n unsigned *ptr = odd;\n for (++ptr; N--; ++ptr) {\n long m;\n if (scanf("%ld", &m) != 1)\n return EXIT_FAILURE;\n m &= 1;\n if (m) {\n oddcount += 2;\n } \n *ptr = oddcount | m;\n }\n /* \n * Process Q queries each of \n * which is a pair L, R\n */\n unsigned long L, R;\n while (Q--) {\n if (scanf("%lu %lu", &L, &R) != 2)\n return EXIT_FAILURE;\n puts(odd[L] != odd[R] || odd[L] & 1 ? "0" : "1");\n }\n}\n</code></pre>\n<h2>How it works</h2>\n<p>As suggested by @TobySpeight, the array keeps track of the count of odd numbers. It allocates <span class=\"math-container\">\\$N+1\\$</span> array items in the <code>odd</code> array and starts at <code>odd[1]</code> to eliminate the need for adjusting the 1-based query values. The addition is that within each array item we actually store two things: whether the particular input number was odd or even (bit 0) and the count of odd numbers so far (all the other bits of the <code>unsigned</code> value). Queries are handled by testing three conditions:</p>\n<ol>\n<li><code>odd[L] != odd[R]</code> true if there were any odd numbers between</li>\n<li><code>odd[L] & 1</code> true if the left limit was an odd number</li>\n<li><code>odd[R] & 1</code> true if the right limit was an odd number</li>\n</ol>\n<p>If any of these conditions are true, then the answer is <code>0</code> indicating an odd resulting value, otherwise the answer is <code>1</code> indicating an even resulting value. In reality, only the first two tests are needed, since the third test cannot be true if neither of the first two are.</p>\n<h2>Limitations</h2>\n<p>Although the program reads in <code>unsigned long</code> values for both <span class=\"math-container\">\\$N\\$</span> and <span class=\"math-container\">\\$Q\\$</span>, the count of odd numbers is stored in an <code>unsigned</code> value. Further, we limit the range even more by using one bit of that number to indicate an odd or even value. Although the size of an <code>unsigned</code> is implementation-defined, the language of the standard yields the result that it must be at least 16 bits. Since we use one of those bits, the guaranteed maximum uniquely representable count is <span class=\"math-container\">\\$2^{15} - 1 = 32,767\\$</span>. After that, the value silently rolls over to zero. What that means for this program is that if the program's input ever has a span of odd numbers with a length that is an exact integral multiple of 32,768 (on systems with a 16-bit <code>int</code>) a query that picks a left location in the even span to the left of it, and a right location in the even span to the right of it, the program will falsely claim that the result is even. For systems with a 32-bit <code>int</code>, the value is 2,147,483,648.</p>\n<p>If each input number is randomly selected, the probability that any given number is odd is <span class=\"math-container\">\\$P=\\frac{1}{2} = 0.5\\$</span>. So the probability of randomly selecting 32,768 odd numbers in a row is <span class=\"math-container\">\\$3.052 \\times 10^{-5}\\$</span> or about 0.003%. The probability of selecting 2,147,483,648 odd numbers in a row is <span class=\"math-container\">\\$4.657 \\times 10^{-10}\\$</span> or about 0.000000047%. (For reference, according to <a href=\"https://www.bostonglobe.com/metro/2017/08/24/these-extremely-rare-things-are-more-likely-happen-you-than-winning-powerball-jackpot/pq0VeHn5PpAWkJhRP310nK/story.html\" rel=\"nofollow noreferrer\">this article</a>, this is about ten times <em>less</em> likely than you winning the >US$700M Powerball lottery jackpot. I say "you" because I never buy lottery tickets; a practice which doesn't significantly alter my odds of winning!) However, we have no guarantee that the input values are selected randomly, and if I were running the contest, I would <em>deliberately</em> choose such inputs.</p>\n<p>Interestingly, perhaps, it's on exactly this kind of input, with long spans of either even or odd numbers, that the first version I posted above works very well.</p>\n<p>So the conclusion is that the program above is guaranteed to fail for certain ranges and types of values; whether that's acceptable is up to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T18:07:16.223",
"Id": "502537",
"Score": "0",
"body": "I think I do not understand what you meant by span. Please elaborate on that. Also, there is possibly a minor flagging (0 or 1) error in your code because it failed when I tried it. (sorry, I don't have the test cases, neither they are public). Also, the single bit idea is marvelous and will help if the elements get big hence increasing modulo's complexity!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T19:55:50.143",
"Id": "502542",
"Score": "0",
"body": "I found the flaw. Input `6 7\n1 4 5 7 4 6\n1 1\n2 2\n2 3\n3 4\n4 4\n5 5\n6 6` Copy pasting wont be a problem. You would see that `6 6` is returned false which should have been 1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T19:59:40.543",
"Id": "502543",
"Score": "0",
"body": "apparently if sequence is `1 4 8 10 4 6` the code will work as intended. But if, `1 4 5 10 4 6` it will fail"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T22:29:45.520",
"Id": "502548",
"Score": "0",
"body": "There was a typo in the code. My apologies."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T22:57:34.240",
"Id": "502551",
"Score": "0",
"body": "I'm guessing the challenge includes at least one test-case where all the inputs are odd - that could be pathological for the proposed algorithm (whereas the question code suffers when all inputs are even)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T22:58:35.463",
"Id": "502552",
"Score": "0",
"body": "Could be; the code in my answer should correctly answer in either case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T23:20:05.930",
"Id": "502556",
"Score": "0",
"body": "Correct yes, but perhaps still [tag:time-limit-exceeded]. It also uses twice as much storage as the original - perhaps worth mentioning?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T23:48:18.993",
"Id": "502557",
"Score": "0",
"body": "Why would it exceed time limit? Also while it allocates double the memory in its current version for convenience, it provably needs *at worst* exactly the same amount of memory as the original. One could trivially allocate `N/2` entries if it mattered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T23:54:36.127",
"Id": "502558",
"Score": "0",
"body": "Indeed I've modified the code to do just that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T05:54:38.987",
"Id": "502569",
"Score": "0",
"body": "Still fails for `4 3 4 1 3 2 1 1 1 2 2 3`. It shows 1 for `2 3`. Also, I very well understand the span method now. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T15:14:01.977",
"Id": "502626",
"Score": "0",
"body": "Ah, I forgot to check the condition for `L`. Fixed now, and fixed allocation of buffer to handle degenerative case for a odd number of inputs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T16:16:29.813",
"Id": "502630",
"Score": "0",
"body": ".... Failed a previously failed test again. [this one](https://codereview.stackexchange.com/questions/254797/determine-whether-bitwise-or-of-sub-array-is-odd#comment502542_254801). It's okayy, I think putting the script to extract spans would be enough for a person to incorporate it in their code. Just remove the output section."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:15:41.927",
"Id": "502653",
"Score": "0",
"body": "I cautiously think that I have finally squashed the last bug."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T19:27:11.180",
"Id": "502801",
"Score": "0",
"body": "Yesss, congratulations! :P also, even though it's appreciably elegant, there is apparently 4x more time required in the given type of test cases. I think complexity wise, they both are O(N+Q) but possibly the constants differ. Thanks a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T19:33:21.843",
"Id": "502804",
"Score": "0",
"body": "Yes, I also noted in my testing that it's much slower for certain kinds of data sets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T19:34:01.653",
"Id": "502805",
"Score": "1",
"body": "Also FWIW, we can combine Toby Speight's excellent insight with the notion of spans of even numbers. I wrote [this implementation](https://tio.run/##ZVHdboIwGL3vU5yxjPAjU9CrMbcXMGZwq16QUqQJtI5CdjF9dlZAwW1N2vT8tN/5WuodKW3bRy5o0aQMr6pOuXzO3wjhokaZcGHZ5JtAj0KKI7YzRGEPFU1EZhlPRQo998KYwdSqGdmD3gjFj4KlkGm627r@4T9NZaOLrLH4IzmnutK0dgxCJitYrqvZEFvPC9HvbQy5xmxlOOIpXBertCelhLmGP2GewSrvr@rGmM1dI5i8F4zbKeJgPN@qX/p17lytDj4qSZlSiPDZsIozBZbQHDIbHV851wRXSHBKeIXNDPFVm08v37FDCe0vGKzI8@5z//6Prm19wozvWj81tbK639gc8NBn38UHnM@4cib8G4oH9A5jYeAFhm/Yt/YubbvCkqy0vERAfPh6BiTA8gc) to illustrate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T05:27:07.847",
"Id": "502841",
"Score": "0",
"body": "Yayie! This amalgamation is awesome! Accepted in the same time (I just added a pragma optimise Ofast) although without it, only 15ms were required. I think you should add this implementation to your answer."
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T16:24:16.080",
"Id": "254801",
"ParentId": "254797",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "254800",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T14:25:40.307",
"Id": "254797",
"Score": "1",
"Tags": [
"algorithm",
"c",
"time-limit-exceeded",
"bitwise"
],
"Title": "Determine whether bitwise-OR of sub-array is odd"
}
|
254797
|
<p>To practice with SFINAE, template meta programming, functional programming and monads in C++, I decided to try writing a skinny version of the two functions (monadic binding and return) that make <code>std::optional</code> a monad.</p>
<p>Here's the result:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <optional>
#include <utility>
#include <vector>
template<typename T, typename TD = std::decay_t<T>, typename = void>
struct is_optional : std::false_type {};
template<typename T, typename TD>
struct is_optional<
T,
TD,
std::enable_if_t<std::is_same_v<TD,std::optional<typename TD::value_type>>>
> : std::true_type {};
template<typename T>
inline constexpr bool is_optional_v = is_optional<T>::value;
template<typename T, typename F, typename = void>
struct MBind {
inline constexpr auto operator()(T&&, F&&) const noexcept = delete;
};
template<typename T, typename F>
struct MBind<T, F, std::enable_if_t<
is_optional_v<T> && is_optional_v<decltype(std::declval<F>()(std::declval<T>().value()))>
>> {
template<typename Opt = T, typename Fun = F>
inline constexpr auto operator()(Opt&& opt, Fun&& f) const noexcept {
return opt ? f(*std::forward<T>(opt)) : decltype(f(*std::forward<T>(opt))){};
}
};
inline constexpr auto mbind = [](auto&& t, auto&& f) noexcept {
return MBind<decltype(t), decltype(f)>{}(
std::forward<decltype(t)>(t),std::forward<decltype(f)>(f)
);
};
inline constexpr auto mreturn = [](auto&& x){
return std::make_optional(std::forward<decltype(x)>(x));
};
int main()
{
auto xxx1 = mbind(std::optional<int>{1}, [](auto){ return mreturn(3.3); }); // Ok
//auto xxx2 = mbind(std::optional<int>{1}, [](auto){ return 1; }); // wrong F
//auto xxx3 = mbind(std::vector<int>{1,2}, [](auto){ return mreturn(3); }); // wrong T
}
</code></pre>
<p>A few points on which I'd like to receive some feedback, beside any other comments that the code above needs.</p>
<ul>
<li>I know I've written a meta-function <code>is_optional_v</code> which doesn't really enforce that <code>T</code> satisfies the general concept of a <em>maybe</em>, but requires that it is exactly a <code>std::optional</code>; my target was not to learn writing concepts (yet).</li>
<li>For invalid types I've <code>deleted</code> the <code>operator()</code> that actually does the binding, so I have no place to put any message like <code>"this is not a `std::optional`, man"</code>; the same hold also for the metafunction <code>is_optional_v</code>; actually, probably the latter, not <code>MBind::operator()</code>, should be responsible for issueing a compiler message about the input being not a <code>std::optional</code>, whereas <code>MBind::operator()</code> should probably be responsible for complaining about the monadic function passed in. (Probably I think this is really a matter of personal preference, as I think this is what Louis Dionne says <a href="https://youtu.be/emHnx_ZG0qc?t=1868" rel="nofollow noreferrer">here</a>.)</li>
<li>I have tried to perfect forwarding things whenever it makes sense, but I'm not really sure I've done it the right way.</li>
<li>I have templated <code>MBind</code> and not (just) its <code>operator()</code> to allow me partial specialization so that I could use the SFINAE-<code>std::enable_if</code> idiom.</li>
<li>I have defaulted the template parameters of <code>operator()</code> to those of the class, because (as explained above) I didn't want to make everything that behaves like an optional a monad; I think I would do that via <a href="http://boostorg.github.io/hana/index.html#tutorial-core-tag_dispatching" rel="nofollow noreferrer">tag dispatching</a> when I get more comfortable with this stuff.</li>
<li>Have I exagerated with <code>inline</code> and <code>constexpr</code>? Or, is any of those superfluous or inherently a <em>bad</em> idea?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T06:25:18.390",
"Id": "502571",
"Score": "1",
"body": "[`constexpr` implies `inline`](https://stackoverflow.com/questions/14391272/does-constexpr-imply-inline)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T15:24:19.950",
"Id": "254799",
"Score": "1",
"Tags": [
"c++",
"functional-programming",
"c++17",
"template-meta-programming",
"sfinae"
],
"Title": "Making std::optional a monad via SFINAE"
}
|
254799
|
<p>I am automating the building and unit testing of a <a href="https://github.com/pacmaninbw/VMWithEditor" rel="nofollow noreferrer">personal
project</a> using shell scripts
, CMake and make on the latest version of Fedora Linux. I have also tested building on the latest version of Ubuntu. I had to decrease the minimum CMake version on Ubuntu to make it work. Parts of the unit testing have previously been reviewed on Code Review
<a href="https://codereview.stackexchange.com/questions/248559/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-a">A</a>,
<a href="https://codereview.stackexchange.com/questions/248560/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-b">B</a>,
<a href="https://codereview.stackexchange.com/questions/248561/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-c">C</a>,
<a href="https://codereview.stackexchange.com/questions/248817/common-unit-testing-code-follow-up">C2</a>.</p>
<p>My original development environment was/is Visual Studio 2019 on Windows 10 Pro, however, to make it easier to get reviews and to create a portable system and application I have developed this build system as well.</p>
<p>It is possible that I could have used CMake for the entire build system, but one of the requirements for this system is that each unit test can build as a separate unit test as well as being combined into other unit tests for regression testing purposes. Each unit test needs to stand on its own because I am using the unit tests to debug the core code, as
well as unit test it. Using only CMake created only one object and binary tree and that was not the intention.</p>
<p>The unit tests themselves are not automated yet, that is the next step in the project. There are currently 2 unit tests that have been completed, the lexical analyzer and the parser. All the other unit tests are an empty shell at this point.</p>
<h2>Requirements:</h2>
<ol>
<li>Build on any system that supports the original Borne Shell and CMake.</li>
<li>Build the unit tests as individual unit tests and as a single unit test that runs all the previous unit tests.</li>
<li>Use regression testing in each progressive unit test to make sure the new code doesn’t break the previous functionality.</li>
<li>Build the primary application after all the unit tests have been built.</li>
</ol>
<h2>What I want out of this review:</h2>
<ol>
<li>I have tested the build on Fedora and Ubuntu, I would appreciate if someone test the build on Mac OSX, my Mac died 3 years ago.</li>
<li>It’s been a long time since I’ve written shell scripts (at least 6 years and really much longer than that for complex shell scripts).
<ol>
<li>Do my shell scripts follow best practices?</li>
<li>How can I improve them?</li>
<li>Do you see any portability problems with them?</li>
</ol>
</li>
<li>I’ve never written CMake scripts before, all suggestions will be helpful.</li>
<li>It may be that this last request is off-topic, but how could I build this on Windows 10 using the scripts and CMake? That would make the build system truly portable.</li>
</ol>
<p>You can review only the shell scripts or only the CMake code if you prefer. The shell scripts are first follow by 3 CMakeLists.txt files.</p>
<h2>Build Directory Structure and Build Files</h2>
<pre><code>VMWithEditor
buildAll.sh
buildClean.sh
VMWithEditor/VMWithEditor:
buildDebug.sh
buildRelease.sh
CMakeLists.txt
VMWithEditor/VMWithEditor/UnitTests:
buildAllDebug.sh
buildAllRelease.sh
VMWithEditor/VMWithEditor/UnitTests/CommandLine_UnitTest/CommandLine_UnitTest:
buildDebug.sh
buildRelease.sh
CMakeLists.txt
VMWithEditor/VMWithEditor/UnitTests/Common_UnitTest_Code:
CodeReview.md
unit_test_logging.c
UTL_unit_test_logging.h
VMWithEditor/VMWithEditor/UnitTests/ControlConsole_UnitTest/ControlConsole_UnitTest:
buildDebug.sh
buildRelease.sh
CMakeLists.txt
VMWithEditor/VMWithEditor/UnitTests/Editor_UnitTest/Editor_UnitTest:
buildDebug.sh
buildRelease.sh
CMakeLists.txt
VMWithEditor/VMWithEditor/UnitTests/HRF_UnitTest/HRF_UnitTest:
buildDebug.sh
buildRelease.sh
CMakeLists.txt
VMWithEditor/VMWithEditor/UnitTests/Parser_Unit_Test/Parser_Unit_Test:
buildDebug.sh
buildRelease.sh
CMakeLists.txt
VMWithEditor/VMWithEditor/UnitTests/RunAllUnitTests/RunAllUnitTests:
buildDebug.sh
buildRelease.sh
CMakeLists.txt
VMWithEditor/VMWithEditor/UnitTests/State_Machine_Unit_Test/State_Machine_Unit_Test:
buildDebug.sh
buildRelease.sh
CMakeLists.txt
VMWithEditor/VMWithEditor/UnitTests/VirtualMachine_UnitTest/VirtualMachine_UnitTest:
buildDebug.sh
buildRelease.sh
CMakeLists.txt
</code></pre>
<h1>The Code</h1>
<p>I am presenting the shell scripts first and then the CMakeLists.txt files.</p>
<h2>Top Shell Script Level Code</h2>
<h3>VMWithEditor/buildAll.sh</h3>
<pre><code>#! /usr/bin/sh
#
# Build the input version of the Virtual MAchine and all the unit tests
# Stop on any build errors.
#
if [ -z "$1" ] ; then
echo "Usage: build.sh BUILDTYPE where BUILDTYPE is Debug or Release."
exit 1
elif [ "$1" != 'Debug' ] && [ "$1" != 'Release' ] ; then
printf "\n unknow build type %s \n" "$1"
exit 1
fi
#
# Build the necessary variables
#
BUILDTYPE="$1"
UNITTESTDIRECTORY="./VMWithEditor/UnitTests"
SHELLFILE="buildAll${BUILDTYPE}.sh";
VMSHELLFILE="build${BUILDTYPE}.sh";
FULLSPECSHELLFILE="${UNITTESTDIRECTORY}/${SHELLFILE}";
LOGFILE="build${BUILDTYPE}log.txt"
#
# Execute the build scripts
#
# Build The Unit Tests
#
if [ -d "${UNITTESTDIRECTORY}" ] ; then
if [ -f "${FULLSPECSHELLFILE}" ] ; then
echo "Building $UNITTESTDIRECTORY";
cd "${UNITTESTDIRECTORY}" || exit
./"${SHELLFILE}" > "${LOGFILE}" 2>&1
retVal=$?
if [ $retVal -ne 0 ]; then
echo "Unit Test Build Failed!"
exit $retVal
fi
cd ../ || exit
fi
#
# Build the Virtual Machine with Editor
#
if [ -f "./buildDebug.sh" ] ; then
./"${VMSHELLFILE}" > "${LOGFILE}" 2>&1
retVal=$?
if [ ${retVal} -ne 0 ]; then
echo "Virtual Machine With Editor Build Failed!"
echo "Check logs for details"
exit ${retVal}
else
printf "%s Version Virtual Machine With Editor Build and Unit Test Build Completed!\n" "${BUILDTYPE}"
exit 0
fi
fi
fi
</code></pre>
<h3>VMWithEditor/buildClean.sh</h3>
<pre><code>#! /usr/bin/bash
#
# Build the release version of the Virtual Machine and all the unit tests
# Stop on any build errors.
#
UNITTESTDIRECTORY="./VMWithEditor/UnitTests"
if [ -d "$UNITTESTDIRECTORY" ] ; then
cd "$UNITTESTDIRECTORY" || exit
make clean
retVal=$?
if [ $retVal -ne 0 ]; then
exit $retVal
fi
cd ../ || exit
make clean
fi
</code></pre>
<h2>Middle Layer Shell Scripts</h2>
<p>The 2 following shell scripts are in the UnitTests directory:</p>
<h3>buildAllDebug.sh</h3>
<pre><code>#! /usr/bin/bash
# Build the debug version of all the unit tests
# Stop on any build errors.
for i in *
do
if [ -d $i ] ; then
TESTDIRECTORY="$i/$i"
SHELLFILE="$TESTDIRECTORY/buildDebug.sh";
if [ -f $SHELLFILE ] ; then
echo "Building $TESTDIRECTORY";
cd "$TESTDIRECTORY"
./buildDebug.sh >& buildDebuglog.txt
retVal=$?
if [ $retVal -ne 0 ]; then
exit $retVal
fi
cd ../..
fi
fi
done;
</code></pre>
<h3>buildAllRelease.sh</h3>
<pre><code>#! /usr/bin/bash
# Build the debug version of all the unit tests
# Stop on any build errors.
for i in *
do
if [ -d $i ] ; then
TESTDIRECTORY="$i/$i"
SHELLFILE="$TESTDIRECTORY/buildRelease.sh";
if [ -f $SHELLFILE ] ; then
echo "Building $TESTDIRECTORY";
cd "$TESTDIRECTORY"
./buildRelease.sh >& buildReleaselog.txt
retVal=$?
if [ $retVal -ne 0 ]; then
exit $retVal
fi
cd ../..
fi
fi
done;
</code></pre>
<h2>Lowest Level Shell Scripts</h2>
<p>The following 2 shell scripts are in all the unit test directories where cmake is executed, the first builds a debugable version the second builds an optimized release version.</p>
<h3>buildDebug.sh</h3>
<pre><code>#! /bin/sh
# Creat a Debug build directory and then build the target within the Debug directory
# Stop on any build errors and stop the parent process.
mkdir Debug
cd Debug || exit
cmake -DCMAKE_BUILD_TYPE=Debug ..
retVal=$?
if [ $retVal -ne 0 ]; then
printf "\n\ncmake failed %s!\n\n" "$retVal"
exit $retVal
fi
make VERBOSE=1
retVal=$?
if [ $retVal -ne 0 ]; then
printf "\n\nmake failed! %s\n\n" "$retVal"
exit $retVal
fi
</code></pre>
<h3>buildRelease.sh</h3>
<pre><code>#! /bin/sh
# Creat a Release build directory and then build the target within the Release directory
# Stop on any build errors and stop the parent process.
mkdir Release
cd Release || exit
cmake -DCMAKE_BUILD_TYPE=Release ..
retVal=$?
if [ $retVal -ne 0 ]; then
printf "\n\ncmake failed %s!\n\n" "$retVal"
exit $retVal
fi
make
retVal=$?
if [ $retVal -ne 0 ]; then
printf "\n\nmake failed! %s\n\n" "$retVal"
exit $retVal
fi
</code></pre>
<h1>The CMake Files:</h1>
<p>There are 2.3 unit tests that actually test the existing code and one unit test that includes all the other unit tests which is working to the extent that the two existing unit tests work (testing is successful for all three tests). The first 2 CMake files presented are the lexical analyzer unit test and the parser unit test. The lexical analyzer unit test is fully complete and was used to debug the lexical analyzer. The parser unit test is complete, it executes the lexical analyzer unit tests prior to executing the parser unit tests. The parser unit test was used to debug the parser code in the main project.</p>
<h2>The Lexical Analyzer Unit Test CMakeLists.txt file:</h2>
<pre><code>cmake_minimum_required(VERSION 3.16.1)
set(EXECUTABLE_NAME "Lexical_Analyzer_Unit_Test.exe")
project(${EXECUTABLE_NAME} LANGUAGES C VERSION 1.0)
if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
set(GCC_WARN_COMPILE_FLAGS " -Wall ")
set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_WARN_COMPILE_FLAGS}")
endif()
set(VM_SRC_DIR "../../..")
set(COMMON_TEST_DIR "../../Common_UnitTest_Code")
add_executable(${EXECUTABLE_NAME} internal_character_transition_unit_tests.c internal_sytax_state_tests.c lexical_analyzer_test_data.c lexical_analyzer_unit_test_main.c lexical_analyzer_unit_test_utilities.c ${VM_SRC_DIR}/error_reporting.c ${VM_SRC_DIR}/lexical_analyzer.c ${VM_SRC_DIR}/safe_string_functions.c ${COMMON_TEST_DIR}/unit_test_logging.c)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED True)
configure_file(VMWithEditorConfig.h.in VMWithEditorConfig.h)
target_compile_definitions(${EXECUTABLE_NAME} PUBLIC UNIT_TESTING)
target_compile_definitions(${EXECUTABLE_NAME} PUBLIC LEXICAL_UNIT_TEST_ONLY)
target_include_directories(${EXECUTABLE_NAME} PUBLIC "${PROJECT_BINARY_DIR}")
target_include_directories(${EXECUTABLE_NAME} PRIVATE "${VM_SRC_DIR}")
target_include_directories(${EXECUTABLE_NAME} PRIVATE "${COMMON_TEST_DIR}")
</code></pre>
<h2>The Parser Unit Test CMakeLists.txt file:</h2>
<pre><code>cmake_minimum_required(VERSION 3.16.1)
set(EXECUTABLE_NAME "Parser_Unit_Test.exe")
project(${EXECUTABLE_NAME} LANGUAGES C VERSION 1.0)
if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
set(GCC_WARN_COMPILE_FLAGS " -Wall ")
set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_WARN_COMPILE_FLAGS}")
endif()
set(VM_SRC_DIR "../../..")
set(LEXICAL_TEST_DIR "../../State_Machine_Unit_Test/State_Machine_Unit_Test")
set(COMMON_TEST_DIR "../../Common_UnitTest_Code")
add_executable(${EXECUTABLE_NAME} internal_parser_tests.c parser_unit_test.c parser_unit_test_main.c ${VM_SRC_DIR}/error_reporting.c ${VM_SRC_DIR}/human_readable_program_format.c ${VM_SRC_DIR}/lexical_analyzer.c ${VM_SRC_DIR}/opcode.c ${VM_SRC_DIR}/parser.c ${VM_SRC_DIR}/safe_string_functions.c ${VM_SRC_DIR}/virtual_machine.c ${COMMON_TEST_DIR}/unit_test_logging.c ${LEXICAL_TEST_DIR}/internal_character_transition_unit_tests.c ${LEXICAL_TEST_DIR}/internal_sytax_state_tests.c ${LEXICAL_TEST_DIR}/lexical_analyzer_test_data.c ${LEXICAL_TEST_DIR}/lexical_analyzer_unit_test_main.c ${LEXICAL_TEST_DIR}/lexical_analyzer_unit_test_utilities.c)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED True)
configure_file(VMWithEditorConfig.h.in VMWithEditorConfig.h)
target_compile_definitions(${EXECUTABLE_NAME} PUBLIC UNIT_TESTING)
target_compile_definitions(${EXECUTABLE_NAME} PUBLIC PARSER_UNIT_TEST_ONLY)
target_include_directories(${EXECUTABLE_NAME} PUBLIC "${PROJECT_BINARY_DIR}")
target_include_directories(${EXECUTABLE_NAME} PRIVATE "${VM_SRC_DIR}")
target_include_directories(${EXECUTABLE_NAME} PRIVATE "${COMMON_TEST_DIR}")
target_include_directories(${EXECUTABLE_NAME} PRIVATE "${LEXICAL_TEST_DIR}")
</code></pre>
<h2>The RunAllUnitTests CMakeLists.txt file:</h2>
<p>This file is the most complex of all the CMakeLists.txt files. It includes code from 7 other unit tests.</p>
<pre><code>cmake_minimum_required(VERSION 3.16.1)
set(EXECUTABLE_NAME "Run_All_Unit_Tests.exe")
project(${EXECUTABLE_NAME} LANGUAGES C VERSION 1.0)
if("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
set(GCC_WARN_COMPILE_FLAGS " -Wall ")
set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_WARN_COMPILE_FLAGS}")
endif()
set(VM_SRC_DIR "../../..")
set(COMMON_TEST_DIR "../../Common_UnitTest_Code")
set(LEXICAL_TEST_DIR "../../State_Machine_Unit_Test/State_Machine_Unit_Test")
set(PARSER_TEST_DIR "../../Parser_Unit_Test/Parser_Unit_Test")
set(CMD_LINE_TEST_DIR "../../CommandLine_UnitTest/CommandLine_UnitTest")
set(HRF_TEST_DIR "../../HRF_UnitTest/HRF_UnitTest")
add_executable(${EXECUTABLE_NAME}
run_all_unit_tests_main.c
${HRF_TEST_DIR}/hrf_unit_test_main.c
${HRF_TEST_DIR}/unit_test_human_readable_program_format.c
${LEXICAL_TEST_DIR}/lexical_analyzer_unit_test_main.c
${LEXICAL_TEST_DIR}/internal_character_transition_unit_tests.c
${LEXICAL_TEST_DIR}/internal_sytax_state_tests.c
${LEXICAL_TEST_DIR}/lexical_analyzer_test_data.c
${LEXICAL_TEST_DIR}/lexical_analyzer_unit_test_utilities.c
${VM_SRC_DIR}/error_reporting.c
${VM_SRC_DIR}/safe_string_functions.c
${VM_SRC_DIR}/arg_flags.c
${VM_SRC_DIR}/file_io_vm.c
${VM_SRC_DIR}/opcode.c
${VM_SRC_DIR}/parser.c
${VM_SRC_DIR}/default_program.c
${VM_SRC_DIR}/human_readable_program_format.c
${VM_SRC_DIR}/lexical_analyzer.c
${VM_SRC_DIR}/virtual_machine.c
${PARSER_TEST_DIR}/parser_unit_test_main.c
${PARSER_TEST_DIR}/internal_parser_tests.c
${PARSER_TEST_DIR}/parser_unit_test.c
${CMD_LINE_TEST_DIR}/command_line_unit_test_main.c
${VM_SRC_DIR}/error_reporting.c
${VM_SRC_DIR}/arg_flags.c
${VM_SRC_DIR}/safe_string_functions.c
${COMMON_TEST_DIR}/unit_test_logging.c
)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED True)
configure_file(VMWithEditorConfig.h.in VMWithEditorConfig.h)
target_compile_definitions(${EXECUTABLE_NAME} PUBLIC UNIT_TESTING)
target_compile_definitions(${EXECUTABLE_NAME} PUBLIC ALL_UNIT_TESTING)
target_include_directories(${EXECUTABLE_NAME} PUBLIC "${PROJECT_BINARY_DIR}")
target_include_directories(${EXECUTABLE_NAME} PRIVATE "${VM_SRC_DIR}")
target_include_directories(${EXECUTABLE_NAME} PRIVATE "${COMMON_TEST_DIR}")
target_include_directories(${EXECUTABLE_NAME} PRIVATE "${LEXICAL_TEST_DIR}")
target_include_directories(${EXECUTABLE_NAME} PRIVATE "${CMD_LINE_TEST_DIR}")
target_include_directories(${EXECUTABLE_NAME} PRIVATE "${PARSER_TEST_DIR}")
target_include_directories(${EXECUTABLE_NAME} PRIVATE "${HRF_TEST_DIR}")
</code></pre>
|
[] |
[
{
"body": "<p>Here are some ideas that may help you improve your code.</p>\n<h2>Understand the purpose of CMake</h2>\n<p>Many people misunderstand CMake as a "build system" but it is not. It is a tool for <em>creating</em> a build system. Generally speaking, this means that you describe the desired artifacts (executables to be compiled, tests to be compiled and run, documentation to be constructed, etc.) and then CMake translates that into a build system that will run on the target system. Like <a href=\"https://www.gnu.org/software/automake/manual/html_node/Autotools-Introduction.html\" rel=\"nofollow noreferrer\"><code>autotools</code></a> before it, it attempts to take care of the annoying arbitrary differences among systems, compilers and build environment to do three things:</p>\n<ol>\n<li>reduce your burden in creating and maintaining the build system</li>\n<li>allow the same software to be built/tested/packaged on multiple platforms</li>\n<li>allow for simple expansion, reuse and modification</li>\n</ol>\n<p>When you add dependencies such a <code>bash</code> shell scripts, you impair the ability of CMake to provide these benefits. Through this review, I'll show how we can both restore those benefits <em>and</em> simplify.</p>\n<h2>Avoid hardcoding platform assumptions</h2>\n<p>One of the current <code>CMakeLists.txt</code> files includes these lines:</p>\n<pre><code>set(EXECUTABLE_NAME "Run_All_Unit_Tests.exe")\n\nproject(${EXECUTABLE_NAME} LANGUAGES C VERSION 1.0)\n\nif("${CMAKE_BUILD_TYPE}" STREQUAL "Debug")\n set(GCC_WARN_COMPILE_FLAGS " -Wall ")\n set(CMAKE_C_FLAGS "${CMAKE_CXX_FLAGS} ${GCC_WARN_COMPILE_FLAGS}")\nendif()\n\nset(VM_SRC_DIR "../../..")\n</code></pre>\n<p>Even though that's not very many lines, there are a number of problems with platform assumptions. First, there's the executable name -- most platforms do not use an <code>.exe</code> suffix. CMake is smart enough to know the required suffix for each platform so simply omit it.</p>\n<p>Second, the <code>project</code> command is typically going to only appear exactly once in the top level directory. Your files seem to have them sprinkled in multiple places. This makes the project more fragile and harder to reuse. It also leads an experienced CMake reader to wonder if you intend for these to actually be separate projects, but it doesn't make much sense to have a <code>Parser_Unit_Test</code> without a parser, so they can't really be separate.</p>\n<p>Third, the <code>if</code> clause will fail unless we happen to be using <code>gcc</code> (or something compatible like <code>clang</code>). Better is to either use <a href=\"https://cmake.org/cmake/help/latest/command/add_compile_options.html\" rel=\"nofollow noreferrer\"><code>add_compile_options</code></a> or use <a href=\"https://cmake.org/cmake/help/latest/command/target_compile_options.html#command:target_compile_options\" rel=\"nofollow noreferrer\"><code>target_compile_options</code></a> for settings per target.</p>\n<p>Fourth, setting the <code>VM_SRC_DIR</code> explicitly enforces a very specific directory structure which is not easily altered. In some cases this is unavoidable, but this is not one of those. Instead, because this is within a unit test, a better approach would be to simply pass from a higher level <code>CMakeLists.txt</code> file the path to the thing you're attempting to test.</p>\n<h2>Avoid global directives</h2>\n<p>It's good that you're using <code>target_compile_definitions</code> instead of setting things globally, but you should also reconsider the use of lines like these:</p>\n<pre><code>set(CMAKE_C_STANDARD 99)\nset(CMAKE_C_STANDARD_REQUIRED True)\n</code></pre>\n<p>The problem is that not all compilers, such as Microsoft Visual C++ before VS 16.7 even have a notion of standard compliance, so these won't have any effect on such platforms. Better is to use <a href=\"https://cmake.org/cmake/help/latest/manual/cmake-compile-features.7.html#manual:cmake-compile-features(7)\" rel=\"nofollow noreferrer\"><code>cmake-compile-features</code></a> to ask CMake for just the features you need. That way, you don't lock into <em>only</em> C99 but could allow compilers which also incorporate newer features. This often results in better target code and better diagnostics.</p>\n<h2>Create libraries as intermediate products</h2>\n<p>If there are separable pieces of a project like this which have a <code>parser</code> and and <code>lexer</code> and a <code>vm</code> portion, I would highly recommend compiling those pieces into libraries (either shared or static or both) and then linking with the libraries for both compiling the final project and also for testing. This has the advantage that instead of listing all of the constituent source code files in multiple <code>CMakeLists.txt</code> files up and down the hierarchy, you can generally list source code files only once where they are compiled and have all others refer to the generated library. You will still need the usual interface <code>.h</code> files, but <em>only</em> those because you can set internal-only header files as <code>PRIVATE</code>. See <a href=\"https://cmake.org/cmake/help/latest/command/add_library.html#id2\" rel=\"nofollow noreferrer\"><code>add_library</code></a> for details.</p>\n<h2>Flatten your directory tree</h2>\n<p>The project you've presented has twelve separate directories, each with its own code in it. This is not a sustainable strategy! I typically find it is better to flatten the directory structure (I frequently use just <code>src</code>, <code>test</code> and <code>doc</code> as the only subdirectories) and sort out which files go into which artifact in the <code>CMakeLists.txt</code> files instead of maintaining a complex multi-layered directory tree. If you reduced your structure to just two directories, <code>src</code> and <code>test</code> under a main project directory, you'd reduce your <code>CMakeLists.txt</code> maintenance workload by 75% over the current approach.</p>\n<h2>Use <code>CTest</code> for testing</h2>\n<p>Testing can be much more highly automated and portble by using <code>CTest</code> which is part of the suite of CMake programs. In particular see <a href=\"https://cmake.org/cmake/help/latest/command/enable_testing.html#command:enable_testing\" rel=\"nofollow noreferrer\"><code>enable_testing</code></a> and <a href=\"https://cmake.org/cmake/help/latest/command/add_test.html#command:add_test\" rel=\"nofollow noreferrer\"><code>add_test</code></a> for how to incorporate these into your existing CMake files.</p>\n<h2>Drive everything from a single top-level <code>CMakeLists.txt</code> file</h2>\n<p>It has been mentioned earlier, but the best approach for projects like this which have subcomponents but not independent subprojects is to have everything driven from a top-level <code>CMakeLists.txt</code> file. (Actually, it's even true if you do have subprojects, but the details look a little different.) Doing so means that you could compile everything with a single top level command. You could also build and run all of your tests from there or select subsets of test and control the reporting. Even better, cross-compiling and packaging is trivial. For example, I typically compile, test and package for Windows 10 on a Linux machine. Not a single line of my project changes -- the only difference is the command line arguments used for CMake.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T18:27:09.817",
"Id": "254805",
"ParentId": "254802",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254805",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T16:52:20.210",
"Id": "254802",
"Score": "2",
"Tags": [
"c",
"unit-testing",
"shell",
"sh",
"cmake"
],
"Title": "Portable Build System for Virtual Machine with Editor and Unit Tests"
}
|
254802
|
<p>This is a really simple standard snake game written in React.</p>
<p>I've included my custom React components and hooks. Most of the game logic is hidden behind an API written in plain procedural TypeScript, and the React part of my app is for handling rendering and game logic that involves state.</p>
<p>Snake.tsx</p>
<pre><code>const DELAY = 50;
const initialPosition: Position = [1, 1];
export const Snake = () => {
// Holds the positions and directions of the snake
const { snake, nextSnake } = useSnake(handleGoalUpdate);
// Holds the position of the goal (the fruit)
const [goal, nextGoal] = useState(initialPosition);
const [score, nextScore] = useReducer(incrementScore, 0);
const [running, setRunning] = useState(true);
// Maps a users arrow key press onto an function that changes the snakes direction
const keyToAction = new Map<String, () => void>([
["ArrowUp", () => updateDirection(directions.up)],
["ArrowDown", () => updateDirection(directions.down)],
["ArrowLeft", () => updateDirection(directions.left)],
["ArrowRight", () => updateDirection(directions.right)],
]);
// On component rendering, add event listeners and initialise game loop
useEffect(() => {
window.addEventListener("keydown", handleUserMove);
runGame();
}, []);
// Game loop for animating snake through async delays
async function runGame() {
while (running) {
await wait(DELAY);
nextSnake({ action: Action.Move, direction: null });
if (isDead(snake)) {
setRunning(false);
break;
}
}
}
// Updates score whenever snake eats a piece of fruit
function incrementScore(score: number) {
return score + 1;
}
// Updates direction that snake is moving in
function updateDirection(direction: Direction) {
nextSnake({ action: Action.ChangeDirection, direction: direction });
}
// Return a random valid position to place the fruit
function generateGoal(snakePositions: Position[]) {
const emptyPositions: Position[] = [];
for (let row = 0; row < HEIGHT; row++) {
for (let col = 0; col < WIDTH; col++) {
const currPos: Position = [row, col];
if (!containsPosition(snakePositions, currPos)) {
emptyPositions.push(currPos);
}
}
}
return randomItemFromArray(emptyPositions);
}
// Check if snake has eaten the fruit, if it has then generate a new piece of fruit and expand the snake
function handleGoalUpdate() {
if (containsPosition(snake.positions, goal)) {
nextGoal(generateGoal(snake.positions));
nextSnake({ action: Action.Expand, direction: null });
nextScore();
}
}
// Make a move from whatever key the user pressed
function handleUserMove(event: KeyboardEvent) {
const action = keyToAction.get(event.key);
if (action !== undefined) {
action();
}
}
function getTileType(isSnake: boolean, isGoal: boolean) {
if (isSnake) {
return TileType.Snake;
} else if (isGoal) {
return TileType.Goal;
} else {
return TileType.Empty;
}
}
// Generate a grid to be rendered in the virtual DOM
function generateGrid() {
const grid: TileType[][] = [];
for (let row = 0; row < HEIGHT; row++) {
grid.push([]);
for (let col = 0; col < WIDTH; col++) {
const currPos: Position = [row, col];
const isSnake = containsPosition(snake.positions, currPos);
const isGoal = isSamePosition(goal, currPos);
grid[row][col] = getTileType(isSnake, isGoal);
}
}
return grid;
}
return (
<>
<Menu score={score} running={running} />
<Grid grid={generateGrid()} running={running} />
</>
);
}
</code></pre>
<p>useSnake.tsx</p>
<pre><code>export const enum Action {
Expand,
Move,
ChangeDirection
}
interface Dispatch {
action: Action;
direction: Direction;
}
export const useSnake = (handleGoalUpdate: () => void) => {
// Holds the positions of the snake and the directions it's moving in
const [snake, nextSnake] = useReducer(reducer, initialSnake);
// Whenever dimensions of the snake changes, check if it has hit the goal (ate the fruit)
useEffect(handleGoalUpdate, [snake]);
function reducer(snake: Snake, {action, direction}: Dispatch) {
switch (action) {
case Action.Expand:
return expandSnake(snake);
case Action.ChangeDirection:
return changeDirection(snake, direction);
case Action.Move:
return moveOneStep(snake);
default:
throw `Argument not supported - ${action}`;
}
}
return { snake, nextSnake };
}
</code></pre>
<p>Menu.tsx</p>
<pre><code>interface Props {
score: number;
running: boolean;
}
export const Menu = ({ score, running }: Props) => {
const gameOverVisibility = running ? "hidden" : "visible";
return (
<div id="menu">
<h1 id="title">Snake</h1>
<p>Score: <strong>{score}</strong></p>
<p style={{ visibility: gameOverVisibility, fontSize: "20px" }}><strong>Game Over!</strong></p>
</div>
);
}
</code></pre>
<p>Grid.tsx</p>
<pre><code>interface Props {
grid: TileType[][];
running: boolean;
}
export const Grid = ({ grid, running }: Props) => {
const HEIGHT_PIXELS = window.innerHeight * 0.6;
const WIDTH_PIXELS = HEIGHT_PIXELS * (WIDTH / HEIGHT);
const tileSize = HEIGHT_PIXELS / HEIGHT;
const opacity = running ? 1 : 0.3;
function renderRow(row: TileType[], rowIndex: number) {
return (
<tr key={rowIndex}>
{row.map((tileType, colIndex) =>
<Tile tileType={tileType} size={tileSize} key={colIndex} />
)}
</tr>
)
}
return (
<table id="grid" style={{height: HEIGHT_PIXELS, width: WIDTH_PIXELS, opacity: opacity}}>
<tbody>
{grid.map((row, index) =>
renderRow(row, index)
)}
</tbody>
</table>
);
}
</code></pre>
<p>Tile.tsx</p>
<pre><code>export const enum TileType {
Empty,
Snake,
Goal
}
interface Props {
tileType: TileType;
size: number;
}
const tileTypeToColor = new Map([
[TileType.Goal, "yellow"],
[TileType.Snake, "#00BFFF"],
[TileType.Empty, "#FED8B1"]
]);
export const Tile = ({ tileType, size }: Props) => {
const color = tileTypeToColor.get(tileType);
return (
<td style={{backgroundColor: color, height: size, width: size}}/>
)
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T18:05:43.370",
"Id": "254803",
"Score": "0",
"Tags": [
"react.js",
"typescript",
"snake-game"
],
"Title": "Snake in React TypeScript"
}
|
254803
|
<p>i had made a simple parallel sorting for my personal games. it did well so far, but i would like to get some advises about how to improve it further or perhaps there are an alternative methods for better sorting data.</p>
<pre><code>#include <iostream>
#include <cassert>
#include <iomanip>
#include <functional>
#include <utility>
#include <vector>
#include <thread>
#include <future>
#include <random>
#include <algorithm>
template<typename T, typename C = std::less<T>>
void parallel_sort(T* data, std::size_t len, std::size_t grainsize, const C& comp = C())
{
// Use grainsize instead of thread count so that we don't e.g.
// spawn 4 threads just to sort 8 elements.
if (len < grainsize)
{
std::sort(data, data + len, comp);
}
else
{
auto future = std::async(parallel_sort<T, C>, data, len / 2, grainsize, comp);
// No need to spawn another thread just to block the calling
// thread which would do nothing.
parallel_sort(data + len / 2, len / 2, grainsize, comp);
future.wait();
std::inplace_merge(data, data + len / 2, data + len, comp);
}
}
int main()
{
auto eval = [](auto fun) {
const auto t1 = std::chrono::high_resolution_clock::now();
const auto [name, result] = fun();
result();
const auto t2 = std::chrono::high_resolution_clock::now();
const std::chrono::duration<double, std::milli> ms = t2 - t1;
std::cout << std::fixed << std::setprecision(1) << name << " took " << ms.count() << " ms\n";
};
using ints_t = std::vector<int>;
ints_t ints(200); // *Not* ints{200}!
std::generate(std::begin(ints), std::end(ints), std::rand);
{
ints_t l{ ints };
eval([&l] { return std::pair{ "parallel_sort",
[&l] { return parallel_sort(l.data(), l.size(), l.size() / std::thread::hardware_concurrency()); } }; });
assert(std::is_sorted(std::begin(l), std::end(l)));
}
{
ints_t l{ ints };
eval([&l] { return std::pair{ "std::sort",
[&l] { return std::sort(std::begin(l), std::end(l)); } }; });
assert(std::is_sorted(std::begin(l), std::end(l)));
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T20:48:04.090",
"Id": "254808",
"Score": "0",
"Tags": [
"multithreading",
"sorting",
"c++17"
],
"Title": "Simple Parallel Sorting"
}
|
254808
|
<p>I got this question during an interview. The question itself was very open-ended - it asked me to implement a ticket queue system, where by default it would have 3 different queues to hold tickets that are of severity 1, severity 2, and severity 3 respectively. It should have functionalities like:</p>
<ol>
<li>add a ticket to the corresponding queue</li>
<li>get the ticket from the highest severity (priority) queue</li>
<li>resolve ticket i.e. remove the ticket from the queue</li>
<li>loop over the tickets starting at the highest severity to the lowest severity</li>
<li>check if a ticket is in the queue.</li>
</ol>
<p>Finally, the design should be easily extensible to adapt future changes e.g. adding a new queue.</p>
<p>It doesn't have any predefined data structure for either the queue or the ticket so we have to come up with our own design. Here is how I implemented:</p>
<p>First for the tickets I have a class <code>Ticket</code>:</p>
<pre class="lang-js prettyprint-override"><code>class Ticket {
constructor({ name, desc = '', severity }) {
this.id = Math.floor(Math.random() * 1000)
this.timestamp = Date.now()
this.name = name
this.desc = desc
this.severity = severity
}
}
</code></pre>
<p>And for the ticket queues I have this:</p>
<pre class="lang-js prettyprint-override"><code>
class TicketQueues {
constructor(numOfQueues = 3) {
this.queues = Array.from({ length: numOfQueues }, () => [])
this.hashSet = new Set()
}
addTicket(ticket) {
if(this.hasTicket(ticket)) return false
const severityIndex = ticket.severity - 1
this.queues[severityIndex].push(ticket)
this.hashSet.add(ticket)
return true
}
*getTicketBySeverity() {
for (const queue of this.queues) {
for (const ticket of queue) {
yield ticket
}
}
}
getTicketAtHighestSeverity() {
for (const queue of this.queues) {
for (const ticket of queue) {
return ticket
}
}
}
resolveTicket(ticket) {
if(!this.hasTicket(ticket)) return false
const [severity, index] = this._findTicketIndex(ticket)
this.queues[severity].splice(index, 1)
this.hashSet.delete(ticket)
return true
}
_findTicketIndex(ticket) {
for (let i = 0; i < this.queues.length; i++) {
for (let j = 0; j < this.queues[i].length; j++) {
if (this.queues[i][j] === ticket) {
return [i, j]
}
}
}
return [-1, -1]
}
hasTicket(ticket) {
return this.hashSet.has(ticket)
}
}
</code></pre>
<p>The idea is that I have a two-dimensional array to represent the ticket queue system. The first array inside the two-dimensional array has the highest severity.</p>
<p>i.e. <code>[ [ticket1] , [ticket2], [ticket3]]</code> means we have one ticket for severity 1 and 2 and 3</p>
<p>And I also have a hash set to hold a reference to every ticket so I can achieve constant time look up. For <code>getTicketBySeverity</code> I implemented a generator function and the idea here is to take advantage of the lazy evaluation of generators since the data set might be huge so the user might not want to iterate through the whole list of tickets.</p>
<p>Please feel free to give me any feedback that you think might be helpful. There are a few design decision that I couldn't really think through all of the pros and cons and I would like you to give me some suggestion on the following design choices:</p>
<ol>
<li>As I mentioned I used two-dimensional array to hold the tickets, and it worked out fine. However one alternative I can think of is to use a hash map. so instead of having <code>[ [ticket1] , [ticket2], [ticket3]]</code> we have</li>
</ol>
<pre class="lang-js prettyprint-override"><code>{
sev1: [ticket1],
sev2: [ticket2],
sev3: [ticket3],
...
}
</code></pre>
<p>I couldn't really pinpoint exactly what are some of pros and cons of using either one data structure. One argument I can think of that is against using a hash map is that there might be an issue when looping through all of the tickets in the order of severity since normally hash map doesn't have the notion of order for keys. Another way I can think of is to have separate variable for each queue. so</p>
<pre class="lang-js prettyprint-override"><code>class TicketQueues {
constructor(numOfQueues = 3) {
this.sev1Queue = []
this.sev2Queue = []
this.sev3Queue = []
}
</code></pre>
<p>However it seems cumbersome to me but I still am not super clear what exactly is bad about this design.</p>
<ol start="2">
<li><p>I am using reference equality to find the ticket instead of using an <code>id</code>. Not sure in real world scenario which approach is better. I guess using <code>id</code> is better since it is not always possible to keep the original reference for the object?</p>
</li>
<li><p>To bucket the ticket to the right queue, the current implementation relies on the user to specify the correct severity i.e. <code>1</code>, <code>2</code>, <code>3</code>. If they use some weird to represent the severity then it would break e.g. <code>A</code> <code>B</code> <code>C</code>. I guess this can be partially addressed by using TypesScript with either <code>Enum</code> or <code>Union type</code> so the user will know the severity's type. However another approach I thought of is to expose specific API for each valid severity queue we have for the user to use. For example,</p>
</li>
</ol>
<pre class="lang-js prettyprint-override"><code>class TicketQueues {
constructor(numOfQueues = 3) {
this.queues = Array.from({length: numOfQueues}, () => [])
}
addSev1(ticket) {
this.queues[0].push(ticket)
}
addSev2(ticket) {
this.queues[1].push(ticket)
}
addSev3(ticket) {
this.queues[2].push(ticket)
}
</code></pre>
<p>but again I cannot really pinpoin exactly which approach is better. The second approach feels like it is hard for us to extend the queues if we ever need to add another queue, since we would have to add another method for the new queue.</p>
<ol start="4">
<li><p>the current implementation is inherently susceptible to starvation. e.g. as long as the sev1 queue is not empty, we will always start with tickets in sev1 queue when looping over the system even when there might a sev2 ticket that has been there for a long long time.</p>
</li>
<li><p>Lastly, I wonder if we can use priority queues instead of plain old queues here?</p>
</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T12:58:22.323",
"Id": "502733",
"Score": "0",
"body": "Not sure if I understood task correctly. When talking about the severity levels, do queues have their own severity level or only tickets have their own severity? Since I see that in the Ticket object you have this.severity = severity; which suggest that Ticket has it's own severity. So not sure if in the task you are refering to the severity of the queues or the severity of the tickets. To me it looks like the Ticket object shouldn't know anything about the severity. You also pointed out that adding severity property manually is not bulletproof so clearly it should be a better way"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:38:14.720",
"Id": "502756",
"Score": "0",
"body": "One thing I can say is you need to focus on SOLID principal more"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T17:52:47.990",
"Id": "502781",
"Score": "0",
"body": "@Erasus Hi thanks for the reply. I wasn't sure about that either. The queues definitely need a severity to distinguish them, but as you pointed out maybe tickets should not be concerned with severity? I am not too sure. What are some the pros and cons for having tickets with severity? I know there must be a better way but I couldn't seem to find it."
}
] |
[
{
"body": "<h2>Responses to your questions</h2>\n<ol>\n<li><p>I think for this specific case, a two-dimensional array would is a great data structure to solve the problem of multiple ticket queues. Like you mentioned, giving concrete names to each ticket queue would just add complexity to the code, because you would then have to sort the named queue by priority whenever you want to use them - effectively turning them into the 2d array you currently have.</p>\n</li>\n<li><p>When checking for the existence of a ticket, you are correct in assuming that it would be better to check the id instead of using a reference to the original object. I think your choice of a set was the wrong data structure to hold all of your tickets in. If you instead did a map (either a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map instance</a> or a plain object), then it would be much easier to look up tickets by id.</p>\n</li>\n<li><p>I would just not worry about data validation here for the following reasons:</p>\n<ul>\n<li>Like you mentioned, it's really the job of typescript to do that kind of validation.</li>\n<li>There's a number of bad parameters a user could pass into this class to put it in a bad state. Too much validation bloats code, making it difficult to read, and can do more harm than good.\nValidation is more important when the data you're receiving is foreign to the project you're working in. i.e. validate when coding publicly-exposed library methods, in rest endpoint handlers, reading config files, etc. Don't bother when creating the internals of a project.</li>\n</ul>\n</li>\n<li><p>The fact that this implementation is susceptible to starvation is due to the design requirements, isn't it? There's nothing you can do about it in your implementation.</p>\n</li>\n<li><p>Using a single priority queue instead of a separate queue for each severity would also work. Adding new entries will be a little slower as it would have to sort them into the right spot. Removing entries from the middle is likely quicker because priority queues are often implemented using a heap. The main issue is that there is no native priority queue in javascript, making this solution more difficult.</p>\n</li>\n</ol>\n<p>As an aside: The computer science definition of the word "queue" doesn't allow removing entries from the middle of the queue. That kind of flexibility is supposed to belong to lists or arrays.</p>\n<h2>Code quality notes</h2>\n<p>You did a really good job with your function naming. Overall, the code was easy enough to understand.</p>\n<p>If you really expect a large amount of tickets to be in this system, then you ought to be able to generate more than 1000 unique ids. The current implementation will have a lot of id clashes.</p>\n<p>Instead of looping over an array and yielding each entry, you can <code>yield* entireArray</code>.</p>\n<h2>Simplified example</h2>\n<p>The problem description didn't state how many tickets were expected to be in the queue at a given time, or how often a user would read from it, or add a ticket to it, etc. There's a number of different data structures that can be used to optimize the code - the right one would depend on which aspects need to be fast, and which ones are OK being a little slower.</p>\n<p>The following solution is meant to be a dead simple solution that's easy to understand and modify, but will start to run slow if you put too many tickets into the system. Code like this is ideal when you don't expect many tickets or much usage.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const generateId = () => Math.floor(Math.random() * 1e12)\n\nexport const createTicket = ({ name, description = '', severity }) => Object.freeze({\n id: generateId(),\n timestamp: Date.now(),\n name,\n description,\n severity,\n})\n\nexport function createTicketCollection() {\n const tickets = {}\n const getBySeverity = () => Object.values(tickets).sort(\n (a, b) => (a.severity - b.severity) || (a.timestamp - b.timestamp)\n )\n return Object.freeze({\n add(ticket) { tickets[ticket.id] = ticket },\n getBySeverity,\n getTicketAtHighestSeverity: () => getBySeverity()[0],\n resolve(ticket) { delete tickets[ticket.id] },\n has: id => !!tickets[id],\n })\n}\n</code></pre>\n<p>(classes can of course be used instead of factory functions - I just tend to prefer factory functions)</p>\n<h2>Optimized example</h2>\n<p>On the other end of the spectrum, if you want all of the operations performed against the system to run fast, then a combination of a map (for quick lookup by id), and a doubly-linked list (for quick iteration and removal of entries) will allow all function to run in a constant big-O (even faster than a priority queue). Optimizations like this will naturally cause the code to be less readable and less flexible, which is why it's never good to prematurely optimize. I do not recommend actually using a design like this unless it is really needed, but I'll post it here as a proof-of-concept. (I've done some light testing with it, but there could still be some bugs).</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const generateId = () => Math.floor(Math.random() * 1e12)\n\nfunction createLinkedList() {\n let front, back\n return Object.freeze({\n get front() { return front },\n get back() { return back },\n pushBack(value) {\n const node = { last: back, next: undefined, value }\n if (back) back.next = node\n back = node\n if (!front) front = node\n return node\n },\n removeNode(node) {\n if (node.last) node.last.next = node.next\n if (node.next) node.next.last = node.last\n if (front === node) front = node.next\n if (back === node) back = node.last\n },\n *values() {\n let node = front\n while (node) {\n yield node.value\n node = node.next\n }\n },\n })\n}\n\nconst createTicket = ({ name, description = '', severity }) => Object.freeze({\n id: generateId(),\n timestamp: Date.now(),\n name,\n description,\n severity,\n})\n\nexport function createTicketCollection() {\n const listNodeLookup = {}\n const severityGroups = []\n function* getBySeverity() {\n for (const linkedList of severityGroups.filter(x => x != null)) {\n yield* linkedList.values()\n }\n }\n return Object.freeze({\n add(options) {\n const ticket = createTicket(options)\n severityGroups[ticket.severity] ??= createLinkedList()\n const listNode = severityGroups[ticket.severity].pushBack(ticket)\n listNodeLookup[ticket.id] = listNode\n return ticket\n },\n getBySeverity,\n getTicketAtHighestSeverity: () => getBySeverity().next().value,\n resolve(ticket) {\n const listNode = listNodeLookup[ticket.id]\n delete listNodeLookup[ticket.id]\n severityGroups[ticket.severity].removeNode(listNode)\n },\n has: id => !!listNodeLookup[id],\n })\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Update</h2>\n<p><strong>In response to @Joji's comment about why I prefer factory functions over classes:</strong></p>\n<p>This question actually made me do some deep thinking. In the end, I think it's simply because factory functions tend to work better when programming in a functional style, while classes tend to fit better when programming in an object-oriented style. I usually program in a more functional style, but I'm not hard-core about it.</p>\n<p>Let me expound:</p>\n<p>I consider this solution "object-oriented" because I'm encapsulating private data and only allowing the private data to get touched via the methods I provide. This can be achieved with both factory functions or classes. I used factory functions there as it felt more concise, but if you continued to add more and more methods to it, it might start to feel clunky and hard to work with (i.e. private functions have to be declared at the top, not next to the public method that needs it). Maybe a normal class would have been a better tool to use in this scenario (I do sometimes use the class syntax too, just not as often).</p>\n<p>Now I want to show the same answer but written in a way that's a little more functional.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// ticket.js\n\nconst generateId = () => Math.floor(Math.random() * 1e12)\n\nexport const create = ({ name, description = '', severity }) => Object.freeze({\n id: generateId(),\n timestamp: Date.now(),\n name,\n description,\n severity,\n})\n\n\n// ticketCollection.js\n\nexport const create = ({ ticketsById = {} } = {}) => Object.freeze({ ticketsById })\n\nexport const getBySeverity = ticketCollection => Object.values(ticketCollection.ticketsById).sort(\n (a, b) => (a.severity - b.severity) || (a.timestamp - b.timestamp)\n)\n\nexport const getTicketAtHighestSeverity = ticketCollection => getBySeverity(ticketCollection)[0]\n\nexport const addTicket = (ticketCollection, ticket) => create({\n ticketsById: { ...ticketCollection.ticketsById, [ticket.id]: ticket },\n})\n\nexport const resolve = (ticketCollection, ticket) => {\n const ticketsById = { ...ticketCollection.ticketsById }\n delete ticketsById[ticket.id]\n return create({ ticketsById })\n}\n\nexport const has = (ticketCollection, id) => !!ticketCollection.ticketsById[id]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Note that we've sacrificed our encapsulation, all data is now publicly accessible (a no-no in OOP). But we've gained other benefits in the process:</p>\n<ul>\n<li>We're not mutating data anymore (leading to fewer unexpected side-effects).</li>\n<li>We now have the power to organize the methods into separate modules if desired (they don't all have to be right there)</li>\n<li>My favorite one: We don't have to tie specific methods to specific classes. As a concrete example: I've been porting some user management code to node. The old implementation was written in a very object-oriented way. There was a User class, and a Group class. user's were members of groups, and groups had users in them. So, which class do you think the implementors put the addUserToGroup() function? If it's put in the User class, how would it update the group's member list? If it's put in the group's class, how will it update the user's group list? Their solution was pretty gross: They put it in both. The addUserToGroup() method on both the user and group class would update their own internal data, then they would call each other's methods using a special optional parameter to keep them from calling each other yet again. There are arguably better ways to do that while still following OOP style, but none of them are very elegant. The port I wrote didn't have a User or Group class, there were just functions to get or set user/group data. Because these encapsulation boundaries didn't exist, there only needed to be one addUserToGroup() function.</li>\n</ul>\n<p>If we're programming in this style, it should hopefully be clearer why the factory functions work a little better. The actual instances of the factory are just pure data, usually, there are few to no functions as those are all found outside of the factory. In this case, it's much easier to just have a function that returns an object literal, then to write a class that takes parameters in a constructor and assigns them all to "this".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T19:18:09.130",
"Id": "503614",
"Score": "1",
"body": "Hi thanks for the reply! Can I ask why you prefer a factory function over es6 class? Is this something about functional programming vs. oo? I am genuinely about the differences or pros and cons here! Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T06:48:07.557",
"Id": "503642",
"Score": "0",
"body": "@Joji I responded to this comment in the answer. It's probably not the best place to put it, but I had a number of thoughts that wouldn't fit into a tiny comment :p."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T10:04:26.937",
"Id": "254943",
"ParentId": "254810",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254943",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T23:31:02.230",
"Id": "254810",
"Score": "2",
"Tags": [
"javascript",
"object-oriented",
"interview-questions"
],
"Title": "Implementation of a ticket queue system in JavaScript"
}
|
254810
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/254665/231235">A Sub-string Extractor Implementation with Specific Keywords in Java</a>. As <a href="https://codereview.stackexchange.com/a/254673/231235">AJNeufeld's answer</a> mentioned, the test case <code>getTargetString("Where the start is before here.", "start", "here");</code> will return <code>""</code>. I am going to fix this with the vocabulary word comparison technique in this version.</p>
<p>The basic rules are the same:</p>
<ul>
<li>The leading/trailing spaces in output sub-string is removed.</li>
<li>If the given start keyword is an empty string, it means that the anchor is at the start of the input string. Otherwise, the first occurrence of the given start keyword is an start anchor. If there is no any occurrence of the given start keyword, the output is an empty string.</li>
<li>If the given end keyword is an empty string, it means that the anchor is at the end of the input string. Otherwise, the first occurrence of the given end keyword is an end anchor. If there is no any occurrence of the given end keyword, the output is an empty string.</li>
<li>If the location of start anchor is after than the location of end anchor, or a part of the first occurrence of the given start keyword and a part of the first occurrence of the given end keyword are overlapped, the output is an empty string.</li>
</ul>
<p>The example input and output is listed as below.</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">Input String</th>
<th style="text-align: center;">Start Keyword</th>
<th style="text-align: center;">End Keyword</th>
<th style="text-align: center;">Output</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">"Where the start is before here."</td>
<td style="text-align: center;">"start"</td>
<td style="text-align: center;">"here"</td>
<td style="text-align: center;">"is before"</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">"dependencies"</td>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation"</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">"is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">"dependencies"</td>
<td style="text-align: center;">"is a class-based, object-oriented programming language that is designed to have as few implementation"</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"dependencies"</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">"as possible"</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">""(empty string)</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"dependencies"</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"ABC"</td>
<td style="text-align: center;">""</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">""</td>
<td style="text-align: center;">"XYZ"</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"ABC"</td>
<td style="text-align: center;">"XYZ"</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
<tr>
<td style="text-align: center;">"Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible"</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">"Java"</td>
<td style="text-align: center;">""(empty string)</td>
</tr>
</tbody>
</table>
</div>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation is as below.</p>
<pre><code>private static String getTargetString(String input, String startKeyword, String endKeyword)
{
ArrayList<String> parts = new ArrayList<>(
Arrays.asList(input.split(" ")));
if (!startKeyword.isEmpty() && parts
.stream()
.map(n -> n.replaceAll("[^a-zA-Z]+",""))
.collect(Collectors.toList())
.contains(startKeyword) == false)
return "";
if (!endKeyword.isEmpty() && parts
.stream()
.map(n -> n.replaceAll("[^a-zA-Z]+",""))
.collect(Collectors.toList())
.contains(endKeyword) == false)
return "";
int startIndex = -1;
int endIndex = parts.size();
// searching startIndex
int index = 0;
for(String element : parts) {
if (element.replaceAll("[^a-zA-Z]+","").equals(startKeyword))
{
startIndex = index;
}
index++;
}
// searching endIndex
index = 0;
for(String element : parts) {
if (element.replaceAll("[^a-zA-Z]+","").equals(endKeyword))
{
endIndex = index;
}
index++;
}
// generating output string
String output = "";
index = 0;
for(String element : parts) {
if (index > startIndex && index < endIndex)
{
output += (element + ' ');
}
index++;
}
return output.trim();
}
</code></pre>
<p><strong>Test cases</strong></p>
<pre><code>String testString1 = "Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible";
System.out.println(getTargetString(testString1, "", ""));
System.out.println(getTargetString(testString1, "", "dependencies"));
System.out.println(getTargetString(testString1, "Java", ""));
System.out.println(getTargetString(testString1, "Java", "dependencies"));
System.out.println(getTargetString(testString1, "dependencies", ""));
System.out.println(getTargetString(testString1, "", "Java"));
System.out.println(getTargetString(testString1, "dependencies", "Java"));
System.out.println(getTargetString(testString1, "ABC", ""));
System.out.println(getTargetString(testString1, "", "XYZ"));
System.out.println(getTargetString(testString1, "ABC", "XYZ"));
System.out.println(getTargetString(testString1, "Java", "Java"));
System.out.println(
getTargetString("Where the start is before here.", "start", "here")
);
</code></pre>
<p>The output of the above test cases.</p>
<pre><code>Java is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible
Java is a class-based, object-oriented programming language that is designed to have as few implementation
is a class-based, object-oriented programming language that is designed to have as few implementation dependencies as possible
is a class-based, object-oriented programming language that is designed to have as few implementation
as possible
is before
</code></pre>
<p><a href="http://tpcg.io/o00g2Yl0" rel="nofollow noreferrer">Coding Ground Link</a></p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/254665/231235">A Sub-string Extractor Implementation with Specific Keywords in Java</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>Considering the mentioned holes, especially the case <code>getTargetString("Where the start is before here.", "start", "here");</code>, a possible fix is implemented here.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement or any other potential defect, please let me know.</p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T07:00:33.743",
"Id": "502700",
"Score": "0",
"body": "@TorbenPutkonen For some reason, I want to make the method `getTargetString` be able to return the origin input string by a kind of start / end keyword pattern. A way comes up in my mind is to set \"\"(empty string) as the symbol that representing the anchor is at the start / end of the input string."
}
] |
[
{
"body": "<h2>Edge case 1</h2>\n<pre><code>String result = getTargetString("Java is class-based", "Java", "class-based");\n</code></pre>\n<p>I would expect the result to be "is", but it is empty. This is because <code>replaceAll("[^a-zA-Z]+","")</code> removes the dash in <code>class-based</code> so the keyword doesn't match.</p>\n<p>Same for numbers:</p>\n<pre><code>String result = getTargetString("Java15 is out", "Java15", "out");\n// result is ""\n</code></pre>\n<h2>Edge Case 2</h2>\n<pre><code>String result = getTargetString("hey - I am here", "hey", "here");\n</code></pre>\n<p>Here <code>result</code> is "- I am" instead of "I am". Is it expected? The reason is that <code>replaceAll</code> is not used in the last part of the method.</p>\n<h2>Splitting a string into words</h2>\n<p>In general, splitting a string into words is <a href=\"https://www.baeldung.com/java-word-counting\" rel=\"nofollow noreferrer\">not a simple task</a> because there are many edge cases. To reduce the complexity of your solution is important to define in your context what a "word" is and make some assumptions.</p>\n<h2>Programming to an interface</h2>\n<p>Try to use the most generic type to don't depend on subtypes. This concept is called <a href=\"https://softwareengineering.stackexchange.com/questions/232359/understanding-programming-to-an-interface\">Programming to an interface</a>.</p>\n<pre><code>ArrayList<String> parts = new ArrayList<>(Arrays.asList(input.split(" ")));\n</code></pre>\n<p>Using <code>List</code> it's enough:</p>\n<pre><code>List<String> parts = Arrays.asList(input.split(" "));\n</code></pre>\n<h2>Simplify</h2>\n<p>Instead of calling <code>replaceAll</code> four times, consider to parse the input at the beginning and reuse it across the method. It improves performance and readability.</p>\n<pre><code>List<String> parsedInput = parts.stream()\n .map(n -> n.replaceAll("[^a-zA-Z]+", ""))\n .collect(Collectors.toList());\n\nif (!startKeyword.isEmpty() && !parsedInput.contains(startKeyword))\n return "";\n//...\n</code></pre>\n<h2>Simplify 2</h2>\n<p>If the input is parsed at the beginning, then this part:</p>\n<pre><code>int startIndex = -1;\nint endIndex = parts.size();\n\n// searching startIndex\nint index = 0;\nfor(String element : parts) {\n if (element.replaceAll("[^a-zA-Z]+","").equals(startKeyword))\n {\n startIndex = index;\n }\n index++;\n}\n\n// searching endIndex\nindex = 0;\nfor(String element : parts) {\n if (element.replaceAll("[^a-zA-Z]+","").equals(endKeyword))\n {\n endIndex = index;\n }\n index++;\n}\n</code></pre>\n<p>can become:</p>\n<pre><code>int startIndex = parsedInput.lastIndexOf(startKeyword);\nint endIndex = endKeyword.isEmpty() ? parts.size() : parsedInput.lastIndexOf(endKeyword);\n</code></pre>\n<h2>Generating the output</h2>\n<pre><code>String output = "";\nindex = 0;\nfor(String element : parts) {\n if (index > startIndex && index < endIndex)\n {\n output += (element + ' ');\n }\n index++;\n}\nreturn output.trim();\n</code></pre>\n<p>Two suggestions about this part:</p>\n<ol>\n<li>Use <code>StringBuilder</code> to generate <code>output</code> more efficiently</li>\n<li>A regular for-loop seems to be a better fit since the start and end indices are known.</li>\n</ol>\n<pre><code>StringBuilder output = new StringBuilder();\nfor (int index = startIndex + 1; index < endIndex; index++) {\n output.append(parts.get(index)).append(' ');\n}\nreturn output.toString().trim();\n</code></pre>\n<h2>Input validation</h2>\n<p>If <code>input</code> is null, the method throws <code>NullPointerException</code>. Would be better to throw an <code>IllegalArgumentException</code> with a friendlier message:</p>\n<pre><code>if (input == null) {\n throw new IllegalArgumentException("input cannot be null.");\n}\n</code></pre>\n<p><code>startKeyword</code> and <code>endKeyword</code> also need to be validated when <code>null</code>.</p>\n<h2>Testing</h2>\n<p>Testing with <code>System.out.println</code> should be very limited if not avoided completely. The reason is that testing using the console is slow and error-prone. The code is tested visually by us every time, and with many tests it becomes unfeasible.</p>\n<p>A good practice is to create unit tests. In Java, you can use <a href=\"https://junit.org/junit5/\" rel=\"nofollow noreferrer\">JUnit</a>. For example:</p>\n<pre><code>public class StringUtilTest {\n\n @Test\n public void baseTest() {\n String actual = getTargetString("JUnit for testing", "JUnit", "testing");\n\n assertEquals("for", actual);\n }\n\n @Test\n public void ifStartKeywordNotContainedThenEmptyString(){\n String actual = getTargetString("One example", "X", "Y");\n\n assertEquals("", actual);\n }\n\n //... More tests\n}\n\n</code></pre>\n<h2>Alternative</h2>\n<p>Regex is very powerful, the whole method could be:</p>\n<pre><code>public static String getTargetString(String input, String startKeyword, String endKeyword){\n Pattern pattern = Pattern.compile("(?<="+startKeyword+")(.*)(?="+endKeyword+")");\n Matcher matcher = pattern.matcher(input);\n return matcher.find() ? matcher.group(1).trim() : "";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T23:03:08.730",
"Id": "502679",
"Score": "1",
"body": "You really should [`Pattern.quote`](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/regex/Pattern.html#quote(java.lang.String)) the `startKeyword` and `endKeyword` to avoid pattern syntax errors. Also, you'd want to add `\\\\b`'s to the regex to avoid `\"here\"` matching `\"Where\"`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T06:14:11.390",
"Id": "254826",
"ParentId": "254811",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254826",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T23:58:15.143",
"Id": "254811",
"Score": "3",
"Tags": [
"java",
"strings"
],
"Title": "A Sub-string Extractor Implementation with Given Vocabulary Words in Java"
}
|
254811
|
<p>I just started to learn pointers, so I'm interested if I used them correctly in this task where I check if the absolute value of the greatest element in an array is two times greater than the absolute value of the smallest one.</p>
<p>My code works properly; I'm just interested if I used the pointer correctly (it should only be used for an array).</p>
<pre><code> #include <stdio.h>
#include<math.h>
int minmax2x(float* array, int size){
double min=array[0],max=array[0];
int i;
for(i=0;i<size;i++){
if(array[i]<0)
array[i]=array[i]*(-1);
}
for(i=0;i<size;i++){
if(array[i]>max)
max=array[i];
if(array[i]<min)
min=array[i];
}
if(max>2*min)
return 1;
else return 0;
}
int main() {
float array1[5] = { 5.5, 6.6, -7.7, -6.6, -5.5};
float array2[5] = { 3.3, 2.2, 1.1, 2.2, 3.3};
int res1 = minmax2x(array1, 5);
int res2 = minmax2x(array2, 5);
printf("%d %d", res1, res2);
}
</code></pre>
<br>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:27:58.293",
"Id": "502601",
"Score": "0",
"body": "Welcome to Code Review! Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
}
] |
[
{
"body": "<p>Your pointer usage is fine, but there are some other oddities in the code. Floats get assigned to doubles for no discernable reason. There exists an entire loop to make an array positive, which can be accomplished using <code>abs()</code>. There exist multiple return statements which can be reduced to a single expression.</p>\n<p>A more notable issue is tht the absolute conversion occurs AFTER the default values for min and max have been set. This means that a negative value at the start of an array can leak into <code>min</code> and affect results. For example, consider the array <code>(-2,1)</code>. Clearly, the absolute maximum is not greater than 2 times the absolute minimum. Yet, your code returns 1 for this case. This critique is working off the assumption that the code's intended purpose is to determine <code>max(abs(x)) > 2*min(abs(x))</code></p>\n<p>Here is how I would write this code:</p>\n<pre><code>int minmax2x(float* array, size_t size){\n float min = abs(array[0]);\n float max = abs(array[0]);\n \n for(size_t i=1; i<size; ++i){\n float val = abs(array[i]);\n if(val>max) max=val;\n if(val<min) min=val;\n }\n return max > 2*min;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:32:14.877",
"Id": "502602",
"Score": "1",
"body": "I always forget we have the type-generic `abs()` since C99. I grew up with `fabs()`, `fabsf()` and `fabsl()` and still turn to those, so thanks for the reminder!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T03:47:55.047",
"Id": "254820",
"ParentId": "254813",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254820",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T00:43:57.970",
"Id": "254813",
"Score": "1",
"Tags": [
"c",
"pointers"
],
"Title": "Pointers and arrays"
}
|
254813
|
<p>I have the following code for determining TP, TN, FP and FN values for binary classification given two sparse vectors as input (using the <code>sparse</code> library):</p>
<pre><code>def confused(sys1, ann1):
# True Positive (TP): we predict a label of 1 (positive), and the true label is 1.
TP = np.sum(np.logical_and(ann1 == 1, sys1 == 1))
# True Negative (TN): we predict a label of 0 (negative), and the true label is 0.
TN = np.sum(np.logical_and(ann1 == 0, sys1 == 0))
# False Positive (FP): we predict a label of 1 (positive), but the true label is 0.
FP = np.sum(np.logical_and(ann1 == 0, sys1 == 1))
# False Negative (FN): we predict a label of 0 (negative), but the true label is 1.
FN = np.sum(np.logical_and(ann1 == 1, sys1 == 0))
return TP, TN, FP, FN
</code></pre>
<p>I'm trying to find a way to optimize this for speed. This is based on <a href="https://kawahara.ca/how-to-compute-truefalse-positives-and-truefalse-negatives-in-python-for-binary-classification-problems/" rel="nofollow noreferrer">how-to-compute-truefalse-positives-and-truefalse-negatives-in-python-for-binary-classification-problems</a> where my addition was to add the sparse arrays to optimize for memory usage, since the input vectors for the current problem I am trying to solve have over 7.9 M elements, and the positive cases (i.e., 1), are few and far between wrt the negative cases (i.e., 0).</p>
<p>I've done profiling of my code and about half the time is spent in this method.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T09:46:12.600",
"Id": "502712",
"Score": "2",
"body": "If you compute the first 3 metrics, then the last can be a simple subtraction"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:04:18.967",
"Id": "502761",
"Score": "0",
"body": "Nice! That shaved ~20 seconds off the processing time with no hit on memory."
}
] |
[
{
"body": "<p>Well, an obvious improvement is not redoing work. You are currently doing twice as much work as needed because you don't save the results of the comparisons:</p>\n<pre><code>def confused(sys1, ann1):\n predicted_true, predicted_false = sys1 == 1, sys1 == 0\n true_true, true_false = ann1 == 1, ann1 == 0\n\n # True Positive (TP): we predict a label of 1 (positive), and the true label is 1.\n TP = np.sum(np.logical_and(true_true, predicted_true))\n\n # True Negative (TN): we predict a label of 0 (negative), and the true label is 0.\n TN = np.sum(np.logical_and(true_false, predicted_false))\n\n # False Positive (FP): we predict a label of 1 (positive), but the true label is 0.\n FP = np.sum(np.logical_and(true_false, predicted_true))\n\n # False Negative (FN): we predict a label of 0 (negative), but the true label is 1.\n FN = np.sum(np.logical_and(true_true, predicted_false))\nreturn TP, TN, FP, FN\n</code></pre>\n<p>This should speed up the calculation, at the cost of keeping things in memory slightly longer. Make sure you have enough memory available.</p>\n<p>I'm not sure I got your true and predicted labels right, which goes to show that <code>ann1</code> and <code>sys1</code> are really bad names. Something like <code>true</code> and <code>predicted</code> would be vastly more readable. And while you're at it, write out the other variables as well. Characters don't cost extra.</p>\n<p><code>np.logical_and</code> works perfectly fine with integers (at least on normal <code>numpy</code> vectors, you should check that this is also the case for sparse vectors), so as long as your vectors can only contain <code>0</code> or <code>1</code>, you can directly use the input vectors and save on half the memory:</p>\n<pre><code>not_true = np.logical_not(true)\nnot_predicted = np.logical_not(predicted)\ntrue_positive = np.sum(np.logical_and(true, predicted))\ntrue_negative = np.sum(np.logical_and(not_true, not_predicted))\nfalse_positive = np.sum(np.logical_and(not_true, predicted))\nfalse_negative = np.sum(np.logical_and(true, not_predicted))\n</code></pre>\n<p>Note that you cannot use <code>~true</code> and <code>~predicted</code> here, since that does two's complement or something like that...</p>\n<p>Finally, note that I could not find proof for or against <code>np.logical_and</code> (or <code>np.logical_not</code> for that matter) being implemented efficiently for <code>sparse</code> vectors, so maybe that is where you actually loose speed. In that case, go and implement it in C and/or Cython and write a pull request for <code>sparse</code>, I guess...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:33:36.270",
"Id": "502768",
"Score": "1",
"body": "By jove! This shared off another ~15 seconds in my test data. I did try using cython, btw, with no real increase in speed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T09:16:03.200",
"Id": "254878",
"ParentId": "254814",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254878",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T01:07:38.003",
"Id": "254814",
"Score": "4",
"Tags": [
"python",
"performance",
"vectorization"
],
"Title": "optimize binary classification method for speed"
}
|
254814
|
<p>Given a 2-column CSV dictionary file that contains translation of certain words, this c# code needs to replace the first occurrence of a word in the dictionary.</p>
<ul>
<li>Once a segment of string has been replaced, it cannot be matched or overwritten by a new dictionary word.</li>
</ul>
<p>This sounded like a fairly simple task but the code I came up with runs horribly slow and I'm looking for ways to improve it.</p>
<p>All the offending code is in the <code>TestReplace</code> function, I build up a hashset that keeps track of what character Ids in the string have been touched. When you apply a rule that changes the lenght of the string, all the character ids switch around so they have to be recalculated and I believe it costs a lot of performance. Wish there was a simpler way to do this !</p>
<p>Here is a super simple case of what the code tries to do :</p>
<p>Dictionary file:</p>
<p><code>hello</code> >>> <code>hi</code></p>
<p><code>hi</code> >>> <code>goodbye</code></p>
<p>Input: hello, world!</p>
<p>First rule is applied so string becomes -> <code>hi, world</code>. The word <code>hi</code> is now locked.</p>
<p>Second rule is applied but the string does not become <code>goodbye, world</code> since this part is locked.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace stringReplacer
{
class Program
{
public static Dictionary<string, string> ReplacementRules = new Dictionary<string, string>()
{
{"John","Freddy" },
{"John walks","Freddy runs" },
{"brown dog","gray dog" },
{"dog","cat" },
{"- not -", "(not)" },
{"(","" },
{")","" },
{"whenever", "sometimes, when"},
{"raining", "snowing" },
{"his", "many" }
};
static void Main(string[] args)
{
string Input = "John walks his brown dog whenever it's - not - raining";
string ExpectedOutput = "Freddy walks many gray dog sometimes, when it's (not) snowing";
string TestReplaceOutput = TestReplace(Input, ReplacementRules);
ValidateReplacement("TestReplace", TestReplaceOutput, ExpectedOutput);
}
public static string TestReplace(string input, Dictionary<string, string> ReplacementRules)
{
HashSet<int> LockedStringSegment = new HashSet<int>();
foreach (var rule in ReplacementRules)
{
string from = Regex.Escape(rule.Key);
string to = rule.Value;
var match = Regex.Match(input, from);
if (match.Success)
{
List<int> AffectedCharacterPositions = Enumerable.Range(match.Index, match.Length).ToList();
if (!AffectedCharacterPositions.Any(x => LockedStringSegment.Contains(x)))
{
input = Regex.Replace(input, from, to);
int LengthDelta = to.Length - rule.Key.Length;
LockedStringSegment
.Where(x => x > match.Index + rule.Key.Length).OrderByDescending(x => x).ToList()
.ForEach(x =>
{
//We shuffle the locked character's place depending on the replacement delta.
LockedStringSegment.Remove(x);
LockedStringSegment.Add(x + LengthDelta);
});
//Add all the new locked character's position to the hashset.
Enumerable.Range(match.Index, to.Length).ToList().ForEach(x => LockedStringSegment.Add(x));
}
}
}
return input;
}
public static void ValidateReplacement(string MethodName, string Actual, string Expected)
{
Console.Write($"{MethodName} : ");
if (Expected != Actual)
Console.WriteLine("String replacement doesn't work");
else
Console.WriteLine("It works");
Console.WriteLine($"Expected : {Expected}");
Console.WriteLine($"Actual : {Actual} \n\n");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A recursive solution seems like a good fit for this problem.</p>\n<pre><code> public static string ReplaceOnce(\n string input, \n Dictionary<string, string> ReplacementRules)\n {\n var matches = ReplacementRules.Where(rule => input.Contains(rule.Key));\n if (!matches.Any()) return input;\n\n var match = matches.First();\n int startIndex = input.IndexOf(match.Key);\n int endIndex = startIndex + match.Key.Length;\n\n var before = ReplaceOnce( input.Substring(0,startIndex), ReplacementRules );\n var replaced = match.Value;\n var after = ReplaceOnce( input.Substring(endIndex), ReplacementRules );\n\n return before + replaced + after;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T14:31:51.967",
"Id": "502621",
"Score": "2",
"body": "I'm amazed at how well this works while also being around 100 times faster than the code I had come up with."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T03:16:39.437",
"Id": "254818",
"ParentId": "254817",
"Score": "3"
}
},
{
"body": "<p>Another possible solution is to use a <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"nofollow noreferrer\">Trie</a>.<br/></p>\n<p>Using a Trie costs more in setup and space than the original solution but if we are going to be processing a lot of strings with the same set of rules, the cost of setup becomes less of an issue.</p>\n<p>Another advantage of the Trie approach is that processing an individual input scales with the length of the input and not with the number of rules.</p>\n<br/>\n<p>In essence, we start at the first character of the input and try to match it against the first character of any of the rules (using a dictionary, so the cost is low).</p>\n<p>If we do not find a match we add that character to the output and move to the next character.<br/></p>\n<p>If we find a match, we try to match the next character of the input against the next character of any of the matching rules (discarding rules as we go), progressing until the input next character of the input no longer matches the next character of any of the remaining matching rules.</p>\n<p>At this point we have either matched a rule (IsLeaf == true) and we add the value to the output or else what we have matched was only a fragment (e.g. the input was 'do ' and the rule was 'dog') and we add that fragment of the input to the output and start matching against the full set of rules from the next character in the input.</p>\n<pre><code>public class Trie\n{\n\n private readonly IDictionary<char, Trie> _lookup = new Dictionary<char, Trie>();\n\n public bool Check(char ch, out Trie next)\n {\n return _lookup.TryGetValue(ch, out next);\n }\n\n public char Char { get; set; }\n\n public string Key { get; set; }\n\n public string Value { get; set; }\n\n public bool IsLeaf => Value != null;\n\n public void Add(string key, string replacement)\n {\n if (string.IsNullOrEmpty(key))\n {\n throw new ArgumentException("key");\n }\n\n Trie trie = null;\n var lookup = _lookup;\n foreach(var ch in key)\n {\n if(!lookup.TryGetValue(ch, out trie))\n {\n trie = new Trie { Char = ch };\n lookup.Add(ch, trie);\n }\n lookup = trie._lookup;\n }\n trie.Key = key;\n trie.Value = replacement;\n }\n\n}\n\n\npublic interface ITextReplacer\n{\n string Replace(string text);\n}\n\n\npublic class TrieReplacer : ITextReplacer\n{\n\n private readonly Trie _root;\n\n public TrieReplacer(IDictionary<string, string> replacementRules)\n {\n _root = CreateRoot(replacementRules);\n }\n\n private static Trie CreateRoot(IDictionary<string, string> replacementRules)\n {\n var ret = new Trie();\n foreach(var replacement in replacementRules)\n {\n ret.Add(replacement.Key, replacement.Value);\n }\n return ret;\n }\n\n public string Replace(string text)\n {\n var ret = new StringBuilder();\n var currentPos = 0;\n\n while(currentPos < text.Length)\n {\n Trie currentTrie = _root;\n Trie innerTrie;\n while((currentPos < text.Length) && !currentTrie.Check(text[currentPos], out innerTrie))\n {\n ret.Append(text[currentPos++]);\n }\n var savedPos = currentPos;\n while ((currentPos < text.Length) && currentTrie.Check(text[currentPos], out innerTrie))\n {\n currentPos++;\n currentTrie = innerTrie;\n if (currentTrie.IsLeaf) break;\n }\n // not a leaf means that we haven't a match before the input end\n if(currentTrie.IsLeaf)\n {\n ret.Append(currentTrie.Value);\n }\n else\n {\n ret.Append(text.Substring(savedPos, (currentPos - savedPos)));\n }\n \n }\n return ret.ToString();\n\n\n }\n}\n</code></pre>\n<p><strong>Other</strong><br/></p>\n<p>I think there is a problem with the original in terms of functionality but I am not sure. If I am reading the description correctly we should support overlapping keys and use the first match found.</p>\n<p>We currently have rules</p>\n<ul>\n<li>John -> Freddy</li>\n<li>John walks -> Freddy runs</li>\n</ul>\n<p>and because of the order, we match <em>John</em> ahead of <em>John walks</em> and thus</p>\n<p><em>'John walks his brown dog whenever it's - not - raining'</em></p>\n<p>becomes</p>\n<p><em>'Freddy walks his brown dog whenever it's - not - raining'</em></p>\n<p>If the rules were reversed, we would match the long one first and get</p>\n<p><em>'Freddy runs his brown dog whenever it's - not - raining'</em></p>\n<p>Now, say, we change the rules to</p>\n<ul>\n<li>John walks -> Freddy runs</li>\n<li>runs -> trots</li>\n</ul>\n<p>We get (as expected)</p>\n<p><em>'Freddy runs his brown dog whenever it's - not - raining'</em></p>\n<p>The 'runs' to 'trots' change is not made because 'Freddy runs' is in our <strong>LockedStringSegment</strong>. All good.</p>\n<p>Now, if we change the input to</p>\n<p><em>'Tom runs and John walks his brown dog whenever it's - not - raining'</em></p>\n<p>we would expect</p>\n<p><em>'Tom trots and Freddy runs his brown dog whenever it's - not - raining'</em></p>\n<p>but we get</p>\n<p><em>'Tom trots and Freddy <strong>trots</strong> his brown dog whenever it's - not - raining'</em></p>\n<p>This is because after the check to see if the match for the new key ('runs') is in the <strong>LockedStringSegment</strong> (it's not), we use the Regex to replace <em>all</em> instances of <em>runs</em> with <em>trots</em> which includes those in the <strong>LockedStringSegment</strong></p>\n<pre><code>List<int> AffectedCharacterPositions = Enumerable.Range(match.Index, match.Length).ToList();\n\nif (!AffectedCharacterPositions.Any(x => LockedStringSegment.Contains(x)))\n{\n input = Regex.Replace(input, from, to);\n</code></pre>\n<p>When we match 'runs', the text is</p>\n<p><em>'Tom runs and Freddy runs his brown dog whenever it's - not - raining'</em></p>\n<p>the first match for 'runs' ('Tom <strong>runs</strong>') is not in the locked segment so we replace all</p>\n<p><em>'Tom trots and Freddy trots his brown dog whenever it's - not - raining'</em></p>\n<p>Similarly, if the input was</p>\n<p><em>'John walks his brown dog whenever it's - not - raining - and Tom runs'</em></p>\n<p>we would get\n'<em>Freddy runs many gray dog sometimes, when it's (not) snowing - and Tom <strong>runs</strong>'</em></p>\n<p>The first match of 'runs' is inside the LockedStringSegment so none of the occurrences of runs are replaced.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:13:29.160",
"Id": "502765",
"Score": "0",
"body": "Wow you're right, I didn't think of the side effect of regex.replace replacing multiple matches. I will look into this TRIE algorithm and see if I can use it in my case, thanks for the example it's extremely useful as I'm not sure I'd have figured out how to implement this from the wikipedia page alone !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T10:50:13.337",
"Id": "254881",
"ParentId": "254817",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "254818",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T02:32:59.230",
"Id": "254817",
"Score": "2",
"Tags": [
"c#",
"performance",
"strings",
"regex"
],
"Title": "Replace string based on multiple rules, don't replace same section twice"
}
|
254817
|
<p>I was trying to designing a simplified parking lot management system. It has three types of slots (s,m,l). The goal here is that we want to make the placement/release of cars as efficient as possible, ideally O(1).</p>
<p>The way I implemented is to use 3 separate stacks to hold empty spots for small, medium and large vehicles and whenever we have a vehicle to place, we check the stack of its size, if there is no empty spots for its size, we upgrade to the next stack of a larger size. So adding and releasing cars would be popping/pushing onto a stack so constant time complexity is guaranteed. And I also maintained a hash map to map the vehicle license id to the actual spot so we can do a constant time lookup when we need to retrieve a car.</p>
<p>Here is my code.</p>
<pre class="lang-js prettyprint-override"><code>class Spot {
constructor({ size, vehicle } = {}) {
this.size = size
this.vehicle = vehicle
}
addVehicle(vehicle) {
if(this.isOccupied()) return false
this.vehicle = vehicle
return true
}
isOccupied() {
return !!this.vehicle
}
getVehicle() {
return this.vehicle
}
releaseVehicle() {
const currentVehicle = this.vehicle
this.vehicle = null
return currentVehicle
}
}
class ParkingLotManager {
constructor({ size: { numOfSmallSpot, numOfMediumSpot, numOfLargeSpot } }) {
this.emptySpots = Array.from({ length: 3 }, (_, i) => {
if(this._getSizeIndex(1) === i) return Array.from({length: numOfSmallSpot}, () => (new Spot({size: 1})))
if(this._getSizeIndex(2) === i) return Array.from({length: numOfMediumSpot}, () => (new Spot({size: 2})))
if(this._getSizeIndex(3) === i) return Array.from({length: numOfLargeSpot}, () => (new Spot({size: 3})))
})
this.vehicles = new Map()
}
placeVehicle(vehicle) {
if(this.hasVehicle(vehicle.licenseId)) throw new Error('duplicate vehicle found')
const sizeIndex = this._getSizeIndex(vehicle.size)
for (let i = sizeIndex; i < this.emptySpots.length; i++) {
if (this.emptySpots[i].length > 0) {
const spot = this.emptySpots[i].pop()
spot.addVehicle(vehicle)
this.vehicles.set(vehicle.licenseId, spot)
return true
}
}
return false
}
_getSizeIndex(size) {
return size - 1
}
hasVehicle(licenseId) {
return this.vehicles.has(licenseId)
}
removeVehicle(vehicle) {
if (!this.hasVehicle(vehicle.licenseId)) return false
const spot = this.vehicles.get(vehicle)
spot.releaseVehicle()
this.vehicles.delete(vehicle)
this.emptySpots[this._getSizeIndex(this.spot.size)].push(spot)
return true
}
}
class Vehicle {
constructor(id) {
this.licenseId = id
}
}
class Motorcycle extends Vehicle {
constructor(id) {
super(id)
this.size = 1
}
}
class Car extends Vehicle {
constructor(id) {
super(id)
this.size = 2
}
}
class Truck extends Vehicle {
constructor(id) {
super(id)
this.size = 3
}
}
const parkingLotManager = new ParkingLotManager({
size: {
numOfSmallSpot: 2,
numOfMediumSpot: 2,
numOfLargeSpot: 2
}
})
const car1 = new Car('car1')
const car2 = new Car('car2')
const car3 = new Car('car3')
parkingLotManager.placeVehicle(car1)
parkingLotManager.placeVehicle(car2)
parkingLotManager.placeVehicle(car3)
const car4 = new Truck('car4')
const car5 = new Truck('car5')
parkingLotManager.placeVehicle(car4)
console.log(parkingLotManager);
</code></pre>
<p>Feel free to give me <em>any</em> feedback - including naming, design, encapsulation, extensibility etc.</p>
<p>Specifically, I hope I can improve these following aspects:</p>
<ol>
<li><p>I am not particular clear on when I should throw an exception or return <code>false</code> for unsuccessful operation. For example, for <code>placeVehicle</code> method, if there is no empty spots, should I return <code>false</code> to indicate that the operation failed or should I just throw an exception? I guess it depends. but I wonder under which specific situation one approach is favorable than the other?</p>
</li>
<li><p>The way I handle the mapping from <code>size</code> to the index of the stack which holds the empty spots isn't very elegant. I am an integar to indicate different sizes because I cannot think of a better way. If I am writing TypeScript I guess I can use <code>enum</code> or union types for <code>Size</code>. but even with <code>enum</code>, I still need to translate it into the actual index. I wonder how I can achieve this gracefully and it is also easily extensible so in the future, if I wanted to expand the parking lot, can I easily add a forth size?</p>
</li>
<li><p>If I have multiple entrances for this parking lot and there is one car coming into this spot in the parking lot and at the same time, another car will be out of the spot. Then there is a deadlock, how can I avoid or resolve that?</p>
</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T06:58:07.857",
"Id": "502579",
"Score": "0",
"body": "There's no ID for each Spot. Is it required that different spots of the same size are distinguished from each other?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T16:42:04.093",
"Id": "502634",
"Score": "0",
"body": "yea good catch. definitely they should be distinguished from each other. It is just I didn't find myself need to use a Spod Id. The hash map I have their will just return the spot instance when given the car license. Is there any situation you think I might need to use a spot Id?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T19:41:34.490",
"Id": "502665",
"Score": "0",
"body": "If there is no distinction then a single number of empty spots for each size would be more appropriate"
}
] |
[
{
"body": "<p><strong>Update</strong>: Added the hasVehicle() function, and added notes about performance.</p>\n<h2>Code Quality</h2>\n<p><strong>Remove the fluff</strong></p>\n<p>As I understand it, the Spot class exists purely to help implement the ParkingLotManager class. It exposes a couple of public functions that never get used by <code>ParkingLotManager()</code> and can be removed or made private. The constructor to Spot() current allows you to set a starting vehicle, but no code is using that feature either, so this ability can be removed.</p>\n<p><strong>for-of</strong></p>\n<p>Instead of</p>\n<pre><code>for (let i = sizeIndex; i < this.emptySpots.length; i++) {\n if (this.emptySpots[i].length > 0) { ... }\n}\n</code></pre>\n<p>you can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\">for-of</a> loop</p>\n<pre><code>for (const emptySpotGroup of this.emptySpots) {\n if (emptySpotGroup.length > 0) { ... }\n}\n</code></pre>\n<p><strong>Inheritance</strong></p>\n<p>I wouldn't say that it's always bad to use inheritance, but it certainly gets overused and often there's a better way to achieve the same objective. You can look up "Composition vs Inheritance" to learn more about this subject. In this scenario, instead of using inheritance to share information, you can use a factory function as follows:</p>\n<pre><code>const vehicleFactory = size => ({ licenseId }) => Object.freeze({ size, licenseId })\nconst createMotorcycle = vehicleFactory(0)\nconst createCar = vehicleFactory(1)\nconst createTruck = vehicleFactory(2)\n</code></pre>\n<h2>Answering Questions</h2>\n<p><strong>1. When to throw errors vs return a boolean (or other error-values)?</strong></p>\n<p>Javascript's error system isn't very great (it's very verbose to throw or catch errors of a specific subclass), which means there's some trade-offs to consider that largely depend on how defensively you want to program. Generally, its good to favor throwing errors as that can make it easier to track down bugs involving the program being in a bad state. If there's the ocasional rare case where you might need to catch the thrown error, then throw a subclass of Error instead of a normal Error object. If handling this exceptional case is somewhat common, then it can be more convenient to just return what's needed and let the user choose how to handle the result.</p>\n<p><strong>2. Dealing with vehicle sizes</strong></p>\n<p>Having integer-based sizes makes a lot of sense in this system, as it automatically provides an ordering to them. You can make your life even easier if you simply choose to make the sizes 0-based (small = 0, medium = 1, large = 2).</p>\n<p>In the places in code where you wish to refer to a size by name, you can provide an object that translates names to numbers, providing enum-like behavior. (i.e. <code>const SIZES = { small: 0, medium: 1, large: 2 }</code>)</p>\n<p><strong>3. How to avoid deadlocks?</strong></p>\n<p>By doing nothing. Javascript is single-threaded. In your implementation, you're never going to have a scenario where the javascript engine is executing one piece of code that's trying to put a vehicle into a stall while simultaneously executing different code that's taking a vehicle out. It always runs one task all the way to the end before starting the next one. This pattern of execution is referred to as javascript's event queue.</p>\n<h2>Performance</h2>\n<p>You wanted to make all of the functions run in O(1) time - I presume this is mostly to help exercise yourself in writing fast code. I just want to add a warning not to go overboard with performance in production applications - if you were building real parking-spot management software, there would be no reason to achieve O(1) lookup time, O(n) is good enough as there are only so many parking spots a lot can have. Development time is better spent improving other parts of the application.</p>\n<h2>Rewrite</h2>\n<p>Here's a rewrite of your code. You'll find that parts of the underlying logic are still very similar (I'm still using a 2d-array), but there's also a few fundamental changes (I took out the Spot class entirely). I have also chosen to assign ids to each parking spot. When you park a vehicle object, you get back the parking-spot id where it got stored. When it's time to drive it away, you get it back using that id.</p>\n<p>You'll notice I'm using three different data-structures to hold parking spot/vehicle information. If this wasn't trying to achieve O(1) performance, then only one data-structure would be needed, greatly simplifying the code further.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const randomId = () => Math.random().toString().slice(2, 8)\n\n// spotCountBySizes is an object of the shape\n// { <size numb>: <number of spots with that size>, ... }\nfunction createParkingLot(spotCountBySizes) {\n const spotSizes = Object.keys(spotCountBySizes).map(Number).sort()\n\n const occupiedSpots = {}\n const licenseIdsInLot = new Set()\n const freeSpotsBySize = spotSizes.map(\n size => Array.from({ length: spotCountBySizes[size] }, randomId)\n )\n\n return Object.freeze({\n placeVehicle(vehicle) {\n for (const size of spotSizes) {\n if (size >= vehicle.size && freeSpotsBySize[size].length > 0) {\n const spotId = freeSpotsBySize[size].pop()\n occupiedSpots[spotId] = { vehicle, spotSize: size }\n licenseIdsInLot.add(vehicle.licenseId)\n return spotId\n }\n }\n return null\n },\n removeVehicle(spotId) {\n const { vehicle, spotSize } = occupiedSpots[spotId]\n if (!vehicle) throw new Error(`The spot ${spotId} does not contain a vehicle.`)\n delete occupiedSpots[spotId]\n freeSpotsBySize[spotSize].push(spotId)\n licenseIdsInLot.delete(vehicle.licenseId)\n return vehicle\n },\n hasVehicle: licenseId => licenseIdsInLot.has(licenseId),\n })\n}\n\nconst vehicleFactory = size => ({ licenseId }) => Object.freeze({ size, licenseId })\nconst createMotorcycle = vehicleFactory(0)\nconst createCar = vehicleFactory(1)\nconst createTruck = vehicleFactory(2)\n</code></pre>\n<p>Example usage:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const randomId = () => Math.random().toString().slice(2, 8)\n\n// spotCountBySizes is an object of the shape\n// { <size numb>: <number of spots with that size>, ... }\nfunction createParkingLot(spotCountBySizes) {\n const spotSizes = Object.keys(spotCountBySizes).map(Number).sort()\n\n const occupiedSpots = {}\n const licenseIdsInLot = new Set()\n const freeSpotsBySize = spotSizes.map(\n size => Array.from({ length: spotCountBySizes[size] }, randomId)\n )\n\n return Object.freeze({\n placeVehicle(vehicle) {\n for (const size of spotSizes) {\n if (size >= vehicle.size && freeSpotsBySize[size].length > 0) {\n const spotId = freeSpotsBySize[size].pop()\n occupiedSpots[spotId] = { vehicle, spotSize: size }\n licenseIdsInLot.add(vehicle.licenseId)\n return spotId\n }\n }\n return null\n },\n removeVehicle(spotId) {\n const { vehicle, spotSize } = occupiedSpots[spotId]\n if (!vehicle) throw new Error(`The spot ${spotId} does not contain a vehicle.`)\n delete occupiedSpots[spotId]\n freeSpotsBySize[spotSize].push(spotId)\n licenseIdsInLot.delete(vehicle.licenseId)\n return vehicle\n },\n hasVehicle: licenseId => licenseIdsInLot.has(licenseId),\n })\n}\n\nconst vehicleFactory = size => ({ licenseId }) => Object.freeze({ size, licenseId })\nconst createMotorcycle = vehicleFactory(0)\nconst createCar = vehicleFactory(1)\nconst createTruck = vehicleFactory(2)\n\n\n// Example Usage\n\nconst SIZES = { small: 0, medium: 1, large: 2 }\nconst parkingLot = createParkingLot({\n [SIZES.small]: 2,\n [SIZES.medium]: 2,\n [SIZES.large]: 2,\n})\n\nconst car1 = createCar({ licenseId: 'car1' })\nconst car2 = createCar({ licenseId: 'car2' })\nconst car3 = createCar({ licenseId: 'car3' })\nconst truck4 = createTruck({ licenseId: 'truck4' })\nconst truck5 = createTruck({ licenseId: 'truck5' })\n\nconst id1 = parkingLot.placeVehicle(car1)\nconst id2 = parkingLot.placeVehicle(car2)\nconst id3 = parkingLot.placeVehicle(car3)\nconst id4 = parkingLot.placeVehicle(truck4)\nconsole.log(\n 'Attempting to add vehicle when lot is full. Spot id returned:',\n parkingLot.placeVehicle(truck5)\n)\nparkingLot.removeVehicle(id3)\nconsole.log(\n 'Attempting to add vehicle again now that there is room. Spot id returned:',\n parkingLot.placeVehicle(truck5)\n)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T11:04:11.713",
"Id": "503052",
"Score": "0",
"body": "NIce answer. You did drop the feature of checking whether a car is already checked in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-22T03:45:33.233",
"Id": "503119",
"Score": "0",
"body": "@konijn - Thanks, I've updated my answer to include the hasVehicle() function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T19:33:30.933",
"Id": "503616",
"Score": "0",
"body": "Hi thank you for the answer! I am curious about \"Composition vs Inheritance\". I have some knowledge of it but I wonder what benefits you think a factory function brings that a class doesn't? Or in other words, what are some pros and cons for choosing factory functions over class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-27T07:00:53.037",
"Id": "503644",
"Score": "0",
"body": "Composition can still be done with es6 classes - you can find plenty of examples online of this pattern. As I think about it some more, I might have been wrong to use that phrase in this scenario - you were mostly using inheritance to enforce a common interface and self-document a relationship, not to share behavior, meaning there was no behavior to compose, so normal composition solutions would not help there. I can't think of a good (and normal) way to remove this kind of inheritance with es6 classes, but it can be done with factory functions."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T04:00:36.187",
"Id": "255034",
"ParentId": "254822",
"Score": "2"
}
},
{
"body": "<p>In no particular order;</p>\n<ul>\n<li><p>If your constructor takes an object and then applies the key/pairs of that object you might as well go for <code>Object.assign(target, source);</code> like this;</p>\n<pre><code>constructor(template) {\n Object.assign(this, template);\n}\n</code></pre>\n</li>\n<li><p>I feel like you release a spot, not a vehicle. I would rename <code>releaseVehicle</code> to simply <code>release</code>. Furthermore it is super convenient for <code>release</code> to provide the vehicle that was there, but it makes the function name lie a bit? But then again, so does <code>Array.pop()</code> which does more than just popping. Final thought, since you have a ParkingLotManager anyway, I would let that class do a 'getVehicle' if needed, and then a <code>release</code>.</p>\n</li>\n<li><p>I would use the aptly named <code>Array.find()</code> to find an empty spot instead of a loop</p>\n</li>\n<li><p>I would separate the spot finding logic in to 'findFreeSpot(size)' unless it can be rewritten in to a one-liner</p>\n</li>\n<li><p>I would rename <code>addVehicle</code> to <code>setVehicle</code>, you can only add 1 vehicle to a spot</p>\n</li>\n<li><p>In the end, since vehicle is not private. I am not even sure I would encapsulate getters and setters</p>\n</li>\n<li><p>This is a parking lot system, for sure O(1) is impossible, it sounds like this code falls in to the trap of premature optimization, my counter proposal will be 'slower' but should be more readable and more extensible</p>\n</li>\n<li><p>However, in <code>removeVehicle</code> you go for <code>hasVehicle</code> which does the lookup, and then you go for <code>vehicles.get</code> which does the lookup again. You can drop one lookup by going straight for <code>vehicles.get</code> and checking for <code>undefined</code></p>\n</li>\n</ul>\n<p>This is my counter proposal.</p>\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>class Spot {\n constructor(template) {\n Object.assign(this, template);\n }\n\n fill(vehicle) {\n this.vehicle = vehicle\n }\n \n isFree(){\n return !this.vehicle\n }\n\n getVehicle() {\n return this.vehicle\n }\n\n release() {\n this.vehicle = undefined;\n }\n}\n\nclass ParkingLotManager {\n \n constructor(vehicleTypes){\n this.spots = [];\n this.vehicles = new Map();\n }\n \n addSpots(vehicleType, idList){\n idList.forEach(id =>{\n this.spots.push(new Spot({vehicleType, id}));\n });\n }\n \n hasVehicle(licenseId){\n return this.vehicles.has(licenseId);\n }\n\n placeVehicle(vehicle) {\n if(this.hasVehicle(vehicle.licenseId)){ //Do some UI stuff here, dont throw..\n console.log(`There is already a vehicle here with id ${vehicle.licenseId}`);\n return;\n } \n \n const spot = this.spots.find(spot => (vehicle instanceof spot.vehicleType && spot.isFree()));\n \n if(spot){\n spot.fill(vehicle)\n this.vehicles.set(vehicle.licenseId, spot);\n console.log(`Vehicle parked at ${spot.id}`)\n }else{\n console.log(`There is no free spot for ${vehicle.licenseId}`);\n }\n }\n\n removeVehicle(vehicle) {\n const spot = this.vehicles.get(vehicle.licenseId);\n if (spot){\n spot.release();\n this.vehicles.delete(vehicle.licenseId); \n }else{\n console.log(\"There is no vehicle with that license id\") \n }\n }\n \n}\n\nclass Vehicle {\n constructor(id) {\n this.licenseId = id\n }\n}\n\nclass Motorcycle extends Vehicle {\n constructor(id) {\n super(id)\n this.size = 1\n }\n}\n\nclass Car extends Vehicle {\n constructor(id) {\n super(id)\n this.size = 2\n }\n}\n\nclass VIP extends Vehicle {\n constructor(id) {\n super(id)\n this.size = 2\n }\n}\n\nclass Truck extends Vehicle {\n constructor(id) {\n super(id)\n this.size = 3\n }\n}\n\nconst parkingLotManager = new ParkingLotManager();\n\nparkingLotManager.addSpots(Motorcycle, ['M1', 'M2']);\nparkingLotManager.addSpots(Truck, ['T1', 'T2']);\nparkingLotManager.addSpots(Car, ['C1','C2']);\nparkingLotManager.addSpots(VIP, ['V1']);\n\nconst car1 = new Car('car1')\nconst car2 = new Car('car2')\nconst car3 = new Car('car3')\n\nparkingLotManager.placeVehicle(car1)\nparkingLotManager.placeVehicle(car1)\nparkingLotManager.placeVehicle(car2)\nparkingLotManager.placeVehicle(car3)\n\nconst car4 = new Truck('car4')\nconst car5 = new Truck('car5')\n\nparkingLotManager.placeVehicle(car4)\n\nconsole.log(parkingLotManager);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-21T07:51:35.587",
"Id": "255039",
"ParentId": "254822",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255034",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T04:29:53.077",
"Id": "254822",
"Score": "4",
"Tags": [
"javascript",
"object-oriented"
],
"Title": "JavaScript: Parking lot simplified OOD"
}
|
254822
|
<p>An elevator starts on the ground floor <code>0</code> and moves up or down by one floor at a time as described by an input string <code>travel</code>. Here's an example <code>travel</code> string <code>udddudduuuuddu</code> where <code>u</code> is a move up 1 floor and <code>d</code> is a move down 1 floor.</p>
<p><code>count-basement-trips</code> takes a <code>travel</code> string and counts how many times the elevator returns back to the ground floor from the dark and mysterious underground levels.</p>
<pre><code>(defun count-basement-trips (travel)
(flet ((finished-basement-trip-p (old-floor new-floor)
(and (= -1 old-floor)
(= 0 new-floor)))
(change (c)
(if (char= c #\u) 1 -1)))
(let ((floor 0)
(count 0))
(loop for c across travel
do (let ((new-floor (+ floor (change c))))
(if (finished-basement-trip-p floor new-floor)
(incf count))
(setf floor new-floor)))
count)))
(count-basement-trips "udddudduuuuddu")
</code></pre>
<p>The last expression evaluates to <code>2</code>.</p>
<p>What changes would make this more idiomatic Common Lisp? My goal is to speak more like a native. Thanks!</p>
|
[] |
[
{
"body": "<p>A few points.</p>\n<ol>\n<li><p><code>if</code> with only the “then” case is usually written with <code>when</code>, which is in general more handy since it allows several forms inside its body. So you could write <code>(when (finished-basement-trip-p floor new-floor) (incf count))</code>.</p>\n</li>\n<li><p>In a <code>loop</code> you can define variables that change at each iteration with the clause <code>for variable = expression</code>, and this in many cases avoid the use of nested <code>let</code> clauses, that make more difficult to read the program. Another useful iteration clause is <code>for variable = expression1 then expression2</code>, which assigns to <code>variabile</code> the value of <code>expression1</code> during the first iteration, and in all the others the value of <code>expression2</code>.</p>\n</li>\n<li><p>In a <code>loop</code>, if you need to count something and then return its value, you can use the “numeric accumulation” clause <code>count</code>, analogous to the <code>sum</code> clause, in which you count how many times a boolean espression is true.</p>\n</li>\n</ol>\n<p>Here is a proposed simplification. Note that in my version I do not use local functions since I think the program is easy enough to read without them. This is just a personal opinion.</p>\n<pre><code>(defun count-basement-trips (travel)\n (let ((floor 0))\n (loop for c across travel\n for up = (char= c #\\u)\n do (incf floor (if up 1 -1))\n count (and (zerop floor) up))))\n</code></pre>\n<p>Here's the buggy version suggested by @user235906 in a comment that got deleted. @Renzo points out it gives an incorrect answer for the test string <code>"ud"</code>:</p>\n<pre><code>(defun count-basement-trips (travel)\n (loop for c across travel\n for up? = (char= c #\\u)\n for floor = 0 then (incf floor (if up? 1 -1))\n for completed-trip? = (and up? (zerop floor))\n count completed-trip?))\n</code></pre>\n<p>And here's the suggested fix:</p>\n<pre><code>(defun count-basement-trips (travel)\n (loop for c across travel\n for up? = (char= c #\\u)\n for change = (if up? 1 -1)\n for floor = change then (incf floor change)\n for completed-trip? = (and up? (zerop floor))\n count completed-trip?))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T10:41:08.600",
"Id": "503988",
"Score": "1",
"body": "@user235906, you are welcome! Note that the solution that you proposed in the comment has been the first that I thought of. But it has a subtle error! Try it with the travel \"ud\", then try the same travel with my solution, and then you will find the problem. Then think about it to understand the reason of the error!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T10:49:38.963",
"Id": "503990",
"Score": "0",
"body": "For a good tutorial on `loop`, see the chapter [“LOOP for Black Belts”](http://www.gigamonkeys.com/book/loop-for-black-belts.html) of the book [“Practical Common Lisp”](http://www.gigamonkeys.com/book/)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-31T19:48:34.840",
"Id": "504012",
"Score": "0",
"body": "(note: Renzo is referring to a comment I deleted after failing to edit it, while the UI hadn't yet updated to show me his response... My buggy solution he's referring to is to use the `then` construct to use `0` as the initial value of `floor` instead of binding `floor` in a surrounding `let`)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:18:48.247",
"Id": "254835",
"ParentId": "254824",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254835",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T05:14:37.063",
"Id": "254824",
"Score": "4",
"Tags": [
"lisp",
"common-lisp"
],
"Title": "Count complete trips to the basement and back to ground floor"
}
|
254824
|
<p>I'm taking the CS50 course, and we're asked to create a program which takes an input (the total height of the pyramid) and outputs a pyramid of that height.</p>
<p>i.e Here’s how the program might work if the user inputs 8 when prompted:</p>
<pre><code>$ ./mario
Height: 8
# #
## ##
### ###
#### ####
##### #####
###### ######
####### #######
######## ########
</code></pre>
<p>Here is my code:</p>
<pre><code>#include <cs50.h>
#include <stdio.h>
void print_hashes(int width, int empty_space);
int main(void)
{
// Get height input between ranges 1 to 8 inclusive
int height;
do
{
height = get_int("Height: ");
}
while (height < 1 || height > 8);
// Loops through each row
for (int row = 1; row <= height; row++)
{
// Prints the left part of the pyramid, we need to print empty spaces before printing the hashes, so
// the width is equal to the height, amount of hashes printed is equal to the row, so amount of empty spaces is the width - row
print_hashes(height, height - row);
printf(" ");
// Prints the right part of the pyramid, we don't need to print empty spaces before printing hashes, so
// the width is equal to the amount of hashes, i.e the row and the amount of empty space is just 0
print_hashes(row, 0);
printf("\n");
}
}
void print_hashes(int width, int empty_space)
{
// Loops through the column in the row
for (int column = 0; column < width; column++)
{
// Checks if there needs to be an empty space within that column, if so print a space and if not print a hash
if (column < empty_space)
{
printf(" ");
}
else
{
printf("#");
}
}
}
</code></pre>
<p>I would like some feedback on my code and how I could improve it; things like readability, efficiency, etc.</p>
<p>Is my code easily understandable? Am I overdoing the comments? The reason I put a lot of comments is because in my experience, when looking at code days/weeks after writing it, I tend to forget what it does. So I wrote explanations so that I can easily understand the code in the future.</p>
<p>How do I improve the style, and are there any code conventions I'm not following? Can I optimize this to make it a faster process? Or maybe there's a better way to do the same thing? Basically, how do I improve my code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T06:01:09.780",
"Id": "502570",
"Score": "0",
"body": "Considering the purpose of the code, are you really interested in performance? I'd say the readability is a bigger concern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T06:28:02.547",
"Id": "502572",
"Score": "0",
"body": "Yeah performance shouldn't be that big of an issue since this is so simple. It's just weird since when I tried it with 100 levels it took a while to print everything out, though maybe that's an issue with the IDE or my computer. What can you tell me about the readability?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T06:53:03.053",
"Id": "502578",
"Score": "0",
"body": "You need more functions. I'll write something down later today."
}
] |
[
{
"body": "<p>A <em>pyramid</em> in geometry is a certain polyhedron i.e. a 3D structure. Your empty stripe in the middle turns it into a <em>stepped</em> pyramid.</p>\n<p>This can be split into two triangles, as you do with <code>print_hashes()</code>. But while the function is declared as:</p>\n<p><code>void print_hashes(int width, int empty_space)</code></p>\n<p>it is called with <code>height</code>, not <code>width</code></p>\n<p><code>print_hashes(height, height - row);</code></p>\n<p>This switch is somehow mentioned in the comment, but the code is confusing.</p>\n<p><strong>Triangle(s)</strong></p>\n<p>Instead of pyramids, rows/columns and hashes you maybe should be working with triangles. A pyramid (or triangle) of height 4 looks like:</p>\n<pre><code>123#...\n12###..\n1#####.\n#######\n</code></pre>\n<p>It has 1+3+5+7 = 16 = 4*4 hashes (sum of odd numbers). Everything can be known in advance. The numbers of spaces to be inserted is <code>3,2,1,0</code>, the number of hashes <code>1,3,5,7</code>. The bottom layer is 4+3=7, i.e. <code>base width = 2*height - 1</code>.</p>\n<p>Instead of looping:</p>\n<pre><code>for (int column = 0; column < width; column++)\n {\n // Checks if there needs to be an empty space within that column, if so print a space and if not print a hash\n if (column < empty_space)\n</code></pre>\n<p>you could prepare a whole line with string/array operators or <code>memset()</code> and print it at once at the end.</p>\n<p>The <strong>one-by-one printing</strong> of every "pixel" is what is slowing the program down, not the loop itself.</p>\n<p>You get along with no math and not much C at all - but at some price.</p>\n<p>A single string (array of chars) that gets changed and printed as line (and represents a layer) is more flexible and much faster. You allocate it, fill it, and then in a loop apply the changes and print it. String (=memory) operations are very fast, and <code>printf()</code> is very slow.</p>\n<hr />\n<p>These stairs in the middle are disruptive...but here is a solution that uses two (different, alas) simpler triangles:</p>\n<pre><code>#include <stdio.h>\n#include <string.h>\n\n// prints the left half-layer of a pyramid with height\n// layer 1 is the top layer; \nvoid print_hashes(int height, int layer)\n{\n char line[height+1];\n int empty = height - layer;\n memset(line, ' ', empty);\n memset(line + empty, '#', layer);\n line[height] = '\\0';\n printf("%s", line);\n}\n// right side \nvoid print_hashes_desc(int layer)\n{\n char line[layer+1];\n memset(line, '#', layer);\n line[layer] = '\\0';\n printf("%s", line);\n}\nint main(void)\n{\n // Ask for height\n int height;\n do\n {\n scanf("%d", &height);\n } while (height < 1 || height > 8);\n \n for (int layer = 1; layer <= height; layer++)\n {\n // Left part\n print_hashes(height, layer);\n // Middle (stairs)\n printf("__");\n // Right part \n print_hashes_desc(layer);\n printf("\\n");\n }\n}\n</code></pre>\n<p>Instead of memset() the string could also be filled with for-loop. The expression <code>empty = height - layer</code> is the only math involved.</p>\n<p>Edit: just realized that the simpler <code>_desc</code> function does not need <code>height</code>. So much for copy-pasting...this is all not so obvious, without handy string operations...and with these stairs in the middle. In the first link they gave up on "print_repeated()"-function.</p>\n<p>Output:</p>\n<pre><code> #__#\n ##__##\n ###__###\n ####__####\n #####__#####\n ######__######\n #######__#######\n########__########\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T22:51:02.837",
"Id": "502678",
"Score": "2",
"body": "Ouch! Memset and pointer arithmetics are not the right tool to fomat a string. They depend on the low-level working of C strings and pointers. It is difficult to read and brings to advantage. Imho."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T09:55:47.810",
"Id": "254833",
"ParentId": "254825",
"Score": "3"
}
},
{
"body": "<p><code>printf</code> is overkill for printing a single character - you could use <code>putc</code> instead.</p>\n<p>However, <code>printf</code> provides some useful facilities that we can use to our advantage. Look at this for inspiration:</p>\n<pre><code>#include <stdio.h>\n\nint main(void)\n{\n const int width = 8;\n for (int i = 0; i < width; ++i) {\n printf("%*s%.*s\\n", width-i, "", i, "################");\n }\n}\n</code></pre>\n<p>See how we can use <code>printf()</code> to pad the empty string with spaces, or truncate a longer string to a given width.</p>\n<p>You'll want to read the <code>printf</code> documentation to see how <code>.</code> and <code>*</code> are used in format strings, and think of a way to ensure you have enough <code>#</code> characters to print.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T14:16:08.110",
"Id": "502619",
"Score": "1",
"body": "Please explain what this code is doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T14:32:49.970",
"Id": "502622",
"Score": "0",
"body": "Why? This isn't spoon-feeding; reading the man page and really understanding `printf` is far more important than having the code for a single exercise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T14:35:42.097",
"Id": "502624",
"Score": "6",
"body": "After reading your answer I don't feel enriched. I've not learnt anything, apart from \"go RTFM\" is still alive and kicking."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:26:33.187",
"Id": "254836",
"ParentId": "254825",
"Score": "-2"
}
},
{
"body": "<p>The code can be structured better, so the code is more self-documenting.\nSelf-documenting code doesn't need as many comments, which makes it easier on everyone. Comments that aren't there can't be obsolete either.</p>\n<ul>\n<li>Take input (height)</li>\n<li>Output pyramid</li>\n</ul>\n<p>Those are the only lines I want to see in <code>main</code>. The rest should be in functions.\nYou started out nicely by creating a <code>print_hashes</code> function, but we can do better. For example, the entire <code>do ... while</code> can be in a function.</p>\n<pre><code>int ask_height(void)\n{\n // Get height input between ranges 1 to 8 inclusive\n int height;\n do\n {\n height = get_int("Height: ");\n } \n while (height < 1 || height > 8);\n return height;\n}\n</code></pre>\n<p>Now, we can start the <code>main</code> program like this instead:</p>\n<pre><code>int main(void)\n{\n int height = ask_height();\n</code></pre>\n<p>That turns 7 lines in <code>main</code> into 1 line in <code>main</code>. And since the function name is descriptive, the comments are almost obsolete.</p>\n<p>We can do the same thing with the rest of the program.</p>\n<pre><code>void print_pyramid(int height)\n{\n // Loops through each row\n for (int row = 1; row <= height; row++)\n {\n // Prints the left part of the pyramid, we need to print empty spaces before printing the hashes, so\n // the width is equal to the height, amount of hashes printed is equal to the row, so amount of empty spaces is the width - row\n print_hashes(height, height - row);\n printf(" ");\n // Prints the right part of the pyramid, we don't need to print empty spaces before printing hashes, so\n // the width is equal to the amount of hashes, i.e the row and the amount of empty space is just 0\n print_hashes(row, 0);\n printf("\\n");\n }\n}\n</code></pre>\n<p>And all of a sudden, we have nicely split-out code, each function has one and only 1 thing to do (you may want to read up on the SRP, the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single-responsibility principle</a>).</p>\n<p>Now your file starts like this:</p>\n<pre><code>#include <cs50.h>\n#include <stdio.h>\n\nint ask_height(void);\nvoid print_hashes(int width, int empty_space);\nvoid print_pyramid(int height);\n\nint main(void)\n{\n int height = ask_height();\n print_pyramid(height);\n}\n</code></pre>\n<p>That's it. The rest is in functions. The function names can probably be further improved, but I'm quite awful at that myself. If you want to go a step further, you don't even need a <code>height</code> variable in <code>main</code>. This works too:</p>\n<pre><code>int main(void)\n{\n print_pyramid(ask_height());\n}\n</code></pre>\n<p>The rest is in functions, and functions can be re-used. Besides, should you ever want to call your program from an outside location, that's a lot easier now too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T12:39:26.520",
"Id": "502611",
"Score": "0",
"body": "I've done some reading on SRP, but it seems like the principles (as well as the SOLID principles for which it's a part of) applies for OOP only. Are these principles applicable to functions as well? I'm not very familiar with OOP atm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T13:05:08.423",
"Id": "502612",
"Score": "0",
"body": "@xdxt For classes it becomes extra important, but there's little reason not to apply it outside of OO as well. You'll find out later there are some situations where not turning everything into a function makes sense too, but in the vast majority of cases you want to keep your functions nice and simple."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T13:11:06.450",
"Id": "502615",
"Score": "0",
"body": "What are some examples in which \"situations where not turning everything into a function makes sense\"? I'm curious. I really like the SRP approach as my code looks much cleaner now, but I'm wondering whether there are cases at which this principle would do more harm than good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T14:10:57.190",
"Id": "502618",
"Score": "0",
"body": "@xdxt It's not something you should be worried about now. But you'll probably encounter a situation where it's simply not worth the effort or where splitting up will lead to so many mini-functions that are already relatively small. There is such a thing as taking it too far, experience will tell you when you've reached that point. Sometimes it's nicer to have a function that appears a bit bigger, but still makes sense in its context. `main` should always be as compact (good use of functions, as shown) as possible, after that it varies how rigid you want/should be."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T11:37:44.900",
"Id": "254838",
"ParentId": "254825",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "254838",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T05:35:09.690",
"Id": "254825",
"Score": "5",
"Tags": [
"performance",
"beginner",
"c",
"programming-challenge",
"ascii-art"
],
"Title": "Printing pyramids in C (CS50)"
}
|
254825
|
<p>I'm learning priority scheduling algorithm and trying to implement it using <code>std::vector</code>. But the current performance of my code that's partially implemented is not that good since I'm performing <code>sort</code> operation every time I add a new process to <code>std::vector</code> list. Can somebody suggest ways I can improve my current partially implemented algorithm. This is my code:</p>
<pre><code>#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
void print_list(const std::vector<std::pair<int, int>>& pair_list) {
for (const auto& pa : pair_list)
std::cout << "process_ID: " << pa.first << ", " << "priority: " << pa.second << "\n";
std::cout << std::endl;
}
void add_pro(int pro_ID, int pro_pri, std::vector<std::pair<int, int>>& pair_list) {
pair_list.emplace_back(pro_ID, pro_pri);
std::sort(pair_list.begin(), pair_list.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) {
return a.second < b.second;
});
}
bool check_pro_is_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list) {
for (const auto& pa : pair_list) {
if (pa.first == pro_ID)
return true;
}
return false;
}
bool is_higher_pri_pro_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list) {
if (pair_list.front().first == pro_ID)
return false;
return true;
}
int main() {
std::vector<int> process_ID_list { 1345, 45, 5646, 52525, 55757, 23424, 68696, 55878, 667, 252 };
std::vector<int> process_pri_list { 41, 334, 747, 41, 47, 7, 75, 544, 42, 6 };
std::vector<std::pair<int, int>> pair_list;
for (int i = 0; i < process_ID_list.size(); ++i) {
int new_pro_ID = process_ID_list.at(i);
int new_pro_pri = process_pri_list.at(i);
if (!check_pro_is_present(new_pro_ID, pair_list))
add_pro(new_pro_ID, new_pro_pri, pair_list);
else
std::cout << "process is already in list" << std::endl;
print_list(pair_list);
}
int query_pro_ID = 1345;
std::cout << std::boolalpha << is_higher_pri_pro_present(query_pro_ID, pair_list) << std::endl;
return (EXIT_SUCCESS);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T07:09:23.363",
"Id": "502580",
"Score": "0",
"body": "One sound choice here is a priority queue, such as [`std::priority_queue`](https://en.cppreference.com/w/cpp/container/priority_queue)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T07:13:30.417",
"Id": "502581",
"Score": "1",
"body": "@JerryCoffin Actually I thought of using it, but the problem is I can't iterate through the list(without popping or copying) if I want to say print current list data and to remove any process from the list based on process identifier due to some reasons, if I implement using `std::priority_queue`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T07:16:07.323",
"Id": "502582",
"Score": "0",
"body": "In that case, perhaps a `vector` with `make_heap`, `pop_heap` (etc.) will be more amenable to your needs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T07:18:01.340",
"Id": "502583",
"Score": "0",
"body": "@JerryCoffin what about `std::set`?. Do you think it has better performance over `std::vector` in this case scenario?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T07:24:33.817",
"Id": "502584",
"Score": "0",
"body": "Harder to guess about set. With `set`, each node is dynamically allocated, so a lot here depends on how fast the allocator is (but it's probably at least worth a try)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:35:28.093",
"Id": "502605",
"Score": "0",
"body": "@Jerry, would you consider writing an answer that describes the pros and cons of the possible alternative types that could be used? I would, but I have other things that need doing today..."
}
] |
[
{
"body": "<p>While comments have suggested more suitable types than <code>std::vector</code>, I'm going to assume that the use of this underlying type is a given, and suggest straightforward improvements without changing that.</p>\n<p>The main performance concern is here:</p>\n<blockquote>\n<pre><code>void add_pro(int pro_ID, int pro_pri, std::vector<std::pair<int, int>>& pair_list) {\n pair_list.emplace_back(pro_ID, pro_pri);\n\n std::sort(pair_list.begin(), pair_list.end(), [=](std::pair<int, int>& a, std::pair<int, int>& b) {\n return a.second < b.second;\n });\n}\n</code></pre>\n</blockquote>\n<p>It's wasteful to sort the vector every time we add an element, when we know it was sorted before we called this function. Instead, we need to <em>insert</em> the new element in the correct position.</p>\n<pre><code>void add_pro(int pro_ID, int pro_pri, std::vector<std::pair<int, int>>& pair_list)\n{\n auto position = std::upper_bound(pair_list.begin(), pair_list.end(), pro_pri,\n [](auto pri, auto const& ele) { return pri < ele.second; });\n pair_list.emplace(position, pro_ID, pro_pri);\n}\n</code></pre>\n<hr />\n<p>We use the type <code>std::vector<std::pair<int, int>></code> a lot. It's worth giving it a name:</p>\n<pre><code>using priority_queue = std::vector<std::pair<int, int>>;\n</code></pre>\n<p>That makes changing the code easier, e.g. if we decide that process ids actually need to be <code>unsigned long</code> or something.</p>\n<p>However, I observe that <em>every</em> function takes one of these as an argument. That suggests that we want a class with this vector as member, then convert those free functions to be members of that class.</p>\n<hr />\n<p>Thank you for including the test program - that's always helpful in a review. There's a couple of small points:</p>\n<blockquote>\n<pre><code>for (int i = 0; i < process_ID_list.size(); ++i) {\n</code></pre>\n</blockquote>\n<p>We're mixing signed and unsigned types in this comparison (<code>int</code> and <code>std::size_t</code>). Obviously we should change <code>int i</code> to <code>std::size_t i</code> - and enable more compiler warnings.</p>\n<blockquote>\n<pre><code> std::cout << "process is already in list" << std::endl;\n</code></pre>\n</blockquote>\n<p>Prefer to use <code>std::cerr</code> for error messages.</p>\n<hr />\n<p>The pattern <code>if (condition) return true; else return false;</code> can simply be replaced with <code>return condition</code>. So:</p>\n<pre><code>bool is_higher_pri_pro_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list)\n{\n return pair_list.front().first != pro_ID;\n}\n</code></pre>\n<hr />\n<p>The loop in <code>check_pro_is_present</code> can be replaced with <code>std::any_of</code>:</p>\n<pre><code>bool check_pro_is_present(int pro_ID, const std::vector<std::pair<int, int>>& pair_list)\n{\n return std::any_of(pair_list.begin(), pair_list.end(),\n [pro_ID](auto const& e){ return e.first == pro_ID; });\n}\n</code></pre>\n<hr />\n<h1>Modified code</h1>\n<p>This is just a beginning - we'll probably want an initialiser-list constructor, and replace <code>print()</code> with <code>operator<<()</code>, but it's a start.</p>\n<pre><code>#include <algorithm>\n#include <iostream>\n#include <utility>\n#include <utility>\n#include <vector>\n\ntemplate<typename T, typename Priority = int>\nclass priority_queue\n{\n std::vector<std::pair<T, Priority>> values = {};\n\npublic:\n void print(std::ostream &os) const {\n for (const auto& pa : values) {\n os << "process_ID: " << pa.first << ", "\n << "priority: " << pa.second << '\\n';\n }\n std::cout << '\\n';\n }\n\n void add(T t, Priority pri) {\n auto const position\n = std::upper_bound(values.begin(), values.end(),\n pri,\n [](auto const& pri, auto const& ele) { return pri < ele.second; });\n values.emplace(position, std::move(t), std::move(pri));\n }\n\n bool contains(int pro_ID) const\n {\n return std::any_of(values.begin(), values.end(),\n [pro_ID](auto const& e){ return e.first == pro_ID; });\n }\n\n bool has_higher(int pro_ID) const\n {\n return values.front().first != pro_ID;\n }\n};\n\nint main()\n{\n const std::pair<int,int> processes[]\n = { { 1345, 41 }, { 45, 334 }, { 5646, 747 },\n { 52525, 41 }, { 55757, 47 },\n { 23424, 7 }, { 68696, 75 }, { 55878, 544 },\n { 667, 42 }, { 252, 6 } };\n\n priority_queue<int, int> queue;\n for (auto const& p: processes) {\n if (queue.contains(p.first)) {\n std::cerr << p.first << " is already in list\\n";\n } else {\n queue.add(p.first, p.second);\n }\n queue.print(std::cout);\n }\n\n int query_pro_ID = 1345;\n std::cout << std::boolalpha << queue.has_higher(query_pro_ID) << '\\n';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:27:32.040",
"Id": "502600",
"Score": "0",
"body": "Thanks for the suggestions. Well if you think that this can be better implemented other than using `std::vector`, please let me know."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:34:25.110",
"Id": "502604",
"Score": "0",
"body": "I might write a separate answer for that, if I get time. Or perhaps somebody else will?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T19:35:23.187",
"Id": "502664",
"Score": "1",
"body": "@TobySpeight, I can do that next week, although it might take time until Friday or so. I will ping you here if you’re interested in the results."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T10:17:48.380",
"Id": "254834",
"ParentId": "254828",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T06:55:08.863",
"Id": "254828",
"Score": "1",
"Tags": [
"c++",
"c++11"
],
"Title": "Priority scheduling algorithm using std::vector"
}
|
254828
|
<p>Hi I have wrote a code here for predicting temperature across months. This is the dataset that I was using: <a href="https://www.kaggle.com/sumanthvrao/daily-climate-time-series-data" rel="nofollow noreferrer">https://www.kaggle.com/sumanthvrao/daily-climate-time-series-data</a></p>
<p>I have used a SARIMA model and looking at the predicted results, it does seem to be pretty decent.</p>
<p>Given that I just started learning about a month ago and most of my reference materials are based off Youtube tutorial. I would just like to seek opinions from professional data scientist/ML experts on what are some caveats which I might have missed out or done wrongly here. (For instance, I saw in a video somewhere that mentioned RSS should be low whereas mine is pretty high here)</p>
<pre><code>%tensorflow_version 2.x # this line is not required unless you are in a notebook
import tensorflow as tf
from numpy import array
from numpy import argmax
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import os
#read data and filter temperature column
df = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/Weather Parameter/DailyDelhiClimateTrain.csv')
df["date"] = pd.to_datetime(df["date"])
df.date.freq ="D"
df.set_index("date", inplace=True)
df_monthly = df['meantemp'].resample('MS').mean()
plt.figure(figsize=(30,8))
plt.plot(df_monthly)
from statsmodels.tsa.seasonal import seasonal_decompose
sd = seasonal_decompose(df_monthly, model='additive')
sd.plot()
plt.show()
#make data stationary
df_monthly_diff = np.log(df_monthly).diff(12)
plt.figure(figsize=(15,5))
plt.plot(df_monthly_diff)
print(df_monthly_diff)
from statsmodels.tsa.stattools import adfuller
adf_result = adfuller(df_monthly_diff.dropna())
print('ADF Statistic: %f' % adf_result[0])
print('p-value: %f' % adf_result[1])
print('Critical Values:')
for key, value in adf_result[4].items():
print('\t%s: %.3f' % (key, value))
from statsmodels.tsa.stattools import acf
lag_acf = acf(df_monthly_diff.dropna())
plt.figure(figsize=(20,5))
plt.plot(lag_acf)
plt.show
from statsmodels.tsa.stattools import pacf
lag_pacf = pacf(df_monthly_diff.dropna())
plt.figure(figsize=(20,5))
plt.plot(lag_pacf)
plt.show
from statsmodels.tsa.arima_model import ARIMA
import statsmodels.api as sm
# fit model
model = sm.tsa.statespace.SARIMAX(df_monthly,order=(0, 1, 0),seasonal_order=(0,1,0,12))
model_fit = model.fit()
# summary of fit model
print(model_fit.summary())
# line plot of residuals
residuals = model_fit.resid
residuals.plot()
plt.show()
# density plot of residuals
residuals.plot(kind='kde')
plt.show()
# summary stats of residuals
print(residuals.describe())
plt.figure(figsize=(20,5))
plt.plot(df_monthly)
plt.plot(model_fit.fittedvalues, color='red')
rss = sum((model_fit.fittedvalues-df_monthly)**2)
plt.show
print(rss)
df_test = pd.read_csv('/content/drive/MyDrive/Colab Notebooks/Weather Parameter/DailyDelhiClimateTest.csv')
df_test["date"] = pd.to_datetime(df_test["date"])
df_test.date.freq ="D"
df_test.set_index("date", inplace=True)
df_test_monthly = df_test['meantemp'].resample('MS').mean()
pred = model_fit.predict(start=48,end=61,dynamic=True)
pred_df_monthly = df_monthly.append(pred)
df_monthly = df_monthly.append(df_test_monthly)
plt.figure(figsize=(20,8))
plt.plot(pred_df_monthly)
plt.plot(df_monthly)
plt.show
</code></pre>
<p><a href="https://i.stack.imgur.com/vewss.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vewss.png" alt="This is the predicted results" /></a></p>
<p>This is the predicted result from my code. Would really appreciate any comments. Thanks!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T07:09:36.773",
"Id": "254829",
"Score": "1",
"Tags": [
"machine-learning",
"tensorflow"
],
"Title": "Industrial Practices for Time-Series Forecasting"
}
|
254829
|
<p><a href="https://i.stack.imgur.com/zdp3o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zdp3o.png" alt="enter image description here" /></a>Sorry, I'm new and not confident. This is right, yes? It seems to work but, again, other people's answers seem more complicated:</p>
<pre><code>grid = [
['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']
]
row = 0
for entry in grid:
for subentry in grid[row]:
print(subentry, end = "")
print("\n")
row = row + 1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T07:45:00.397",
"Id": "502586",
"Score": "0",
"body": "Without knowing the purpose of this code, it's hard to review it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T08:07:56.310",
"Id": "502588",
"Score": "0",
"body": "Sorry, I've edited with the original task. You're supposed to print out the picture without the commas and brackets"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T08:21:44.783",
"Id": "502589",
"Score": "3",
"body": "Thank you. It's also best to [transcribe text](https://meta.stackexchange.com/a/332269/130301) instead of pasting images of text - images can't be read by screen readers, don't have the same controls as text for adapting to vision problems, and can't be indexed by search engines."
}
] |
[
{
"body": "<h2>The question itself</h2>\n<p>It's not great. The textbook makes some decisions that haven't done the programmer any favours. First, you will notice that the input and output are mirrored about the line <span class=\"math-container\">\\$x=y\\$</span>. This is not a coincidence: it's the result of the textbook using <a href=\"https://en.wikipedia.org/wiki/Row-_and_column-major_order\" rel=\"nofollow noreferrer\">column-major order</a> when row-major order makes much more sense in this context.</p>\n<p>Also, the grid presented is not only a sequence of sequences, it's a sequence of sequences <em>of sequences</em> since there are inner strings.</p>\n<p>To solve both problems, ignore what the textbook tells you and instead attempt to code for this grid:</p>\n<pre><code>grid = (\n '..OO.OO..',\n # ...\n)\n</code></pre>\n<p>and use <code>[y][x]</code> indexing instead of <code>[x][y]</code> indexing.</p>\n<p>Such changes will reduce this to a much more trivial problem that does not require any explicit loops, and can be done via</p>\n<pre><code>print('\\n'.join(grid))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T04:35:39.200",
"Id": "502839",
"Score": "0",
"body": "huh? So why is mine simpler?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T05:26:56.200",
"Id": "502840",
"Score": "0",
"body": "I don't understand the question. Yours isn't simpler - it has explicit loops and an additional level of sequence nesting in the input data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T06:28:56.450",
"Id": "502940",
"Score": "0",
"body": "That's like saying a 10 page book on transcendental logic is easier than a 100 page book on the Teletubbies because it's shorter"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T14:53:39.520",
"Id": "502964",
"Score": "0",
"body": "Very funny. By \"simpler\" here I mean shorter code, with less complexity presented to the interpreter, and likely to execute more quickly. If you have specific questions about how this works feel free to ask them."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T15:59:37.980",
"Id": "254846",
"ParentId": "254830",
"Score": "1"
}
},
{
"body": "<p><code>for subentry in grid[row]:</code> can be simplified as <code>for subentry in entry:</code>, meaning that you no longer need the <code>row</code> variable. As for</p>\n<blockquote>\n<p>That doesn't work</p>\n</blockquote>\n<p>:</p>\n<pre><code>$ diff <(python original.py) <(python my.py) && echo "No difference"\nNo difference\n$ diff --unified original.py my.py \n--- original.py 2021-01-18 19:34:02.177350487 +1300\n+++ my.py 2021-01-18 19:34:43.855590559 +1300\n@@ -12,7 +12,7 @@\n \n row = 0\n for entry in grid:\n- for subentry in grid[row]:\n+ for subentry in entry:\n print(subentry, end = "")\n print("\\n")\n row = row + 1\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T22:10:54.120",
"Id": "254865",
"ParentId": "254830",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T07:24:22.050",
"Id": "254830",
"Score": "4",
"Tags": [
"python",
"beginner"
],
"Title": "Character Picture Grid (from Automate the Boring Stuff)"
}
|
254830
|
<p>Previous: <a href="https://codereview.stackexchange.com/q/254260/188857">Advent of Code 2020 - Day 2: validating passwords</a></p>
<h1>Problem statement</h1>
<p>I decided to take a shot at <a href="https://adventofcode.com/2020" rel="nofollow noreferrer">Advent of Code 2020</a> to exercise my Rust knowledge. Here's the task for Day 3:</p>
<blockquote>
<h2>Day 3: Password Philosophy</h2>
<p>[...]</p>
<p>Due to the local geology, trees in this area only grow on exact
integer coordinates in a grid. You make a map (your puzzle input) of
the open squares (<code>.</code>) and trees (<code>#</code>) you can see. For example:</p>
<pre><code>..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#
</code></pre>
<p>These aren't the only trees, though; due to something you read about
once involving arboreal genetics and biome stability, the same pattern
repeats to the right many times:</p>
<pre><code>..##.........##.........##.........##.........##.........##....... --->
#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..
.#....#..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.
..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#
.#...##..#..#...##..#..#...##..#..#...##..#..#...##..#..#...##..#.
..#.##.......#.##.......#.##.......#.##.......#.##.......#.##..... --->
.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#
.#........#.#........#.#........#.#........#.#........#.#........#
#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...#.##...#...
#...##....##...##....##...##....##...##....##...##....##...##....#
.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.# --->
</code></pre>
<p>You start on the open square (<code>.</code>) in the top-left corner and need to
reach the bottom (below the bottom-most row on your map).</p>
<p>The toboggan can only follow a few specific slopes (you opted for a
cheaper model that prefers rational numbers); start by <strong>counting all
the trees</strong> you would encounter for the slope <strong>right 3, down 1</strong>:</p>
<p>From your starting position at the top-left, check the position that
is right 3 and down 1. Then, check the position that is right 3 and
down 1 from there, and so on until you go past the bottom of the map.</p>
<p>The locations you'd check in the above example are marked here with
<code>O</code> where there was an open square and <code>X</code> where there was a tree:</p>
<pre><code>..##.........##.........##.........##.........##.........##....... --->
#..O#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#..
.#....X..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#.
..#.#...#O#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#
.#...##..#..X...##..#..#...##..#..#...##..#..#...##..#..#...##..#.
..#.##.......#.X#.......#.##.......#.##.......#.##.......#.##..... --->
.#.#.#....#.#.#.#.O..#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#
.#........#.#........X.#........#.#........#.#........#.#........#
#.##...#...#.##...#...#.X#...#...#.##...#...#.##...#...#.##...#...
#...##....##...##....##...#X....##...##....##...##....##...##....#
.#..#...#.#.#..#...#.#.#..#...X.#.#..#...#.#.#..#...#.#.#..#...#.# --->
</code></pre>
<p>In this example, traversing the map using this slope would cause you
to encounter <code>7</code> trees.</p>
<p>Starting at the top-left corner of your map and following a slope of
right 3 and down 1, <strong>how many trees would you encounter?</strong></p>
<p>[...]</p>
<h3>Part Two</h3>
<p>Time to check the rest of the slopes - you need to minimize the
probability of a sudden arboreal stop, after all.</p>
<p>Determine the number of trees you would encounter if, for each of the
following slopes, you start at the top-left corner and traverse the
map all the way to the bottom:</p>
<ul>
<li>Right 1, down 1.</li>
<li>Right 3, down 1. (This is the slope you already checked.)</li>
<li>Right 5, down 1.</li>
<li>Right 7, down 1.</li>
<li>Right 1, down 2.</li>
</ul>
<p>In the above example, these slopes would find <code>2</code>, <code>7</code>, <code>3</code>, <code>4</code>, and
<code>2</code> tree(s) respectively; multiplied together, these produce the
answer <code>336</code>.</p>
<p>What do you get if you multiply together the number of trees
encountered on each of the listed slopes?</p>
</blockquote>
<p>The full story can be found on the <a href="https://adventofcode.com/2020/day/3" rel="nofollow noreferrer">website</a>.</p>
<h1>My solution</h1>
<p><strong>src/day_3.rs</strong></p>
<pre class="lang-rust prettyprint-override"><code>use {
anyhow::{anyhow, bail, ensure, Result},
itertools::Itertools,
ndarray::prelude::*,
std::io::{self, prelude::*},
};
pub const PATH: &str = "./data/day_3/input";
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Pixel {
Empty,
Tree,
}
impl Pixel {
pub fn from_char(c: char) -> Result<Self> {
match c {
'.' => Ok(Self::Empty),
'#' => Ok(Self::Tree),
_ => bail!("invalid pixel"),
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct Terrain {
pixels: Array2<Pixel>,
}
impl Terrain {
pub fn parse_from<R: BufRead>(reader: R) -> Result<Self> {
TerrainParser::parse(reader.lines())
}
pub fn slope_count(&self, delta_x: usize, delta_y: usize) -> usize {
assert!(delta_y != 0, "delta_y is zero");
let pixels = &self.pixels;
(0..pixels.nrows())
.step_by(delta_y)
.zip((0..).step_by(delta_x).map(|x| x % pixels.ncols()))
.filter(|pos| pixels[*pos] == Pixel::Tree)
.count()
}
}
#[derive(Debug)]
struct TerrainParser {
pixels: Vec<Pixel>,
width: usize,
height: usize,
}
impl TerrainParser {
fn parse<R: BufRead>(mut lines: io::Lines<R>) -> Result<Terrain> {
let first_line =
lines.next().ok_or_else(|| anyhow!("empty terrain"))??;
let mut parser = Self::parse_first_line(&first_line)?;
for line in lines {
parser = parser.parse_line(&line?)?;
}
let TerrainParser {
pixels,
width,
height,
} = parser;
Ok(Terrain {
pixels: Array2::from_shape_vec([height, width], pixels)?,
})
}
fn parse_first_line(line: &str) -> Result<Self> {
let pixels: Vec<_> =
line.chars().map(Pixel::from_char).try_collect()?;
let width = pixels.len();
ensure!(width != 0, "zero-width terrain");
Ok(Self {
pixels,
width,
height: 1,
})
}
fn parse_line(mut self, line: &str) -> Result<Self> {
let expected_len = self.pixels.len() + self.width;
self.pixels.reserve_exact(self.width);
itertools::process_results(
line.chars().map(Pixel::from_char),
|pixels| self.pixels.extend(pixels),
)?;
ensure!(self.pixels.len() == expected_len, "jagged terrain");
self.height += 1;
Ok(self)
}
}
#[cfg(test)]
mod tests {
use {super::*, std::io::BufReader};
#[test]
fn pixel_from_char() {
assert_eq!(Pixel::from_char('.').unwrap(), Pixel::Empty);
assert_eq!(Pixel::from_char('#').unwrap(), Pixel::Tree);
assert!(Pixel::from_char(' ').is_err());
}
#[test]
fn terrain_parse_from() -> anyhow::Result<()> {
fn parse(input: &str) -> Result<Terrain> {
Terrain::parse_from(BufReader::new(input.as_bytes()))
}
let expected = Array2::from_shape_vec(
[3, 3],
[Pixel::Empty, Pixel::Tree]
.iter()
.copied()
.cycle()
.take(9)
.collect(),
)?;
assert_eq!(parse(".#.\n#.#\n.#.\n")?.pixels, expected);
assert!(parse("").is_err());
assert!(parse(". #").is_err());
assert!(parse(".\n##").is_err());
Ok(())
}
#[test]
fn terrain_slope_count() -> anyhow::Result<()> {
// .#.
// #.#
// .#.
// #.#
let pixels = Array2::from_shape_vec(
[4, 3],
[Pixel::Empty, Pixel::Tree]
.iter()
.copied()
.cycle()
.take(12)
.collect(),
)?;
let terrain = Terrain { pixels };
assert_eq!(terrain.slope_count(1, 1), 1);
assert_eq!(terrain.slope_count(2, 1), 3);
assert_eq!(terrain.slope_count(3, 1), 2);
assert_eq!(terrain.slope_count(1, 2), 1);
Ok(())
}
}
</code></pre>
<p><strong>src/bin/day_3_1.rs</strong></p>
<pre class="lang-rust prettyprint-override"><code>use {
anyhow::Result,
aoc_2020::day_3::{self as lib, Terrain},
std::{fs::File, io::BufReader},
};
fn main() -> Result<()> {
let file = BufReader::new(File::open(lib::PATH)?);
let count = Terrain::parse_from(file)?.slope_count(3, 1);
println!("{}", count);
Ok(())
}
</code></pre>
<p><strong>src/bin/day_3_2.rs</strong></p>
<pre class="lang-rust prettyprint-override"><code>use {
anyhow::Result,
aoc_2020::day_3::{self as lib, Terrain},
std::{fs::File, io::BufReader},
};
const SLOPES: &[[usize; 2]] = &[[1, 1], [3, 1], [5, 1], [7, 1], [1, 2]];
fn main() -> Result<()> {
let file = BufReader::new(File::open(lib::PATH)?);
let terrain = Terrain::parse_from(file)?;
let product: usize = SLOPES
.iter()
.map(|&[delta_x, delta_y]| terrain.slope_count(delta_x, delta_y))
.product();
println!("{}", product);
Ok(())
}
</code></pre>
<p>Crates used: <a href="https://docs.rs/anyhow/1.0.37/anyhow/" rel="nofollow noreferrer"><code>anyhow</code> 1.0.37</a> <a href="https://docs.rs/itertools/0.10.0/itertools/" rel="nofollow noreferrer"><code>itertools</code> 0.10.0</a> <a href="https://docs.rs/ndarray/0.14.0/ndarray/" rel="nofollow noreferrer"><code>ndarray</code> 0.14.0</a></p>
<p><code>cargo fmt</code> and <code>cargo clippy</code> have been applied.</p>
|
[] |
[
{
"body": "<h2>Main files & solution layout</h2>\n<p>Seems OK. I always order my imports from the most standard to the most specific, so your order is (anyhow, aoc_2020, std) while mine would be (std, anyhow, aoc_2020).</p>\n<h2>lib::TerrainParser && lib::Terrain</h2>\n<p>In future Rust versions, you may do <code>.flatten()?</code> instead of the weird-looking <code>??</code>. We aren't at that stable point yet.</p>\n<p>I would consider implementing <code>TryFrom<TerrainParser></code> for <code>Terrain</code> for use in <code>TerrainParser::parse</code>. There's an argument against that -- exposing such a method is not needed.</p>\n<h2>fn slope_count</h2>\n<p>I "refactored" the main iteration logic as follows</p>\n<pre class=\"lang-rust prettyprint-override\"><code>let pos_x = (0..pixels.ncols()).cycle().step_by(delta_x);\nlet pos_y = (0..pixels.nrows()).step_by(delta_y);\npos_y.zip(pos_x)\n .filter(|pos| pixels[*pos] == Pixel::Tree)\n .count()\n</code></pre>\n<h2>Testing</h2>\n<p>Doing the <code>pixel_from_char</code> test seems entirely unnecessary. It reflects code 1:1. This is write-once code, but such tests would be a pain in write-often code contexts. Furthermore, you are already running this functionality from other tests. I'd focus on these other tests.</p>\n<p>I would change <code>assert_eq!(parse(".#.\\n#.#\\n.#.\\n")?.pixels, expected);</code> to</p>\n<pre class=\"lang-rust prettyprint-override\"><code>assert_eq!(\n parse(concat!(\n ".#.\\n",\n "#.#\\n",\n ".#.\\n"\n ))?.pixels,\n expected\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-11T01:32:21.453",
"Id": "505034",
"Score": "1",
"body": "Helpful review as always. The import order was chosen by `rustfmt` — this can be overrided with a separate `use std::{ /* ... */ }` though. The fact that the index order is `(Y, X)` rather than `(X, Y)` also trips me a lot :( As for testing, I don't think I've been paying enough attention to them, so I'll try to write concise and useful tests in the future. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-10T13:26:43.167",
"Id": "255843",
"ParentId": "254832",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255843",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T09:40:48.983",
"Id": "254832",
"Score": "1",
"Tags": [
"programming-challenge",
"parsing",
"rust"
],
"Title": "Advent of Code 2020 - Day 3: tobogganing down a slope"
}
|
254832
|
<p>I'm taking CS50, an Introduction to CS, and we're asked to do the following task:</p>
<blockquote>
<p>Suppose that a cashier owes a customer some change and in that cashier’s drawer are quarters (25¢), dimes (10¢), nickels (5¢), and pennies (1¢). The problem to be solved is to decide which coins and how many of each to hand to the customer. Think of a “greedy” cashier as one who wants to take the biggest bite out of this problem as possible with each coin they take out of the drawer. For instance, if some customer is owed 41¢, the biggest first (i.e., best immediate, or local) bite that can be taken is 25¢. (That bite is “best” inasmuch as it gets us closer to 0¢ faster than any other coin would.) Note that a bite of this size would whittle what was a 41¢ problem down to a 16¢ problem, since 41 - 25 = 16. That is, the remainder is a similar but smaller problem. Needless to say, another 25¢ bite would be too big (assuming the cashier prefers not to lose money), and so our greedy cashier would move on to a bite of size 10¢, leaving him or her with a 6¢ problem. At that point, greed calls for one 5¢ bite followed by one 1¢ bite, at which point the problem is solved. The customer receives one quarter, one dime, one nickel, and one penny: four coins in total</p>
</blockquote>
<p>Here is my solution to the problem:</p>
<pre><code>#include <stdio.h>
#include <cs50.h>
#include <math.h>
float cents, money;
int ask_money(void);
int dollars_to_cents(int dollars);
int get_max_coins(int _cents, int coin_type);
int min_coins_exchanged(int _money, int _coin_types[], int _arr_length);
int quarter = 25, dimes = 10, nickles = 5, pennies = 1;
int main(void)
{
money = dollars_to_cents(ask_money());
int arr_length = 4;
int coin_types[] = {quarter, dimes, nickles, pennies};
printf("%i\n", min_coins_exchanged(money, coin_types, arr_length));
}
// Given some amount of money, this returns the maximum amount of coins of a certain type possible
// such that the remaining money is less than the value of the coin type, then it subtracts our money by that amount
int get_max_coins(int _cents, int coin_type)
{
int max_coins = floor((float)((_cents) / coin_type));
money -= max_coins * coin_type;
return max_coins;
}
int ask_money(void)
{
do
{
money = get_float("Change owed: ");
}
while (money < 0);
return money;
}
// Necessary to avoid problems with floating point imprecision
int dollars_to_cents(int dollars)
{
return round(money * 100);
}
// Calculates the minimum amount of coins exchanged such that when these coins are added up they are equal to the change owed
int min_coins_exchanged(int _money, int _coin_types[], int _arr_length)
{
int _min_coins_exchanged = 0;
for(int i = 0; i < _arr_length; i++)
{
_money = money;
_min_coins_exchanged += get_max_coins(_money, _coin_types[i]);
}
return _min_coins_exchanged;
}
</code></pre>
<p>I'm looking for feedback on my code. How do I make my code better and cleaner? I.e in terms of readability, performance, comments, design principles, etc. There's a lot of ways to approach this problem, and indeed when trying to solve it I've tried many different ways but this is my current favorite. What do you think about my solution? Perhaps there's a better way to approach the problem?</p>
|
[] |
[
{
"body": "<p>This code needs compiling with more warnings enabled:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -std=c17 -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wstrict-prototypes -Wconversion 254841.c -o 254841\n254841.c: In function ‘main’:\n254841.c:14:13: warning: conversion from ‘int’ to ‘float’ may change value [-Wconversion]\n money = dollars_to_cents(ask_money());\n ^~~~~~~~~~~~~~~~\n254841.c:17:40: warning: conversion from ‘float’ to ‘int’ may change value [-Wfloat-conversion]\n printf("%i\\n", min_coins_exchanged(money, coin_types, arr_length));\n ^~~~~\n254841.c: In function ‘get_max_coins’:\n254841.c:24:21: warning: conversion from ‘double’ to ‘int’ may change value [-Wfloat-conversion]\n int max_coins = floor((float)((_cents) / coin_type));\n ^~~~~\n254841.c:25:11: warning: conversion from ‘int’ to ‘float’ may change value [-Wconversion]\n money -= max_coins * coin_type;\n ^~\n254841.c: In function ‘ask_money’:\n254841.c:36:12: warning: conversion from ‘float’ to ‘int’ may change value [-Wfloat-conversion]\n return money;\n ^~~~~\n254841.c: In function ‘dollars_to_cents’:\n254841.c:42:12: warning: conversion from ‘double’ to ‘int’ may change value [-Wfloat-conversion]\n return round(money * 100);\n ^~~~~~~~~~~~~~~~~~\n254841.c:40:26: warning: unused parameter ‘dollars’ [-Wunused-parameter]\n int dollars_to_cents(int dollars)\n ~~~~^~~~~~~\n254841.c: In function ‘min_coins_exchanged’:\n254841.c:51:18: warning: conversion from ‘float’ to ‘int’ may change value [-Wfloat-conversion]\n _money = money;\n ^~~~~\n</code></pre>\n<p>You have avoided some of the common traps, such as embedding the set of coins into the logic, although I wouldn't give those locale-specific names - here in Britain, we have 1, 2, 5, 10, 20, 50, 100 and 200 but they don't have nicknames.</p>\n<p>I would instead make the set of coins be a global constant, without naming them individually:</p>\n<pre><code>const unsigned int coin_values = {\n 25, /* quarter */\n 10, /* dime */\n 5, /* nickel */\n 1 /* penny */\n};\nconst size_t coin_values_len = sizeof coin_values / sizeof *coin_values;\n</code></pre>\n<p>Avoid using floating-point types for money. The problem is that .01 is not an exact fraction in binary, so the code is prone to error due to rounding.</p>\n<p>Instead, do something like</p>\n<pre><code>unsigned int dollars, cents = 0;\nif (scanf("%u.%u") < 1) {\n fputs("Currency parse failure\\n", stderr);\n return EXIT_FAILURE;\n}\n/* if we got here, we read the dollars, and perhaps the cents */\nunsigned int total_cents = 100 * dollars + cents; /* TODO: deal with overflow */\n</code></pre>\n<p>You're using some names that you shouldn't:</p>\n<blockquote>\n<pre><code>int get_max_coins(int _cents, int coin_type)\n</code></pre>\n</blockquote>\n<p>All identifiers beginning with <code>_</code> followed by a letter are reserved for use by the implementation. That means it's a bad idea to use these names in your own code. There's no reason not to just call the argument <code>cents</code> without that prefix, so that's what I'd recommend.</p>\n<p>There's some pointless conversion here:</p>\n<blockquote>\n<pre><code>int max_coins = floor((float)((_cents) / coin_type));\n</code></pre>\n</blockquote>\n<p><code>cents / coin_type</code> is of type <code>int</code>. We convert that to <code>float</code> (losing precision), truncate the fractional part (which will be zero, since we started with an integer) and then implicitly convert to <code>int</code>. That code is a very inefficient and problematic way to write</p>\n<blockquote>\n<pre><code>int max_coins = _cents / coin_type;\n</code></pre>\n</blockquote>\n<p>There's some serious problems with global variables, and there seems to be confusion passing values by parameter or via globals. Look at this:</p>\n<pre><code>float money;\n\nint main(void)\n{\n money = dollars_to_cents(ask_money());\n}\n\nint dollars_to_cents(int dollars)\n{\n return round(money * 100);\n}\n\nint ask_money(void)\n{\n do\n {\n money = get_float("Change owed: ");\n }\n while (money < 0);\n return money;\n}\n</code></pre>\n<p>In <code>main()</code>, we assign to <code>money</code>, which we're also using in <code>ask_money</code>. And <code>dollars_to_cents()</code> completely ignores its argument and shares the global variable. There's no need for this variable to be shared - each function can have its own local variable:</p>\n<pre><code>int main(void)\n{\n int money = dollars_to_cents(ask_money());\n}\n\nint dollars_to_cents(float dollars)\n{\n /* don't actually use float - see earlier in review */\n return round(dollars * 100);\n}\n\nfloat ask_money(void)\n{\n float money;\n do\n {\n money = get_float("Change owed: ");\n }\n while (money < 0);\n return money;\n}\n</code></pre>\n<hr />\n<h1>Summary</h1>\n<ul>\n<li>Eliminate the global variables</li>\n<li>Use more appropriate numeric types</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T15:06:18.607",
"Id": "254843",
"ParentId": "254841",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "254843",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T14:07:34.017",
"Id": "254841",
"Score": "0",
"Tags": [
"beginner",
"algorithm",
"c",
"programming-challenge"
],
"Title": "Greedy algorithms to find minimum number of coins (CS50)"
}
|
254841
|
<p><strong>Goal</strong></p>
<p>I am aiming to create a page with two columns, left side to be a summary section and the right side just an image.</p>
<p>I'd like to hear some reviews to where I can improve my current html and css code :)</p>
<p>It is not yet media responsive, just wanting to improve each step at a time.</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-css lang-css prettyprint-override"><code>* {
margin: 0;
padding: 0;
}
html {
font-size: 16px;
font-family: 'Playfair Display', serif;
height: 100%;
}
body {
background-color: black;
color: white;
height: 100%;
}
/* Social Links */
.fa-instagram {
background: none;
color: #fff;
text-decoration: none;
}
/* Navigation bar */
nav {
width: 100%;
display: flex;
justify-content: space-around;
align-items: center;
position: fixed;
background-color: black;
border-bottom: 1px solid gray;
z-index: 2;
}
nav h2 {
font-size: 2.5rem;
font-weight: bold;
}
/* About me */
#aboutme {
width: 80%;
margin: 0 auto;
}
#aboutme h1 {
color: gray;
margin-bottom: 1rem;
font-size: 1.9rem;
}
#aboutme img {
filter: grayscale(100%);
opacity: 0.5;
}
#aboutme .col {
width: 40%;
float: left;
margin-bottom: 4rem;
}
#aboutme img {
max-width: 100%;
min-height: 100%;
transition: all .2s;
}
#aboutme .summary {
padding-right: 3rem;
}
#aboutme .summary p:last-child {
font-size: .9rem;
width: 80%;
}
#aboutme img:hover {
transform: scale(1.1);
opacity: 1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<!-- NAVIGATION -->
<nav>
<div class="social-links">
<a href="#" class="fa fa-instagram"></a>
</div>
<div class="logo">
<h2>LOGO</h2>
</div>
<div>
<!-- TO ADD SOMETHING -->
</div>
</nav>
<section id="aboutme">
<h1>About me</h1>
<div class="education">
<h2>Education</h2>
<div>
<div class="summary col">
<h3>Title</h3>
<p>Title 2</p>
<p>2016 - 2020</p>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quia ducimus quibusdam amet consequatur reiciendis possimus. Accusantium dolor enim adipisci officia deserunt, reiciendis ipsum esse accusamus, maiores, molestias cupiditate rem pariatur!
Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<div class="col">
<img src="https://static01.nyt.com/images/2019/11/05/science/28TB-SUNSET1/merlin_163473282_fe17fc6b-78b6-4cdd-b301-6f63e6ebdd7a-superJumbo.jpg" alt="">
</div>
</div>
<div>
<div class="summary col">
<h3>Title</h3>
<p>Title 2</p>
<p>2020 - Present</p>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quia ducimus quibusdam amet consequatur reiciendis possimus. Accusantium dolor enim adipisci officia deserunt, reiciendis ipsum esse accusamus, maiores, molestias cupiditate rem pariatur!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempore non, recusandae blanditiis voluptate maxime, id quos dolorem fugit deleniti cum veniam facilis porro ut voluptatem! Eveniet suscipit consectetur optio dignissimos.</p>
</div>
<div class="col">
<img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__340.jpg" alt="">
</div>
</div>
</div>
</section>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Hello :) I'll try to review Your solution. Please take a look at the below comments:</p>\n<p>CSS:</p>\n<ul>\n<li>Avoid styling by the <code>id</code> tag. It gives 100 pts to the rule strength so it might be hard to overwrite that in the future</li>\n</ul>\n<p>HTML:</p>\n<ul>\n<li>I'm not sure if it's a good idea to put the logo in the <code>h2</code></li>\n<li>Your <code>h1</code> is not visible on the page at all</li>\n<li>Why did You leave the <code>img</code> alt tag empty ? Remember that is should only be empty in case it brings nothing new to the page content. (Google for Accessible images HTML)</li>\n<li>Your <code>a</code> tag does nothing. In that case it shouldn't really be an <code>a</code> tag.</li>\n<li><code>lang</code> property is missing in the HTML</li>\n<li>Some really important content is missing in Your <code>head</code> tag. Read about what should be placed there</li>\n</ul>\n<p>NOTES:</p>\n<ul>\n<li>Remove the unnecessary comments from the code. Also those which describe the self-explanatory code</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T10:46:02.560",
"Id": "503253",
"Score": "0",
"body": "Thanks for the comments! What's a lang property?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T10:49:43.127",
"Id": "503254",
"Score": "1",
"body": "https://www.w3schools.com/tags/att_lang.asp take a look at this link. The page is not the best source of good practices however this definition makes sense :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T10:29:57.887",
"Id": "255129",
"ParentId": "254842",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T14:48:57.013",
"Id": "254842",
"Score": "1",
"Tags": [
"html",
"css"
],
"Title": "HTML CSS 2 columns project"
}
|
254842
|
<p>The method gets called extensively throughout my programm, is there any way I can speed it up or improve other aspects?</p>
<hr />
<p>The code calculates the n-ary Cartesian Product of a List containing n Lists, so that for example:</p>
<p>Product([[1],[2,3],[4,5]]) yields [1,2,4],[1,2,5],[1,3,4],[1,3,5]</p>
<pre><code>public static IEnumerable<T[]> Product<T>(T[][] items)
{
T[] currentItem = new T[items.Length];
static IEnumerable<T[]> go(T[][] items, T[] currentItem, int index)
{
if (index == items.Length)
{
yield return currentItem;
yield break;
}
else
{
foreach (T item in items[index])
{
currentItem[index] = item;
foreach(var j in go(items, currentItem, index + 1))
{
yield return j;
}
}
}
}
return go(items, currentItem, 0);
}
</code></pre>
<hr />
<p>A possible problem i can think of, is the</p>
<pre><code>foreach(var j in go(items, currentItem, index + 1))
{
yield return j;
}
</code></pre>
<p>section, since it takes n yields for every (single) array that is part of the n-ary Cartesian Product.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T16:39:06.540",
"Id": "502633",
"Score": "2",
"body": "I must admit that I do not understand what this code does. Usually, it is enough to have two nested loops to create a cartesian product, but here you additionally have a recursive call. Also, a cartesian product is usually done over two sets. What are the two sets here? Can you please explain what your algorithm is supposed to do and how it works?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T16:53:07.883",
"Id": "502635",
"Score": "2",
"body": "I made an edit to the Post"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:01:36.153",
"Id": "502637",
"Score": "0",
"body": "Thank you for the edit. How big are the lists?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:12:54.773",
"Id": "502643",
"Score": "0",
"body": "The number of lists( < 15 in my use case) is always greater than the length of one individual list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T21:11:33.120",
"Id": "502674",
"Score": "1",
"body": "The total number of resulting lists is the product of the lengths of the individual input lists. This can be a huge number with 15 input lists. There is probably nothing wrong with the code."
}
] |
[
{
"body": "<p>The implementation contains one small but important bug (or feature?), it yields the same array instance from each loop.</p>\n<p>Consider this example.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>int[][] numbers = new[] { new[] { 1 }, new[] { 2, 3 }, new[] { 4, 5 } };\n\nforeach (int[] arr in Product(numbers))\n{\n Console.WriteLine(string.Join(", ", arr));\n}\n</code></pre>\n<p>The output is perfect</p>\n<pre class=\"lang-none prettyprint-override\"><code>1, 2, 4\n1, 2, 5\n1, 3, 4\n1, 3, 5\n</code></pre>\n<p>But if you want to store the result as jagged array and process it later:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>foreach (int[] arr in Product(numbers).ToArray())\n{\n Console.WriteLine(string.Join(", ", arr));\n}\n</code></pre>\n<p>You'll get this output</p>\n<pre class=\"lang-none prettyprint-override\"><code>1, 3, 5\n1, 3, 5\n1, 3, 5\n1, 3, 5\n</code></pre>\n<p>That's because it's an array of four references to the same array.</p>\n<p>Next small thing is one redundant line of code</p>\n<pre class=\"lang-cs prettyprint-override\"><code>yield break;\n</code></pre>\n<p>You don't need it because previous line is the last statement in the method. The method exits after it.</p>\n<p>Fix is simple</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static IEnumerable<T[]> Product<T>(T[][] items)\n{\n T[] currentItem = new T[items.Length];\n static IEnumerable<T[]> Go(T[][] items, T[] currentItem, int index)\n {\n if (index == items.Length)\n {\n yield return (T[])currentItem.Clone();\n }\n else\n {\n foreach (T item in items[index])\n {\n currentItem[index] = item;\n foreach (T[] j in Go(items, currentItem, index + 1))\n {\n yield return (T[])j.Clone();\n }\n }\n }\n }\n return Go(items, currentItem, 0);\n}\n</code></pre>\n<p>That's it.</p>\n<p>Performance while keeping it as returning arrays will be slow because e.g. for 10 arrays of 10 items it will yield <code>10*10*10*10*10*10*10*10*10*10 = 10000000000</code> arrays of 10 items each. But you want up to 15. It won't be fast at all.</p>\n<p>But let's try to eliminate the recursion.</p>\n<p>Consider an alternative implementation of the same</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static IEnumerable<T[]> MyProduct<T>(T[][] items)\n{\n int length = items.Length;\n int[] indexes = new int[length];\n\n while (true)\n {\n T[] arr = new T[length];\n for (int i = 0; i < length; i++)\n {\n arr[i] = items[i][indexes[i]];\n }\n yield return arr;\n\n int row = length - 1;\n indexes[row]++;\n while (indexes[row] == items[row].Length)\n {\n if (row == 0)\n yield break;\n indexes[row] = 0;\n row--;\n indexes[row]++;\n }\n }\n}\n</code></pre>\n<p>To understand this implementation imagine a digital clock. What if you make 3 arrays 24,60,60 items and fill it with numbers from 0 to 23/59. The <code>Product</code> will yield time to display for each second of the day - 86400 arrays of 3 items each. Then imagine how clock counts time on display and you'll catch the idea of this implementation.</p>\n<p>Looks like it works</p>\n<pre class=\"lang-none prettyprint-override\"><code>1, 2, 4\n1, 2, 5\n1, 3, 4\n1, 3, 5\n</code></pre>\n<p>And finally let's make a benchmark for both implementations. Using <strong>Benchmark.NET</strong> of course. For example with 6 arrays of 6 items each.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>[MemoryDiagnoser]\npublic class MyBenckmark\n{\n private int[][] numbers;\n\n [GlobalSetup]\n public void Setup()\n {\n numbers = new int[6][];\n for (int i = 0; i < 6; i++)\n {\n numbers[i] = Enumerable.Range(i * 6, 6).ToArray();\n }\n }\n\n [Benchmark]\n public void RunProduct()\n {\n foreach(var _ in Product(numbers)) ;\n }\n\n [Benchmark]\n public void RunMyProduct()\n {\n foreach (var _ in MyProduct(numbers)) ;\n }\n\n\n public static IEnumerable<T[]> Product<T>(T[][] items)\n {\n T[] currentItem = new T[items.Length];\n static IEnumerable<T[]> Go(T[][] items, T[] currentItem, int index)\n {\n if (index == items.Length)\n {\n yield return (T[])currentItem.Clone();\n }\n else\n {\n foreach (T item in items[index])\n {\n currentItem[index] = item;\n foreach (T[] j in Go(items, currentItem, index + 1))\n {\n yield return (T[])j.Clone();\n }\n }\n }\n }\n return Go(items, currentItem, 0);\n }\n\n public static IEnumerable<T[]> MyProduct<T>(T[][] items)\n {\n int length = items.Length;\n int[] indexes = new int[length];\n\n while (true)\n {\n T[] arr = new T[length];\n for (int i = 0; i < length; i++)\n {\n arr[i] = items[i][indexes[i]];\n }\n yield return arr;\n\n int row = length - 1;\n indexes[row]++;\n while (indexes[row] == items[row].Length)\n {\n if (row == 0)\n yield break;\n indexes[row] = 0;\n row--;\n indexes[row]++;\n }\n }\n }\n}\n</code></pre>\n<p>Go!</p>\n<pre class=\"lang-none prettyprint-override\"><code>BenchmarkDotNet=v0.12.1, OS=Windows 10.0.19042\nIntel Core i7-4700HQ CPU 2.40GHz (Haswell), 1 CPU, 8 logical and 4 physical cores\n.NET Core SDK=5.0.102\n [Host] : .NET Core 3.1.11 (CoreCLR 4.700.20.56602, CoreFX 4.700.20.56604), X64 RyuJIT\n DefaultJob : .NET Core 3.1.11 (CoreCLR 4.700.20.56602, CoreFX 4.700.20.56604), X64 RyuJIT\n\n| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |\n|------------- |----------:|----------:|----------:|----------:|------:|------:|----------:|\n| RunProduct | 28.509 ms | 0.2488 ms | 0.2077 ms | 6750.0000 | - | - | 20.08 MB |\n| RunMyProduct | 1.274 ms | 0.0103 ms | 0.0086 ms | 712.8906 | - | - | 2.14 MB |\n</code></pre>\n<p>You vote.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T09:07:33.527",
"Id": "502711",
"Score": "1",
"body": "Wow, thank you so much, that helped a lot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T08:58:22.340",
"Id": "254877",
"ParentId": "254845",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "254877",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T15:43:43.500",
"Id": "254845",
"Score": "3",
"Tags": [
"c#",
"performance"
],
"Title": "Calculating n-ary Cartesian Product too slow"
}
|
254845
|
<p>I have written some code in python to determine the outcome(including the remaining troops of both sides) of a Risk battle fought until one side is defeated. When using the Numba's njit decorator the code can simulate one battle's outcome in ~ 0.2ms.
This is not fast enough for the application I have in mind. Ideally it would be one to two orders of magnitude faster. Any advice on how to improve performance would be greatly appreciated.</p>
<p>Function Code:</p>
<pre><code>@njit
def _attack_(n_atk,n_def):
n_atk_dies = 0
n_def_dies = 0
while n_atk >0 and n_def>0:
if n_atk>=3:
n_atk_dies = 3
if n_atk==2:
n_atk_dies = 2
if n_atk ==1:
n_atk_dies = 1
if n_def >=2:
n_def_dies = 2
if n_def ==1:
n_def_dies = 1
atk_rolls = -np.sort(-np.random.randint(1,7,n_atk_dies))
def_rolls = -np.sort(-np.random.randint(1,7,n_def_dies))
comp_ind = min(n_def_dies,n_atk_dies)
comp = atk_rolls[:comp_ind]-def_rolls[:comp_ind]
atk_losses =len([1 for i in comp if i<=0])
def_losses = len([1 for i in comp if i>0])
n_atk -= atk_losses
n_def -= def_losses
return [n_atk,n_def]
</code></pre>
<p>Benchmarking Code:</p>
<pre><code>atk_list = list(np.random.randint(1,200,10000))
def_list = list(np.random.randint(1,200,10000))
cProfile.run('list(map(_attack_,atk_list,def_list))',sort='tottime')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:15:55.360",
"Id": "502646",
"Score": "1",
"body": "What application do you have in mind?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:19:40.653",
"Id": "502647",
"Score": "1",
"body": "Reinforcement Learning environment. Don't want the game environment speed to be a limiting factor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:15:47.990",
"Id": "502654",
"Score": "1",
"body": "See [What should I not do?](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:25:37.163",
"Id": "502655",
"Score": "2",
"body": "Will not do this again. I rolled back thinking you had not rolled back."
}
] |
[
{
"body": "<p>I haven't benchmarked any of the following but I suspect that they can help you out. I'd check each alteration separately.</p>\n<p>First, selecting the number of dice (die is singular, dice is plural) as you have is confusing and probably slow.</p>\n<pre><code>n_atk_dice = min(n_atk, 3)\nn_def_dice = min(n_def, 2)\n</code></pre>\n<p>Second, using <code>np.sort</code> is (a) overkill for the problem and (b) probably slow as you need to cross into another library to do it. What do I mean by "overkill"? General sorting algorithms have to work for any length of list. But there are optimal sorting algorithms for any fixed length of list. Pulling up my <a href=\"https://en.wikipedia.org/wiki/The_Art_of_Computer_Programming#Volume_3_%E2%80%93_Sorting_and_Searching\" rel=\"noreferrer\">Art of Computer Programming Volume 3</a>, we can write the following:</p>\n<pre><code>def sort2(l):\n if l[0] < l[1]:\n return l[(1, 0)]\n return l\n\ndef sort3(l):\n if l[0] < l[1]:\n if l[1] < l[2]:\n return l[(2, 1, 0)]\n elif l[0] < l[2]:\n return l[(1, 2, 0)]\n else:\n return l[(1, 0, 2)]\n elif l[1] < l[2]:\n if l[0] < l[2]:\n return l[(2, 0, 1)]\n else:\n return l[(0, 2, 1)]\n else:\n return l\n\nsort = [None, lambda l: l, sort2, sort3]\n...\n atk_rolls = sort[n_atk_dice](np.random.randint(1, 7, n_atk_dice))\n def_rolls = sort[n_def_dice](np.random.randint(1, 7, n_def_dice))\n</code></pre>\n<p>Third, use <code>numpy</code> to count instead of creating a new list to count:</p>\n<pre><code>def_losses = (comp > 0).count_nonzero()\n</code></pre>\n<p>and only iterate over the list once:</p>\n<pre><code>atk_losses = comp_ind - def_losses\n</code></pre>\n<p>Fourth, consider doing a similar trick for comparisons as you did for sorting. Instead of using the fully general numpy comparisons, array subtraction, etc, realize that there are two cases: <code>comp_ind</code> is either 1 or 2. If you write specific code for each case you may get faster code and possibly avoid using numpy altogether.</p>\n<p>Finally, investigate random number generation. This may actually be your chokepoint. See e.g. <a href=\"https://eli.thegreenplace.net/2018/slow-and-fast-methods-for-generating-random-integers-in-python/\" rel=\"noreferrer\">https://eli.thegreenplace.net/2018/slow-and-fast-methods-for-generating-random-integers-in-python/</a>. If you can get an all-base-Python solution (no numpy) with fast random numbers, or generate large batches of random numbers at once, you may get a performance boost.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:01:25.253",
"Id": "502649",
"Score": "0",
"body": "You'll also want to investigate whether views or copies are faster when sorting - `l[(2,1, 0)]` vs `l[[2, 1, 0]]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:11:37.130",
"Id": "502651",
"Score": "0",
"body": "Thank you! I will try all of these changes and report back."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:00:18.073",
"Id": "254853",
"ParentId": "254848",
"Score": "7"
}
},
{
"body": "<p>You play with up to 199 dice per player. So most of the time, the attacker will attack with 3 dice and the defender will attack with 2 dice. As long as that's the case, you could simply pick one of the three possible outcomes (with precalculated probabilities) and apply it. Outline:</p>\n<pre><code>def _attack_(n_atk,n_def):\n while n_atk >= 3 and n_def >= 2:\n # pick random outcome and update the dice numbers\n while n_atk >0 and n_def>0:\n # same as before\n return [n_atk,n_def]\n</code></pre>\n<p>You could even precompute the result distributions for all <span class=\"math-container\">\\$199^2\\$</span> possible inputs and randomly pick the result according to the given input's distribution. Outline:</p>\n<pre><code>def _attack_(n_atk,n_def):\n return random.choices(results[n_atk, n_def], cum_weights=cum_weights[n_atk, n_def])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T16:04:14.730",
"Id": "502760",
"Score": "0",
"body": "As far as I can tell, \"pick random outcome\" for 3 vs 2 would be `x = random.choices([0, 1, 2], cum_weights=[2275, 4886, 7776])`. The defense loses x soldiers, the attackers loses (2-x). It should be many orders of magnitude faster than what OP wrote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T17:32:48.020",
"Id": "502779",
"Score": "0",
"body": "@EricDuminil Yeah, that looks about right. I computed the numbers as well, but already deleted the code. Had a version with just `r = randrange(7776)` and two boundary comparisons instead of `choices`. Did you get the numbers with math somehow, or did you evaluate all 7776 possibilities and counted (that's what I did)? I doubt it'll be \"many orders of magnitude\", but then again, I don't know how Numba is affected by all this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T17:43:36.117",
"Id": "502780",
"Score": "0",
"body": "@superbrain Simple brute-force, because there aren't that many possibilities. I took the liberty to write an [answer](https://codereview.stackexchange.com/a/254915/139491) as a complement to yours. I might have been too optimistic, but I sure hope to see a good improvement since now, only a dict lookup and one single random number are needed, compared to random arrays generation and sorting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T18:00:59.350",
"Id": "502784",
"Score": "0",
"body": "@EricDuminil Made a little [benchmark](https://preview.tinyurl.com/y6f2bv6t) now, my way does look faster but yours is more general. So perhaps the two-loops outline I showed is still a good idea. (hmm, I think I switched attacker/defender when using yours, but for the benchmark it doesn't matter)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T09:40:58.237",
"Id": "502861",
"Score": "1",
"body": "@mcgowan_wmb: Good to know. Do you need every intermediate step e.g. `['(12, 7)', '(12, 5)', '(12, 3)', '(10, 3)', '(8, 3)', '(8, 1)', '(8, 0)', 'attack_wins']`, or just to know if the attack wins?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T12:30:01.040",
"Id": "502877",
"Score": "1",
"body": "@Eric Duminil the only important information is the end state eg (8,0)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T09:33:40.483",
"Id": "503462",
"Score": "0",
"body": "I wrote this [answer](https://codereview.stackexchange.com/a/255211/139491) in order to calculate the matrix and display the probability distribution."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T18:35:29.167",
"Id": "254857",
"ParentId": "254848",
"Score": "8"
}
},
{
"body": "<p>If you profile the code without using <code>njit</code>, you will find that most of the time is consumed in calls to <code>randint</code> and <code>sort</code>:</p>\n<pre><code>atk_rolls = sort[n_atk_dice](np.random.randint(1, 7, n_atk_dice))\ndef_rolls = sort[n_def_dice](np.random.randint(1, 7, n_def_dice))\n</code></pre>\n<p>So, instead of generating and sorting those random numbers for each loop iteration, you could pregenerate them before: saving them on an array with length 200.\n(For the worst case, you will need 200 rows.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:28:54.857",
"Id": "502751",
"Score": "0",
"body": "I'm no sure I understand. `n_atk_dice` is 3 at most, and `n_def_dice` is 2 at most, right? Your `sort` example, which you apparently got from another answer, doesn't make sense with 200 dice, does it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T15:57:07.730",
"Id": "502759",
"Score": "0",
"body": "Also, you cannot sort the arrays more than 3 elements at a time. Let's say you have an army of 200, against one single defender. It makes a huge difference if you roll 199 times 1 followed by one 6 at the end, or if you roll a `6` directly at the beginning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:03:04.790",
"Id": "502891",
"Score": "0",
"body": "@EricDuminil: `n_atk_dice` would be an 3x200 array. And `n_def_dice`would be an 2x200 array. If you have an army of 200 vs one: instead of executing a loop (with at most 200 iterations) you could pregenerate the numbers and have them on an array. So, inside the loop there will not be any call to `randint`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:06:41.847",
"Id": "502892",
"Score": "0",
"body": "The main idea is that it's a lot slower calling `randint` 200 times to generate a number than calling it one time to generate 200 numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:18:30.850",
"Id": "502895",
"Score": "0",
"body": "Did you test your idea, and benchmarked it? It also means that you'll sometimes generate 5*200 random numbers, for a single dice battle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:52:11.923",
"Id": "502899",
"Score": "0",
"body": "@EricDuminil You can also try it:\nimport timeit\nimport numpy as np\nprint(timeit.timeit('for i in range(200): np.random.randint(1, 7, 200)', setup='import numpy as np', number=1000))\nprint(timeit.timeit('np.random.randint(1, 7, 200*200)', setup='import numpy as np', number=1000))\n\n4.7743687999999995\n0.8526632999999997"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T16:04:15.017",
"Id": "502901",
"Score": "0",
"body": "Yes. But how can you use your proposal in order to help the original poster? `for i in range(200)` might not be representative at all because almost no battle will be that long."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T13:14:48.633",
"Id": "254891",
"ParentId": "254848",
"Score": "1"
}
},
{
"body": "<h1>Preprocessing</h1>\n<p>Be sure to read superb_rain's excellent <a href=\"https://codereview.stackexchange.com/a/254857/139491\">answer</a>.</p>\n<p>The following code is meant as a preprocessing. It simply iterates over every single attack & defense configuration, and calculates the cumulative probability that the attacker manages to kill 0, 1 or 2 defense soldiers.</p>\n<p>It is slow, but it's not a problem since it's only supposed to run once and output a probability distribution that you can use in your code.</p>\n<pre><code>from itertools import product\nfrom collections import Counter\n\nD6 = [1, 2, 3, 4, 5, 6]\n\nprobabilities = {}\n\nfor n_atk_dice in range(1, 4):\n for n_def_dice in range(1, 3):\n attacker_kills = Counter()\n for attack in product(D6, repeat=n_atk_dice):\n attack = sorted(attack, reverse=True)\n for defense in product(D6, repeat=n_def_dice):\n defense = sorted(defense, reverse=True)\n result = sum(1 for a,d in zip(attack, defense) if a > d)\n attacker_kills[result] +=1\n probabilities[(n_atk_dice, n_def_dice)] = [\n attacker_kills[0],\n attacker_kills[0] + attacker_kills[1],\n attacker_kills[0] + attacker_kills[1] + attacker_kills[2]\n ]\n\nimport pprint\npprint.pprint(probabilities)\n</code></pre>\n<p><code>probabilities</code> is now:</p>\n<pre><code>{(1, 1): [21, 36, 36],\n (1, 2): [161, 216, 216],\n (2, 1): [91, 216, 216],\n (2, 2): [581, 1001, 1296],\n (3, 1): [441, 1296, 1296],\n (3, 2): [2275, 4886, 7776]}\n</code></pre>\n<p>That's all the information you need, and you won't need to sort any array anymore. You could save the code in a separate script, and simply use this literal definition in your code. You can check the values with other sources (e.g. <a href=\"https://web.stanford.edu/%7Eguertin/risk.notes.html\" rel=\"nofollow noreferrer\">https://web.stanford.edu/~guertin/risk.notes.html</a>).</p>\n<h1>Use</h1>\n<h2>With <code>random.choices</code></h2>\n<p>As an example, for 3 vs 2:</p>\n<pre><code>import random\nrandom.choices([0, 1, 2], cum_weights=probabilities[(3, 2)])\n# => Either [0], [1] or [2]\n</code></pre>\n<p>There will be a 2275/7776 chance that the attack loses 2 soldiers, a (4886 - 2275)/7776 chance that both sides lose 1 soldier, and a (7776-4886)/7776 chance that the defense loses 2 soldiers.</p>\n<p>For 1 vs 2:</p>\n<pre><code>random.choices([0, 1, 2], cum_weights=probabilities[(1, 2)])\n# => [0] or [1]\n</code></pre>\n<p>Since the cumulative weights are <code>[161, 216, 216]</code>, there's 0% chance that the defense loses 2 soldiers. Either the attack loses a soldier (with a 161/216 probability) or the defense loses one (with a 55/216 probability).</p>\n<h2>With <code>random.random()</code></h2>\n<p>You could also define <code>probabilities</code> this way:</p>\n<pre><code>total = sum(attacker_kills.values())\nprobabilities[(n_atk_dice, n_def_dice)] = [\n attacker_kills[0] / total,\n (attacker_kills[0] + attacker_kills[1]) / total\n]\n</code></pre>\n<p>The output becomes:</p>\n<pre><code>{(1, 1): [0.5833333333333334, 1.0],\n (1, 2): [0.7453703703703703, 1.0],\n (2, 1): [0.4212962962962963, 1.0],\n (2, 2): [0.44830246913580246, 0.7723765432098766],\n (3, 1): [0.3402777777777778, 1.0],\n (3, 2): [0.2925668724279835, 0.628343621399177]}\n</code></pre>\n<p>You can then simply get a random number between 0.0 and 0.99999999999 (with <code>random.random()</code>), and compare it to the two values.</p>\n<ul>\n<li>If the random number is smaller than the first number : defense loses no soldier.</li>\n<li>If the random number is between both numbers, defense loses 1 soldier.</li>\n<li>If the random number is larger than the second number : defense loses 2 soldiers.</li>\n</ul>\n<p>If defense loses <code>x</code> soldiers, the attacker loses <code>min(n_atk_dice, n_def_dice) - x</code> soldiers.</p>\n<h1>Markov chains, part 1</h1>\n<p>Just for fun, I tried to use the non-cumulated probabilities to define a <a href=\"https://en.wikipedia.org/wiki/Markov_chain\" rel=\"nofollow noreferrer\">Markov chain</a>:</p>\n<pre><code># pip install PyDTMC\n# see https://pypi.org/project/PyDTMC/\nfrom pydtmc import MarkovChain, plot_graph\n\nN = 30\n\nprobabilities = {\n (1, 1): [0.5833333333333334, 0.4166666666666667, 0.0],\n (1, 2): [0.7453703703703703, 0.25462962962962965, 0.0],\n (2, 1): [0.4212962962962963, 0.5787037037037037, 0.0],\n (2, 2): [0.44830246913580246, 0.32407407407407407, 0.22762345679012347],\n (3, 1): [0.3402777777777778, 0.6597222222222222, 0.0],\n (3, 2): [0.2925668724279835, 0.3357767489711934, 0.37165637860082307]}\n\nstates = [(a, b) for a in range(N) for b in range(N)]\n\n#NOTE: A sparse matrix would be a good idea for large N\np = [[0 for _ in range(N * N + 2)] for _ in range(N * N + 2)]\n\np[-1][-1] = 1.0 # Absorbing state 'defense wins'\np[-2][-2] = 1.0 # Absorbing state: 'attack_wins'\n\ndef state_id(a, b):\n return a * N + b\n\nfor a, b in states:\n i = state_id(a, b)\n if a == 0:\n p[i][-1] = 1.0 # defense wins\n elif b == 0:\n p[i][-2] = 1.0 # attack wins\n else:\n a_dice = min(a, 3)\n b_dice = min(b, 2)\n d = min(a_dice, b_dice)\n p0, p1, p2 = probabilities[(a_dice, b_dice)]\n p[i][state_id(a-d,b)] = p0\n p[i][state_id(a-(d-1),b-1)] = p1\n if d == 2:\n p[i][state_id(a-(d-2),b-2)] = p2\n\nstate_names = [f'{a} vs {b}' for a, b in states] + ['attack_wins', 'defense_wins']\n \nmc = MarkovChain(p, state_names)\n</code></pre>\n<p>The resulting graphs are interesting:</p>\n<pre><code>import matplotlib.pyplot as plt\nplt.rcParams['figure.figsize'] = [15, 10]\nplot_graph(mc, nodes_type=False, dpi=200)\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/MQ7bi.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MQ7bi.jpg\" alt=\"enter image description here\" /></a></p>\n<p><code>mc.absorption_probabilities</code> is a matrix containing the probabilities to win or lose depending on the initial state.</p>\n<p>You can get the probability that the attacker wins for a given start (e.g. 10 vs 7), without any loop:</p>\n<pre><code>mc.absorption_probabilities[0][state_id(10, 7)]\n# 0.7998329909591375\n</code></pre>\n<p>And by iterating over every initial state, it's possible to recreate the matrix presented <a href=\"https://boardgames.stackexchange.com/a/3520/22092\">in this answer</a>:</p>\n<pre><code>import numpy as np\nprob_matrix = np.array([[mc.absorption_probabilities[0][state_id(b,a)]\n for a in range(N)] for b in range(N)])\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/B6AvC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/B6AvC.png\" alt=\"enter image description here\" /></a></p>\n<p>It's also possible to see the intermediate steps during a random battle:</p>\n<pre><code>mc.walk(20, initial_state='12 vs 9')\n</code></pre>\n<p>It outputs:</p>\n<pre><code>['12 vs 7',\n '11 vs 6',\n '10 vs 5',\n '10 vs 3',\n '9 vs 2',\n '8 vs 1',\n '8 vs 0',\n 'attack_wins', ....\n</code></pre>\n<p>See this <a href=\"https://codereview.stackexchange.com/a/255211/139491\">answer</a> for more examples.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T20:14:46.033",
"Id": "502814",
"Score": "0",
"body": "@superbrain: Thanks again for the bug finding. Are the last sentences correct, now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T20:22:23.140",
"Id": "502815",
"Score": "1",
"body": "Yes, looks good now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T22:14:29.450",
"Id": "502927",
"Score": "0",
"body": "@Eric Duminil Could your Markov chain approach be used to compute the exact probabilities of each battle outcome, including remaining troops?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T22:57:26.033",
"Id": "502928",
"Score": "0",
"body": "@mcgowan_wmb: It's the first time I used a Markov chain for a concrete example. As far as I can tell, there should be enough information in `mc` in order to calculate a distribution from each initial_state, yes. I don't know enough about Markov chains or about PyDTMC to know how to implement it, though. It also might take a long time or a lot of memory. There are 200*200 initial states and 400 final states(from `200 vs 0` to `0 vs 200`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T23:27:26.447",
"Id": "502931",
"Score": "1",
"body": "@mcgowan_wmb: Yes, it works. The absorbing states need to be changed (so no \"attack wins\" anymore, but simply \"4 vs 0\") and the code needs to be slightly modified. For N=50, it takes less than a minute and outputs a (99 * 2401) matrix, with the probability distribution of each end state, for each initial state."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T23:29:05.403",
"Id": "502932",
"Score": "1",
"body": "@mcgowan_wmb For example, here are the possible outcomes of '12 vs 14' : ['0 vs 2 : 7.1 %', '0 vs 3 : 6.7 %', '0 vs 4 : 7.2 %', '0 vs 5 : 6.4 %', '0 vs 6 : 6.3 %', '0 vs 7 : 5.1 %', '3 vs 0 : 7.6 %', '4 vs 0 : 7.3 %', '5 vs 0 : 6.4 %', '6 vs 0 : 5.4 %']\nI filtered the ones with > 5%. It's getting late here, I might update the code tomorrow."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T17:41:11.657",
"Id": "254915",
"ParentId": "254848",
"Score": "7"
}
},
{
"body": "<h1>Markov Chains, Part 2</h1>\n<h2>Goal</h2>\n<p>My <a href=\"https://codereview.stackexchange.com/a/254915/139491\">above answer</a> was getting too long. The goal here will be to use a Markov chain to calculate the probability of reaching an absorbing state (end state, e.g. <code>3 vs 0 -> attacker wins</code> or <code>0 vs 2 -> defense wins</code>) from a transient state (initial state, e.g. <code>12 vs 7</code>).</p>\n<h2>Code</h2>\n<p>Here's a slightly modified code:</p>\n<pre><code># pip install PyDTMC\n# see https://pypi.org/project/PyDTMC/\nfrom pydtmc import MarkovChain\n\nN = 30\n\nprobabilities = {\n (1, 1): [0.5833333333333334, 0.4166666666666667, 0.0],\n (1, 2): [0.7453703703703703, 0.25462962962962965, 0.0],\n (2, 1): [0.4212962962962963, 0.5787037037037037, 0.0],\n (2, 2): [0.44830246913580246, 0.32407407407407407, 0.22762345679012347],\n (3, 1): [0.3402777777777778, 0.6597222222222222, 0.0],\n (3, 2): [0.2925668724279835, 0.3357767489711934, 0.37165637860082307]}\n\nstates = [(a, d) for a in range(N) for d in range(N)]\n\n#NOTE: A sparse matrix would be a good idea for large N\np = [[0 for _ in range(N * N)] for _ in range(N * N)]\n\ndef state_id(a, d):\n return a * N + d\n\ndef transient_state_id(a, d):\n return (a - 1) * (N - 1) + (d - 1)\n\nfor a, d in states:\n i = state_id(a, d)\n if a == 0 or d == 0:\n p[i][i] = 1.0 # someone wins -> absorbing state\n else:\n a_dice = min(a, 3)\n d_dice = min(d, 2)\n m = min(a_dice, d_dice) # how many dice are compared\n p0, p1, p2 = probabilities[(a_dice, d_dice)]\n p[i][state_id(a - m, d)] = p0\n p[i][state_id(a - m + 1, d - 1)] = p1\n if m == 2:\n p[i][state_id(a - m + 2, d - 2)] = p2\n\nstate_names = [f'{a}vs{d}' for a, d in states]\n \nmc = MarkovChain(p, state_names)\n</code></pre>\n<h2>Probabilities</h2>\n<p><code>mc.absorption_probabilities</code> is the matrix with the desired information. It has <code>2 * N - 1</code> rows (1 for each end state) and <code>(N - 1)**2</code> columns (1 for each initial state).</p>\n<p>For example, with <code>N=30</code>, the matrix is <code>(59, 841)</code>. For <code>N=199</code>, the shape would be <code>(397, 39204)</code>. I'm not sure how long it would take to generate this matrix, though.</p>\n<p>The matrix could be saved to a file once it is generated:</p>\n<pre><code>import numpy as np\nwith open(f'risk_markov_{N}.npy', 'wb') as f:\n np.save(f, mc.transient_states)\n np.save(f, mc.absorbing_states)\n np.save(f, mc.absorption_probabilities)\n\n# with open(f'risk_markov_{N}.npy', 'rb') as f:\n # print(np.load(f))\n # print(np.load(f))\n # print(np.load(f))\n</code></pre>\n<h2>Probability distribution</h2>\n<p>Here's the code to get the probability distribution of <code>14 vs 5</code>:</p>\n<pre><code>ps = mc.absorption_probabilities[:,transient_state_id(14, 5)]\n# array([0. , 0.04169685, 0.08077598, 0.07195455, 0.07046567,\n# 0.05591131, 0.04746686, 0.03114066, 0.02060625, 0.00910449,\n# 0.00328452, 0. , 0. ....\n</code></pre>\n<p><code>ps</code> is an array with <code>2 * N - 1</code> elements.</p>\n<p>It's possible to select states with more than 5% probability:</p>\n<pre><code>['%s : %.1f %%' % (s, p*100) for s,p in zip(mc.absorbing_states, ps) if p > 0.05]\n</code></pre>\n<p>It returns:</p>\n<pre><code>['7vs0 : 6.1 %',\n '8vs0 : 7.6 %',\n '9vs0 : 10.5 %',\n '10vs0 : 12.2 %',\n '11vs0 : 14.5 %',\n '12vs0 : 14.7 %',\n '13vs0 : 12.4 %',\n '14vs0 : 9'.1 %']\n</code></pre>\n<h2>Diagrams</h2>\n<pre><code># 3 vs 5 -> -2\ndef get_diff(vs):\n a, d = vs.split('vs')\n return int(a.strip()) - int(d.strip()) \n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nplt.rcParams['figure.figsize'] = [15, 10]\n\nattack, defense = 12, 7\nps = mc.absorption_probabilities[:,transient_state_id(attack, defense)]\ndf = pd.DataFrame(ps * 100, mc.absorbing_states, columns=['p'])\ndf['difference'] = df.index.map(get_diff)\ndf = df.sort_values(by='difference', ascending=False)\ndf = df[df.p > 0]\ndf['color'] = df.difference.map(lambda d: 'green' if d > 0 else 'red')\nwin = df[df.difference > 0].p.sum()\ndf.p.plot(kind='bar',\n color=df.color,\n title = 'Initial state : %d vs %d (%.1f %% win)' % (attack, defense, win))\nplt.ylabel('Probability [%]')\nplt.xlabel('End state')\nplt.show()\n</code></pre>\n<p>It displays, for 12 vs 7:</p>\n<p><a href=\"https://i.stack.imgur.com/5UFFv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5UFFv.png\" alt=\"enter image description here\" /></a></p>\n<p>or for 9 vs 14:</p>\n<p><a href=\"https://i.stack.imgur.com/5Ek6O.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5Ek6O.png\" alt=\"enter image description here\" /></a></p>\n<p>Just for fun, it's also possible to plot them all in a large plot:</p>\n<pre><code>import numpy as np\nimport matplotlib.pyplot as plt\n\nn = 10\nfig, subplots = plt.subplots(n, n, sharex='col', sharey='row')\nfor (i, j), subplot in np.ndenumerate(subplots):\n attack, defense = i + 1, j + 1\n ps = mc.absorption_probabilities[:,transient_state_id(attack, defense)]\n df = pd.DataFrame(ps * 100, mc.absorbing_states, columns=['p'])\n df['difference'] = df.index.map(get_diff)\n df = df.sort_values(by='difference', ascending=False)\n df = df[df.p > 0]\n df['color'] = df.difference.map(lambda d: 'green' if d > 0 else 'red')\n win = df[df.difference > 0].p.sum()\n df.p.plot(kind='bar', color=df.color,\n ax=subplots[i,j]\n )\n\nfig.suptitle("Risk: Attack vs Defense")\nplt.show()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/JvAwz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JvAwz.png\" alt=\"enter image description here\" /></a></p>\n<p>Generating the matrix for <code>N=100</code> took half an hour, required ~10GB of RAM and wrote a 16 MB npy binary file.</p>\n<p><a href=\"https://i.stack.imgur.com/2ploo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2ploo.png\" alt=\"enter image description here\" /></a></p>\n<p>The script crashed for <code>N=199</code> on my laptop because no memory was left. I guess that ~64GB should be enough.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-25T09:27:36.707",
"Id": "255211",
"ParentId": "254848",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "254857",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T16:41:01.453",
"Id": "254848",
"Score": "10",
"Tags": [
"python",
"performance",
"numba"
],
"Title": "Fast Risk Battle Simulator"
}
|
254848
|
<p>As an exercise, I put together a postfix calculator using modern Fortran. Language apart, I am interested in knowing your take on the algorithm. As far as I remember from my freshman year (chemistry - long ago), the problem has a standard solution in C, which I imagine is optimal in some sense. However, I did not look it up, and wrote something that is probably different in some respects. The program runs and passes the tests.</p>
<p>I am interested in knowing whether the present solution is acceptable, or if it has any major hidden flaws / inefficiencies. For folks not familiar with the simple syntax of modern Fortran, I suggest the following <a href="https://fortran-lang.org/learn/quickstart" rel="nofollow noreferrer">quick modern Fortran tutorial</a>.</p>
<p>Thanks!</p>
<pre class="lang-fortran prettyprint-override"><code>module mod_postfix
implicit none
private
integer, parameter :: TOKEN_MAX_LEN = 50
public :: EvalPostfix
contains
real(kind(1d0)) function EvalPostfix( CmdStrn ) result(res)
character(len=*), intent(in) :: CmdStrn
integer :: iToken, nTokens, shift
character(len=:) , allocatable :: Token
character(len=TOKEN_MAX_LEN), allocatable :: stack(:)
nTokens = GetNTokens(CmdStrn)
allocate(stack(nTokens))
do iToken = 1, nTokens
call GetToken(CmdStrn,iToken,Token)
stack(iToken) = Token
enddo
shift=0
call simplify_stack(nTokens,Stack,shift)
read(Stack(nTokens),*)res
end function EvalPostfix
recursive subroutine simplify_stack(n,Stack,shift)
integer , intent(in) :: n
character(len=TOKEN_MAX_LEN), intent(inout) :: Stack(:)
integer , intent(inout) :: shift
character(len=:), allocatable :: sOp
integer :: i
real(kind(1d0)) :: v1, v2, res
logical :: IsBinary, IsUnary, IsNonary, IsOperator
if(n==0)return
sOp = trim(Stack(n))
!.. Case Binary Operators
IsBinary = index( "+ - * / max min mod **", sOp ) > 0
IsUnary = index( " sin cos tan asin acos atan exp log int sqrt abs", sOp ) > 0
IsNonary = index( " random_number PI", sOp ) > 0
IsOperator = IsBinary .or. IsUnary .or. IsNonary
if( ( .not. IsOperator ) .and. n == shift + 1 )return
call simplify_stack(n-1,stack,shift)
if( IsBinary )then
read(Stack(n-1),*)v2
read(Stack(n-2),*)v1
if( sOp == "+" ) res = v1+v2
if( sOp == "-" ) res = v1-v2
if( sOp == "*" ) res = v1*v2
if( sOp == "/" ) res = v1/v2
if( sOp == "max" ) res = max(v1,v2)
if( sOp == "min" ) res = min(v1,v2)
if( sOp == "mod" ) res = mod(v1,v2)
if( sOp == "**" ) res = v1**v2
write(Stack(n),"(e24.16)")res
shift=shift+2
do i=n-3,1,-1
Stack(i+2)=Stack(i)
enddo
elseif( IsUnary )then
read(Stack(n-1),*)v1
if( sOp == "sin" ) res = sin (v1)
if( sOp == "cos" ) res = cos (v1)
if( sOp == "tan" ) res = tan (v1)
if( sOp == "asin") res = asin(v1)
if( sOp == "acos") res = acos(v1)
if( sOp == "atan") res = atan(v1)
if( sOp == "exp" ) res = exp (v1)
if( sOp == "log" ) res = log (v1)
if( sOp == "sqrt") res = sqrt(v1)
if( sOp == "abs" ) res = abs (v1)
if( sOp == "int" ) res = dble(int(v1))
write(Stack(n),"(e24.16)")res
shift=shift+1
do i=n-2,1,-1
Stack(i+1)=Stack(i)
enddo
elseif( IsNonary )then
if( sOp == "random_number")call random_number(res)
if( sOp == "PI" )res=4.d0*atan(1.d0)
write(Stack(n),"(e24.16)")res
if(n == shift + 1)return
call simplify_stack(n-1,stack,shift)
end if
end subroutine simplify_stack
!> Counts the number of tokens
integer function GetNTokens( strn, separator_list_ ) result( n )
implicit none
character(len=*) , intent(in) :: strn
character(len=*), optional, intent(in) :: separator_list_
!
character , parameter :: SEPARATOR_LIST_DEFAULT = " "
character(len=:), allocatable :: separator_list
integer :: i,j
n=0
if(len_trim( strn ) == 0)return
if(present(separator_list_))then
allocate(separator_list,source=separator_list_)
else
allocate(separator_list,source=SEPARATOR_LIST_DEFAULT)
endif
i=1
do
j=verify(strn(i:),separator_list)
if(j<=0)exit
n=n+1
j=i-1+j
i=scan(strn(j:),separator_list)
if(i<=0)exit
i=j-1+i
if(i>len(strn))exit
enddo
if(allocated(separator_list))deallocate(separator_list)
end function GetNTokens
subroutine GetToken( strn, iToken, token, separator_list_ )
implicit none
character(len=*), intent(in) :: strn
integer , intent(in) :: iToken
character(len=:), allocatable, intent(out):: token
character(len=*), optional , intent(in) :: separator_list_
!
character , parameter :: SEPARATOR_LIST_DEFAULT = " "
character(len=:), allocatable :: separator_list
integer :: i,j,n
if(present(separator_list_))then
allocate(separator_list,source=separator_list_)
else
allocate(separator_list,source=SEPARATOR_LIST_DEFAULT)
endif
if(iToken<1)return
if(iToken>GetNTokens(strn,separator_list))return
if(allocated(token))deallocate(token)
i=1
n=0
do
j=verify(strn(i:),separator_list)
if(j<=0)exit
n=n+1
j=i-1+j
i=scan(strn(j:),separator_list)
if(i<=0)then
i=len_trim(strn)+1
else
i=j-1+i
endif
if(n==iToken)then
allocate(token,source=strn(j:i-1))
exit
endif
enddo
end subroutine GetToken
end module Mod_Postfix
program TestPostfixCalculator
use mod_postfix
implicit none
real(kind(1d0)) , parameter :: THRESHOLD = 1.d-10
real(kind(1d0)) :: res
character(len=:), allocatable :: sPostfix
call assert("+" , abs( EvalPostfix(" 3 4 +") - 7 ) < THRESHOLD )
call assert("-" , abs( EvalPostfix(" 3 4 -") + 1 ) < THRESHOLD )
call assert("*" , abs( EvalPostfix(" 3 4 *") - 12 ) < THRESHOLD )
call assert("/" , abs( EvalPostfix(" 3 4 /") - 0.75 ) < THRESHOLD )
call assert("max", abs( EvalPostfix(" 3 4 max") - 4 ) < THRESHOLD )
call assert("min", abs( EvalPostfix(" 3 4 min") - 3 ) < THRESHOLD )
call assert("mod", abs( EvalPostfix("13 5 mod") - 3 ) < THRESHOLD )
call assert("**" , abs( EvalPostfix(" 2 5 **" ) - 32 ) < THRESHOLD )
call assert("cos", abs( EvalPostfix(" PI 3 / cos" ) - 0.5 ) < THRESHOLD )
res = sqrt( (log(10.d0)-atan(2.d0))/max(cos(6.d0),exp(3.d0)) )
sPostfix ="10 log 2 atan - 6 cos 3 exp max / sqrt"
call assert("expression1", abs( EvalPostfix(sPostfix) - res ) < THRESHOLD )
!.. etc. etc.
contains
subroutine assert(msg,cond)
use, intrinsic :: iso_fortran_env, only : OUTPUT_UNIT
character(len=*), intent(in) :: msg
logical , intent(in) :: cond
write(OUTPUT_UNIT,"(a)",advance="no") "["//msg//"] "
if( cond )then
write(OUTPUT_UNIT,"(a)") "passed"
else
write(OUTPUT_UNIT,"(a)") "FAILED"
endif
end subroutine assert
end program TestPostfixCalculator
</code></pre>
|
[] |
[
{
"body": "<p><strong>Things to improve in the current solution:</strong></p>\n<ol>\n<li><p>It is always better to use an <code>integer, parameter</code> for the desired kinds of types. You can still set <code>integer, parameter :: wp = kind(1.d0)</code> to achieve the same result as currently, but you can change it in one place, if you want to.</p>\n</li>\n<li><p>Some reused functionality should be encapsulated into functions. (For example the string to number conversion and back.)</p>\n</li>\n<li><p><code>intent(out), allocatable </code> dummy arguments are automatically deallocated. <code>if(allocated(token)) deallocate(token)</code> can be ommited.</p>\n</li>\n<li><p>The check for specific operators is exclusive. (If it is a <code>"+"</code> you don't have to check anymore if it is a <code>"-"</code> etc.) It should either become <code>if - else if - else if ...</code> or a <code>select case</code> statement. It informs human readers of the code, that the cases are excluding each other. Enumerated <code>if</code>s should be IMHO only used if you explicitly want to fall through all possibilities and if the order of the ifs matter.\nAs in</p>\n</li>\n</ol>\n<pre><code>if (use_mpi .and. .not. mpi_initialized) call MPI_Init(ierr)\n! fancy library relies on MPI\nif (use_fancy_library_to_speedup_fancy_algorithm) call init_fancy_library()\n</code></pre>\n<p>Possibly increased performance is a nice addition.</p>\n<ol start=\"5\">\n<li>One <code>implicit none</code> per program and per module scope is sufficient.¹ If your compiler supports it <code>implicit none(type, external)</code> is preferred. If you forget to import names of subroutines it will fail at compile instead of linking time, which speeds up the trial-and-error loop in larger projects.</li>\n</ol>\n<p><strong>Architecture</strong>:</p>\n<ol>\n<li><p>Using a string stack makes the code unnecessarily complicated and deteriorates precision (and possibly performance), because you convert back and forth between floating points and their string representaiton.. Basically only a <code>real(wp)</code> array of <code>MAX_ARITY</code> size is required as Stack.</p>\n</li>\n<li><p>The <code>GetToken</code> routine is a "Schlemiel the Painter's Algorithm". For the n-th token you have to loop through all previous tokens and you do this n times.\nIt would be probably better to return an array of tokens, or to keep track of the current position in the string. This requires a bit more memory than in the current solution, but this memory demand only increases linearly with the length of the expression.</p>\n</li>\n<li><p>It would be perhaps better to separate parsing from evaluating. The parsing could return a function pointer which is then evaluated on the operands.</p>\n</li>\n<li><p>At the moment you test if something is an operator. If it is not, you assume that it can be converted to a real number. If an invalid operator is passed, the error will be something like\n<code>Fortran runtime error: Bad real number in item 1 of list input</code> depending on the IO functionality of the specific runtime library of your compiler.\nI would rather try to convert anything to a number and anything that cannot be converted might be a valid operator. Then you can check if that operator exists or not.</p>\n</li>\n<li><p>If the operators are not operating on individual arguments, but directly on the stack a lot of special casing code can go away.\nThe <code>-</code> operator takes two values and appends one (The operation might look like this: <code>[5, 1, 3] -> [5, 2]</code>),\nthe <code>PI</code> operator just appends one value, and so on.\nThis makes the generalization to arbitrary aryness very easy.\nOne can e.g. implement a <code>mean</code> function that consumes the whole stack and appends one element. If one looks to functional languages\n<a href=\"https://codereview.stackexchange.com/questions/99150/reverse-polish-notation-in-f\">here</a> that is the recommended way to go there as well.</p>\n</li>\n</ol>\n<p>Since I had a fixed stack class at hand the actual implementation became quite easy. (I did not implement all operators, but this should be straightforward.)</p>\n<pre><code>module constants_mod\n implicit none(type, external)\n public\n integer, parameter :: wp = kind(1.d0)\n real(wp), parameter :: PI = 4._wp * atan(1._wp)\nend module\n\n\nmodule stack_mod\n use constants_mod, only: wp\n implicit none(type, external)\n private\n public :: Stack_t\n\n integer, parameter :: STACK_SIZE = 50\n\n type :: Stack_t\n private\n real(wp) :: values(STACK_SIZE)\n integer :: pos = 0\n contains\n private\n procedure, public :: push_back\n procedure, public :: pop\n procedure, public :: size => my_size\n procedure, public :: capacity\n end type\n\ncontains\n\n !> @brief\n !> Push value onto stack. Aborts if stack size is exceeded.\n subroutine push_back(this, x)\n class(Stack_t), intent(inout) :: this\n real(wp), intent(in) :: x\n if (this%pos == size(this%values)) error stop 'push back would exceed stack size.'\n this%pos = this%pos + 1\n this%values(this%pos) = x\n end subroutine\n\n\n !> @brief\n !> Pop value from stack. Aborts if stack is empty.\n real(wp) function pop(this)\n class(Stack_t), intent(inout) :: this\n if (this%pos == 0) error stop 'It is not possible to pop from empty stack.'\n pop = this%values(this%pos)\n this%pos = this%pos - 1\n end function\n\n !> @brief\n !> Return current size of stack.\n integer elemental function my_size(this)\n class(Stack_t), intent(in) :: this\n my_size = this%pos\n end function\n\n !> @brief\n !> Return the overall capacity (i.e. upper bound for size).\n integer elemental function capacity(this)\n class(Stack_t), intent(in) :: this\n capacity = size(this%values)\n end function\nend module\n\n\nmodule reverse_polish_calculator_mod\n use, intrinsic :: iso_fortran_env\n use, intrinsic :: ieee_arithmetic\n use constants_mod, only: wp, PI\n use stack_mod, only: Stack_t\n implicit none(type, external)\n\n private\n public :: RPN_eval\n\n type :: Token_t\n character(len=:), allocatable :: str\n end type\n\ncontains\n\n !> @brief\n !> Return true if `str` can be converted to floating point number.\n !>\n !> @details\n !> if true, the converted number is written to `x`.\n !> if false, `x` is set to NaN.\n logical function is_number(str, x)\n character(*), intent(in) :: str\n real(wp), intent(out) :: x\n integer :: ierr\n read(str, *, iostat=ierr) x\n is_number = ierr == 0\n if (.not. is_number) then\n x = ieee_value(x, ieee_quiet_nan)\n end if\n end function\n\n\n !> @brief\n !> Split string by whitespace.\n pure function tokenize(expr) result(res)\n character(*), intent(in) :: expr\n type(Token_t), allocatable :: res(:)\n character(len=1), parameter :: delimiter = ' '\n type(Token_t), allocatable :: tmp(:)\n\n integer :: n, low, high\n\n allocate(tmp(len(expr) / 2 + 1))\n low = 1; n = 0\n do while (low <= len(expr))\n do while (expr(low : low) == delimiter)\n low = low + 1\n if (low > len(expr)) exit\n end do\n if (low > len(expr)) exit\n\n high = low\n if (high < len(expr)) then\n do while (expr(high + 1 : high + 1) /= delimiter)\n high = high + 1\n if (high == len(expr)) exit\n end do\n end if\n n = n + 1\n tmp(n)%str = expr(low : high)\n low = high + 2\n end do\n res = tmp(: n)\n end function\n\n !> @brief\n !> Evaluate a string expression in reverse polish notation.\n function RPN_eval(expr) result(res)\n character(*), intent(in) :: expr\n real(wp) :: res\n\n type(Token_t), allocatable :: tokens(:)\n type(Stack_t) :: stack\n real(wp) :: x\n real(wp) :: A, B\n integer :: i\n\n tokens = tokenize(expr)\n do i = 1, size(tokens)\n associate(token => tokens(i)%str)\n if (is_number(token, x)) then\n call stack%push_back(x)\n else\n select case(token)\n ! 0-ary operators\n case("PI")\n call stack%push_back(PI)\n case("random_number")\n call random_number(A)\n call stack%push_back(A)\n ! 1-ary operators\n case("exp")\n A = stack%pop()\n call stack%push_back(exp(A))\n ! 2-ary operators\n case("+")\n A = stack%pop()\n B = stack%pop()\n call stack%push_back(A + B)\n case("-")\n A = stack%pop()\n B = stack%pop()\n call stack%push_back(A - B)\n case("*")\n A = stack%pop()\n B = stack%pop()\n call stack%push_back(A * B)\n case("/")\n A = stack%pop()\n B = stack%pop()\n call stack%push_back(A / B)\n ! any-ary operators\n case("mean")\n block\n integer :: N\n real(wp) :: acc\n N = 0; acc = 0._wp\n do while (stack%size() > 0)\n acc = stack%pop() + acc\n N = N + 1\n end do\n call stack%push_back(acc / real(N, wp))\n end block\n case default\n error stop "Operator "//token//" not known"\n end select\n end if\n end associate\n end do\n ! Here you could force that the Stack has to be reduced\n ! to one number using stack%size == 1.\n res = stack%pop()\n end function\nend module\n\n\nprogram reverse_polish_calculator_prog\n use reverse_polish_calculator_mod, only: RPN_eval\n implicit none(type, external)\n\n\n write(*, *) RPN_eval("7.2 0.8 +")\n write(*, *) RPN_eval("7.2 0.8 + 2 +")\n write(*, *) RPN_eval("PI PI - PI")\n write(*, *) RPN_eval("2 4 mean")\n\nend program\n</code></pre>\n<p>Additional Notes:</p>\n<ol>\n<li>If the stack does not have a fixed capacity, but reallocates and grows upon <code>push_back</code> (like C++'s <code>std::vector::push_back</code>).\nThis implementation works on arbitrary large expressions.\nIf the <code>tokenize</code> function does not return an array of tokens, but becomes something like a generator i.e. returns the next token upon request, the memory demand of the tokenizing step does not grow with the expression size.</li>\n<li>It is tempting to write e.g. for the <code>-</code> operator:</li>\n</ol>\n<pre><code>call stack%push_back(stack%pop() - stack%pop())\n</code></pre>\n<p>This is unfortunately not valid. Which I had to clarify for myself <a href=\"https://stackoverflow.com/questions/65869750/function-evaluation-conflicting-with-other-effects-in-statement/65870298#65870298\">here</a>.</p>\n<hr />\n<p>¹ Except if you are writing interfaces. There you have to repeat the <code>implicit none</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T19:30:50.947",
"Id": "503312",
"Score": "0",
"body": "Thanks for looking into it. Fair points. The ```getToken``` is indeed awkward, since the program iterates over all of them anyway. I should have payed more attention to that item, rather than recycle the code. Returning an array of tokens is certainly the best option there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T13:13:09.520",
"Id": "503382",
"Score": "1",
"body": "Thanks for reviving the Fortran Code Review. ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T12:00:17.323",
"Id": "503565",
"Score": "1",
"body": "I have appended an answer to your code"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-23T16:56:27.530",
"Id": "255144",
"ParentId": "254849",
"Score": "1"
}
},
{
"body": "<p>Thank you for the code alternative.\nI like many of the changes you did: The non-quadratic tokenizer, of course, as well as the use of a stack of the minimum size needed, and the <code>is_number</code> check.</p>\n<p>I am less fond of the allocation of a temporary array to the possible maximum number of tokens, though, even if the data in the unused elements is not allocated. As I see it, the function you wrote splits naturally in a token counter and in a token reader. Once the number of tokens is known, it is easy to fetch them from the input expression with the index function.\nTherefore, I would rather replace the tokenize function with something like the following</p>\n<pre class=\"lang-fortran prettyprint-override\"><code> !> @brief\n !> Count tokens in string.\n pure integer function countTokens(expr,delimiter) result(nTokens)\n character(*), intent(in) :: expr\n character(*), intent(in) :: delimiter\n !\n integer :: low, high\n\n low = 1; nTokens = 0\n do while (low <= len(expr))\n do while (expr(low : low) == delimiter)\n low = low + 1\n if (low > len(expr)) exit\n end do\n if (low > len(expr)) exit\n high = low\n if (high < len(expr)) then\n do while (expr(high + 1 : high + 1) /= delimiter)\n high = high + 1\n if (high == len(expr)) exit\n end do\n end if\n nTokens = nTokens + 1\n low = high + 2\n end do\n end function countTokens\n\n !> @brief\n !> Split string by whitespace.\n pure function tokenize(expr) result(res)\n character(*), intent(in) :: expr\n type(Token_t), allocatable :: res(:)\n !\n character(len=1), parameter :: delimiter = ' '\n integer , parameter :: TOKEN_MAX_LEN = 50\n !\n character(len=TOKEN_MAX_LEN):: sBuf\n integer :: iToken, nTokens, low\n\n nTokens = countTokens(expr,delimiter)\n allocate(res(nTokens))\n low=1\n do iToken = 1, nTokens\n read(expr(low:),*) sBuf\n res(iToken)%str = trim(adjustl(sBuf))\n if(iToken == nTokens)exit\n low = low + index(expr(low:),res(iToken)%str) - 1\n low = low + index(expr(low:)," ")\n enddo\n\n end function\n</code></pre>\n<p>I am on the fence regarding the <code>select case</code> statement. I originally used this same algorithm, but I did not like (and still do not like) repeating the boilerplate code <code>A = stack%pop(); B = stack%pop()</code> over and over. The only possible advantage I can see is if the compiler implements a binary search across the listed cases (?), which would be best for a large number of operators, of course. If, however, it goes linearly through the cases, then the gain over a list of ifs is just of about a factor of two.</p>\n<p>I understand also the appeal of operators with arbitrary arity. I think a possible approach to avoid too much boilerplate would be to separately specify the kind (fixed number, number specified at run time, or to be determined from the stack) and, if applicable, the value of this operator attribute, and on this basis popping as many operands as needed.</p>\n<p>Btw, as a MOLCAS contributor (if I understand correctly from your Chemistry stackExchange posts) you may know Jeppe Olsen, who used to be a MOLCAS contributor too. We are building a molecular photoionization code together, now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T12:32:27.170",
"Id": "503566",
"Score": "1",
"body": "> Btw, as a MOLCAS contributor (if I understand correctly from your Chemistry stackExchange posts) you may know Jeppe Olsen, who used to be a MOLCAS contributor too. We are building a molecular photoionization code together, now.\n\nThat's cool. I am in Ali Alavi's group in Stuttgart and at the moment developing GAS in FCIQMC (which Jeppe Olsen did in LUCIA for conventional CI calculation).\n\nThe world is small ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T12:38:29.013",
"Id": "503567",
"Score": "1",
"body": "> I am on the fence regarding the select case statement.\n\nMy reasoning is not because of performance but to be more self-documenting. Lots of `if`s should IMHO only be used, if you explicitly want to fallthrough all possibilities and if the order of the `if`s matter. Possibly increased performance is just a plus."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T15:00:02.380",
"Id": "503589",
"Score": "0",
"body": "Small indeed. Lucia is a very nice tool, and Jeppe has done a tremendous job in extending it for our purposes. We use Lucia to compute the CI parent ions and their properties. We then cloak the ions with a hybrid GTOs+numerical functions for the photoelectron, and go from there. Soon we'll get to the multichannel TDSE, for which I plan to use coarrays (I used PETSc for the propagator in some past projects, but I have lost faith, after seeing that, in a single node, multithreaded MKL runs five or six times faster)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-24T21:34:15.127",
"Id": "255189",
"ParentId": "254849",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "255144",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T16:41:55.540",
"Id": "254849",
"Score": "2",
"Tags": [
"parsing",
"reinventing-the-wheel",
"calculator",
"math-expression-eval",
"fortran"
],
"Title": "A postfix (a.k.a. Reverse-Polish Notation - RPN) calculator"
}
|
254849
|
<p>I have been developing a software driver for the internal a/d converter on <a href="https://www.xilinx.com/support/documentation/data_sheets/ds190-Zynq-7000-Overview.pdf" rel="nofollow noreferrer">this platform</a>. The a/d converter peripheral is described in following <a href="https://www.xilinx.com/support/documentation/user_guides/ug480_7Series_XADC.pdf" rel="nofollow noreferrer">document</a>. The driver is written in C++ and is build upon existing driver which has been developed by the platform manufacturer in C language. The reason why I have decided to wrap existing driver into the C++ is that I would like to achieve a state where this driver constitutes a consistent hardware abstraction layer with my other drivers already written in C++.
During driver development I have had in my mind below given hardware schematic which describes how the internal a/d converter will be used in my application</p>
<p><a href="https://i.stack.imgur.com/hRGCP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hRGCP.jpg" alt="enter image description here" /></a></p>
<p>As far as the driver design I have chosen following approach:</p>
<ul>
<li><p>I have decided to encapsulate the driver into a class <code>AdcInt</code> which offers an interface for
the a/d converter usage from the higher software layer. The intended usage of the driver is
following. After instantiation of the driver the <code>initialize</code> method is called. The <code>update</code> method
has to be called in periodic manner (e.g. from RTOS task) with appropriate period in respect to
the sampled physical quantities. As soon as the isReady method returns true the client code can start
reading a/d samples via <code>getValue</code> method or monitor alarm occurens via <code>isAlarmActive</code> method</p>
</li>
<li><p>in respect to the fact that the a/d peripheral can be configured in rich manner I have decided to
define special class <code>AdcIntCfgManager</code> which manages this configuration i.e. it works upon the
<code>AdcIntCfg</code> struct (which is filled by the higher layer programmer) and offers set of methods
for retrieving the configuration data</p>
</li>
</ul>
<p><strong>AdcInt.h</strong></p>
<pre><code>#include "AdcIntCfgManager.h"
#include "xsysmon.h"
#include <cstdint>
class AdcInt
{
public:
enum class Input
{
kChannel00,
kChannel01,
kChannel02,
kChannel03,
kChannel04,
kChannel05,
kChannel06,
kChannel07,
kChannel08,
kChannel09,
kChannel10,
kChannel11,
kChannel12,
kNoChannels,
kOnChipTemp,
kVccInt,
kVccAux,
kVrefP,
kVrefN,
kVBram,
kVccPInt,
kVccPAux,
kVccOddr,
kNoInputs
};
AdcInt(AdcIntCfgManager *_configuration_manager, uint16_t _xadc_device_id,
uint8_t _xadc_interrupt_id);
void initialize();
void update();
bool isReady();
bool getValue(Input input, float &var);
bool isAlarmActive(AdcIntCfgManager::Alarm alarm);
void handle_interrupt();
private:
class AnalogInput
{
public:
AnalogInput();
void initialize(XSysMon *_xadc_driver, uint8_t _addr, bool _enable,
float _norm);
bool isEnabled();
float getValue();
bool isReady();
void notify();
private:
uint8_t addr;
uint16_t value;
float norm;
bool enabled;
bool ready;
AdcIntCfgManager::ChannelType type;
XSysMon *xadc_driver;
};
class Sensor
{
public:
Sensor();
void initialize(XSysMon *_xadc_driver, uint8_t _addr, bool _enable,
AdcIntCfgManager::OnChipSensorType _type);
bool isEnabled();
float getValue();
bool isReady();
void notify();
private:
uint8_t addr;
AdcIntCfgManager::OnChipSensorType type;
uint16_t value;
bool enabled;
bool ready;
XSysMon *xadc_driver;
};
class Alarm
{
public:
Alarm();
void initialize(bool _enable, uint32_t _activate_mask,
uint32_t _deactivate_mask);
bool isEnabled();
bool isActive();
void notify(uint32_t status);
private:
uint32_t activate_mask;
uint32_t deactivate_mask;
bool enabled;
bool active;
};
class ChannelAddressMonitor
{
public:
ChannelAddressMonitor();
void refreshAddress();
uint8_t getChannelAddress();
private:
uint8_t channel_address;
};
static const uint32_t NON_EXISTING_ALARM_ACTIVE_MASK = 0x00000000;
static const uint32_t NON_EXISTING_ALARM_DEACTIVE_MASK = 0x00000000;
static const uint64_t sensor_masks[static_cast<uint8_t>(
AdcIntCfgManager::OnChipSensor::kNoOnChipSensors)];
static const uint16_t calibration_masks[static_cast<uint8_t>(
AdcIntCfgManager::Calibration::kNoCalibrations)];
static const uint32_t
alarm_masks[static_cast<uint8_t>(AdcIntCfgManager::Alarm::kNoAlarms)];
static const uint16_t threshold_masks[static_cast<uint8_t>(
AdcIntCfgManager::AlarmThresholdName::kNoAlarmThresholdNames)];
static const uint8_t sensors_address[static_cast<uint8_t>(
AdcIntCfgManager::OnChipSensor::kNoOnChipSensors)];
static const uint32_t alarm_activate_masks[static_cast<uint8_t>(
AdcIntCfgManager::Alarm::kNoAlarms)];
static const uint32_t alarm_deactivate_masks[static_cast<uint8_t>(
AdcIntCfgManager::Alarm::kNoAlarms)];
static bool isEndOfSequenceInterrupt(uint32_t status);
static bool isAlarmInterrupt(uint32_t status);
static float temperatureRawToC(uint16_t raw_temp);
static uint16_t temperatureCToRaw(float temp);
static float voltageRawToV(uint16_t raw_voltage);
static uint16_t voltageVToRaw(float voltage);
AdcIntCfgManager *configuration_manager;
AnalogInput analog_inputs[static_cast<uint8_t>(
AdcIntCfgManager::Channel::kNoChannels)];
Sensor sensors[static_cast<uint8_t>(
AdcIntCfgManager::OnChipSensor::kNoOnChipSensors)];
Alarm alarms[static_cast<uint8_t>(AdcIntCfgManager::Alarm::kNoAlarms)];
ChannelAddressMonitor channel_address_monitor;
XSysMon xadc_driver;
uint16_t xadc_device_id;
uint8_t xadc_interrupt_id;
void startConversion();
bool isBusy();
bool getChannelValue(AdcIntCfgManager::Channel channel, float &var);
bool getOnChipSensorValue(AdcIntCfgManager::OnChipSensor sensor, float &var);
int configureSequencerChannels(uint64_t channels_mask);
int configureSettlingTime(uint64_t channels_mask);
void configureCalibration();
void configureAlarms();
void configureLowerAlarmThreshold(AdcIntCfgManager::Alarm alarm);
void configureUpperAlarmThreshold(AdcIntCfgManager::Alarm alarm);
void configureOperMode();
void configureInterrupts();
void initializeAnalogInputs();
void initializeSensors();
void initializeAlarms();
void notifySensors();
void notifyAlarms(uint32_t status);
uint64_t getChannelsMask();
uint16_t getCalibrationMask();
uint32_t getAlarmMask();
uint16_t getAlarmThresholdLowerMask(AdcIntCfgManager::Alarm alarm);
uint16_t getAlarmThresholdUpperMask(AdcIntCfgManager::Alarm alarm);
uint32_t getAlarmActivateMask(AdcIntCfgManager::Alarm alarm);
uint32_t getAlarmDeactivateMask(AdcIntCfgManager::Alarm alarm);
uint32_t getAlarmsInterruptEnableMask();
uint8_t getOnChipSensorAddress(AdcIntCfgManager::OnChipSensor sensor);
};
</code></pre>
<p><strong>AdcInt.cpp</strong></p>
<pre><code>#include "AdcInt.h"
#include <iostream>
using namespace std;
const uint64_t AdcInt::sensor_masks[static_cast<uint8_t>(
AdcIntCfgManager::OnChipSensor::kNoOnChipSensors)] = {
XSM_SEQ_CH_TEMP, XSM_SEQ_CH_VCCINT, XSM_SEQ_CH_VCCAUX,
XSM_SEQ_CH_VREFP, XSM_SEQ_CH_VREFN, XSM_SEQ_CH_VBRAM,
XSM_SEQ_CH_VCCPINT, XSM_SEQ_CH_VCCPAUX, XSM_SEQ_CH_VCCPDRO};
const uint16_t AdcInt::calibration_masks[static_cast<uint8_t>(
AdcIntCfgManager::Calibration::kNoCalibrations)] = {
XSM_CFR1_CAL_ADC_OFFSET_MASK, XSM_CFR1_CAL_ADC_GAIN_OFFSET_MASK,
XSM_CFR1_CAL_PS_OFFSET_MASK, XSM_CFR1_CAL_PS_GAIN_OFFSET_MASK};
const uint32_t AdcInt::alarm_masks[static_cast<uint8_t>(
AdcIntCfgManager::Alarm::kNoAlarms)] = {
XSM_CFR_OT_MASK, XSM_CFR_ALM_TEMP_MASK, XSM_CFR_ALM_VCCINT_MASK,
XSM_CFR_ALM_VCCAUX_MASK, XSM_CFR_ALM_VBRAM_MASK, XSM_CFR_ALM_VCCPINT_MASK,
XSM_CFR_ALM_VCCPAUX_MASK, XSM_CFR_ALM_VCCPDRO_MASK};
const uint16_t AdcInt::threshold_masks[static_cast<uint8_t>(
AdcIntCfgManager::AlarmThresholdName::kNoAlarmThresholdNames)] = {
XSM_ATR_TEMP_UPPER, XSM_ATR_VCCINT_UPPER, XSM_ATR_VCCAUX_UPPER,
XSM_ATR_OT_UPPER, XSM_ATR_TEMP_LOWER, XSM_ATR_VCCINT_LOWER,
XSM_ATR_VCCAUX_LOWER, XSM_ATR_OT_LOWER, XSM_ATR_VBRAM_UPPER,
XSM_ATR_VCCPINT_UPPER, XSM_ATR_VCCPAUX_UPPER, XSM_ATR_VCCPDRO_UPPER,
XSM_ATR_VBRAM_LOWER, XSM_ATR_VCCPINT_LOWER, XSM_ATR_VCCPAUX_LOWER,
XSM_ATR_VCCPDRO_LOWER};
const uint8_t AdcInt::sensors_address[static_cast<uint8_t>(
AdcIntCfgManager::OnChipSensor::kNoOnChipSensors)] = {
XSM_CH_TEMP, XSM_CH_VCCINT, XSM_CH_VCCAUX, XSM_CH_VREFP, XSM_CH_VREFN,
XSM_CH_VBRAM, XSM_CH_VCCLPINT, XSM_CH_VCCPAUX, XSM_CH_VCCPDRO};
const uint32_t AdcInt::alarm_activate_masks[static_cast<uint8_t>(
AdcIntCfgManager::Alarm::kNoAlarms)] = {XSM_IPIXR_OT_MASK,
XSM_IPIXR_TEMP_MASK,
XSM_IPIXR_VCCINT_MASK,
XSM_IPIXR_VCCAUX_MASK,
XSM_IPIXR_VBRAM_MASK,
NON_EXISTING_ALARM_ACTIVE_MASK,
NON_EXISTING_ALARM_ACTIVE_MASK,
NON_EXISTING_ALARM_ACTIVE_MASK};
const uint32_t AdcInt::alarm_deactivate_masks[static_cast<uint8_t>(
AdcIntCfgManager::Alarm::kNoAlarms)] = {
XSM_IPIXR_OT_DEACTIVE_MASK, XSM_IPIXR_TEMP_DEACTIVE_MASK,
NON_EXISTING_ALARM_DEACTIVE_MASK, NON_EXISTING_ALARM_DEACTIVE_MASK,
NON_EXISTING_ALARM_DEACTIVE_MASK, NON_EXISTING_ALARM_DEACTIVE_MASK,
NON_EXISTING_ALARM_DEACTIVE_MASK, NON_EXISTING_ALARM_DEACTIVE_MASK};
AdcInt::AdcInt(AdcIntCfgManager *_configuration_manager,
uint16_t _xadc_device_id, uint8_t _xadc_interrupt_id)
{
configuration_manager = _configuration_manager;
xadc_device_id = _xadc_device_id;
xadc_interrupt_id = _xadc_interrupt_id;
}
void AdcInt::initialize()
{
XSysMon_Config *xadc_cfg;
int oper_result;
uint64_t channels_mask;
xadc_cfg = XSysMon_LookupConfig(xadc_device_id);
if (xadc_cfg == NULL) {
cout << "xadc device id hasn't been found" << endl;
} else {
oper_result =
XSysMon_CfgInitialize(&xadc_driver, xadc_cfg, xadc_cfg->BaseAddress);
if (oper_result != XST_SUCCESS) {
cout << "xadc driver initialization failed" << endl;
} else {
channels_mask = getChannelsMask();
oper_result = configureSequencerChannels(channels_mask);
if (oper_result != XST_SUCCESS) {
cout << "xadc sequencer channels configuration failed" << endl;
} else {
XSysMon_SetAdcClkDivisor(&xadc_driver,
configuration_manager->getClkDivRatio());
XSysMon_SetAvg(&xadc_driver,
configuration_manager->getNoAveragedSamples());
oper_result = configureSettlingTime(channels_mask);
if (oper_result != XST_SUCCESS) {
cout << "xadc settling time configuration failed" << endl;
} else {
configureCalibration();
configureAlarms();
configureOperMode();
initializeAnalogInputs();
initializeSensors();
initializeAlarms();
configureInterrupts();
}
}
}
}
}
void AdcInt::update()
{
if (isBusy() == false) {
startConversion();
}
}
bool AdcInt::isReady()
{
for (AnalogInput &input : analog_inputs) {
if (input.isReady() == false) {
return false;
}
}
for (Sensor &sensor : sensors) {
if (sensor.isReady() == false) {
return false;
}
}
return true;
}
bool AdcInt::getValue(Input input, float &var)
{
if (static_cast<uint8_t>(input) < static_cast<uint8_t>(Input::kNoChannels)) {
return getChannelValue(static_cast<AdcIntCfgManager::Channel>(input), var);
} else if ((static_cast<uint8_t>(input) >
static_cast<uint8_t>(Input::kNoChannels)) &&
(static_cast<uint8_t>(input) <
static_cast<uint8_t>(Input::kNoInputs))) {
uint8_t sensor_index = static_cast<uint8_t>(input) -
static_cast<uint8_t>(Input::kNoChannels) - 1;
return getOnChipSensorValue(
static_cast<AdcIntCfgManager::OnChipSensor>(sensor_index), var);
} else {
return false;
}
}
bool AdcInt::isAlarmActive(AdcIntCfgManager::Alarm alarm)
{
return alarms[static_cast<uint8_t>(alarm)].isActive();
}
void AdcInt::handle_interrupt()
{
uint32_t status = XSysMon_IntrGetStatus(&xadc_driver);
if (isEndOfSequenceInterrupt(status)) {
analog_inputs[channel_address_monitor.getChannelAddress()].notify();
notifySensors();
channel_address_monitor.refreshAddress();
} else if (isAlarmInterrupt(status)) {
notifyAlarms(status);
}
}
AdcInt::AnalogInput::AnalogInput()
{
value = 0;
ready = true;
enabled = false;
}
void AdcInt::AnalogInput::initialize(XSysMon *_xadc_driver, uint8_t _addr,
bool _enable, float _norm)
{
addr = _addr;
enabled = _enable;
norm = _norm;
xadc_driver = _xadc_driver;
}
bool AdcInt::AnalogInput::isEnabled()
{
return enabled;
}
float AdcInt::AnalogInput::getValue()
{
return (value / 4096.0 * norm);
}
bool AdcInt::AnalogInput::isReady()
{
return ready;
}
void AdcInt::AnalogInput::notify()
{
if (enabled) {
value = XSysMon_GetAdcData(xadc_driver, addr);
}
}
AdcInt::Sensor::Sensor()
{
value = 0;
ready = true;
enabled = false;
}
void AdcInt::Sensor::initialize(XSysMon *_xadc_driver, uint8_t _addr,
bool _enable,
AdcIntCfgManager::OnChipSensorType _type)
{
addr = _addr;
type = _type;
enabled = _enable;
xadc_driver = _xadc_driver;
}
bool AdcInt::Sensor::isEnabled()
{
return enabled;
}
float AdcInt::Sensor::getValue()
{
float ret_val;
if (type == AdcIntCfgManager::OnChipSensorType::kVoltageSensor) {
ret_val = voltageRawToV(value);
} else if (type == AdcIntCfgManager::OnChipSensorType::kTemperatureSensor) {
ret_val = temperatureRawToC(value);
}
return ret_val;
}
bool AdcInt::Sensor::isReady()
{
return ready;
}
void AdcInt::Sensor::notify()
{
if (enabled) {
value = XSysMon_GetAdcData(xadc_driver, addr);
}
}
AdcInt::Alarm::Alarm()
{
active = false;
enabled = false;
}
void AdcInt::Alarm::initialize(bool _enable, uint32_t _activate_mask,
uint32_t _deactivate_mask)
{
activate_mask = _activate_mask;
deactivate_mask = _deactivate_mask;
enabled = _enable;
}
bool AdcInt::Alarm::isEnabled()
{
return enabled;
}
bool AdcInt::Alarm::isActive()
{
return active;
}
void AdcInt::Alarm::notify(uint32_t status)
{
if (enabled) {
if (status & activate_mask) {
active = true;
} else if (status & deactivate_mask) {
active = false;
}
}
}
AdcInt::ChannelAddressMonitor::ChannelAddressMonitor()
{
channel_address = 0;
}
void AdcInt::ChannelAddressMonitor::refreshAddress()
{
if (++channel_address ==
static_cast<uint8_t>(AdcIntCfgManager::Channel::kNoChannels)) {
channel_address = 0;
}
}
uint8_t AdcInt::ChannelAddressMonitor::getChannelAddress()
{
return channel_address;
}
void AdcInt::startConversion()
{
XSysMon_StartAdcConversion(&xadc_driver);
}
bool AdcInt::isBusy()
{
return ((XSysMon_GetStatus(&xadc_driver) & XSM_SR_BUSY_MASK) != 0);
}
bool AdcInt::getChannelValue(AdcIntCfgManager::Channel channel, float &var)
{
bool enabled = false;
uint8_t index = static_cast<uint8_t>(channel);
if (analog_inputs[index].isEnabled()) {
var = analog_inputs[index].getValue();
enabled = true;
}
return enabled;
}
bool AdcInt::getOnChipSensorValue(AdcIntCfgManager::OnChipSensor sensor,
float &var)
{
bool enabled = false;
uint8_t index = static_cast<uint8_t>(sensor);
if (sensors[index].isEnabled()) {
var = sensors[index].getValue();
enabled = true;
}
return enabled;
}
bool AdcInt::isEndOfSequenceInterrupt(uint32_t status)
{
if (status & XSM_IPIXR_EOS_MASK) {
return true;
} else {
return false;
}
}
bool AdcInt::isAlarmInterrupt(uint32_t status)
{
if ((status & XSM_IPIXR_VBRAM_MASK) |
(status & XSM_IPIXR_TEMP_DEACTIVE_MASK) |
(status & XSM_IPIXR_OT_DEACTIVE_MASK) | (status & XSM_IPIXR_VCCAUX_MASK) |
(status & XSM_IPIXR_VCCINT_MASK) | (status & XSM_IPIXR_TEMP_MASK) |
(status & XSM_IPIXR_OT_MASK)) {
return true;
} else {
return false;
}
}
float AdcInt::temperatureRawToC(uint16_t raw_temp)
{
// see ug480 on page 33
return ((raw_temp * 503.975) / 4096.0 - 273.15);
}
uint16_t AdcInt::temperatureCToRaw(float temp)
{
// see ug480 on page 33
return (4096.0 * (temp + 273.15) / 503.975);
}
float AdcInt::voltageRawToV(uint16_t raw_voltage)
{
// see ug480 on page 34
return (raw_voltage * 3.0 / 4096.0);
}
uint16_t AdcInt::voltageVToRaw(float voltage)
{
// see ug480 on page 34
return (voltage * 4096.0 / 3.0);
}
int AdcInt::configureSequencerChannels(uint64_t channels_mask)
{
// disable sequencer before configuration (please see the xsysmon_extmux_example.c from Xilinx)
XSysMon_SetSequencerMode(&xadc_driver, XSM_SEQ_MODE_SAFE);
int oper_result = XSysMon_SetSeqChEnables(&xadc_driver, channels_mask);
return oper_result;
}
int AdcInt::configureSettlingTime(uint64_t channels_mask)
{
int oper_result = XST_SUCCESS;
if (configuration_manager->isIncreasedSettlingTimeEnabled()) {
oper_result = XSysMon_SetSeqAcqTime(&xadc_driver, channels_mask);
}
return oper_result;
}
void AdcInt::configureCalibration()
{
uint16_t calibration_mask = getCalibrationMask();
XSysMon_SetCalibEnables(&xadc_driver, calibration_mask);
}
void AdcInt::configureAlarms()
{
uint32_t alarms_mask = getAlarmMask();
XSysMon_SetAlarmEnables(&xadc_driver, alarms_mask);
for (uint8_t alarm = 0;
alarm < static_cast<uint8_t>(AdcIntCfgManager::Alarm::kNoAlarms);
alarm++) {
if (configuration_manager->isAlarmEnabled(
static_cast<AdcIntCfgManager::Alarm>(alarm))) {
configureLowerAlarmThreshold(static_cast<AdcIntCfgManager::Alarm>(alarm));
configureUpperAlarmThreshold(static_cast<AdcIntCfgManager::Alarm>(alarm));
}
}
}
void AdcInt::configureLowerAlarmThreshold(AdcIntCfgManager::Alarm alarm)
{
float threshold;
uint8_t threshold_mask;
uint16_t raw_threshold;
threshold = configuration_manager->getAlarmThresholdLower(alarm);
threshold_mask = getAlarmThresholdLowerMask(alarm);
if (configuration_manager->getAlarmType(alarm) ==
AdcIntCfgManager::AlarmType::kTemperatureAlarm) {
raw_threshold = temperatureCToRaw(threshold);
} else if (configuration_manager->getAlarmType(alarm) ==
AdcIntCfgManager::AlarmType::kVoltageAlarm) {
raw_threshold = voltageVToRaw(threshold);
}
XSysMon_SetAlarmThreshold(&xadc_driver, threshold_mask, raw_threshold);
}
void AdcInt::configureUpperAlarmThreshold(AdcIntCfgManager::Alarm alarm)
{
float threshold;
uint8_t threshold_mask;
uint16_t raw_threshold;
threshold = configuration_manager->getAlarmThresholdUpper(alarm);
threshold_mask = getAlarmThresholdUpperMask(alarm);
if (configuration_manager->getAlarmType(alarm) ==
AdcIntCfgManager::AlarmType::kTemperatureAlarm) {
raw_threshold = temperatureCToRaw(threshold);
} else if (configuration_manager->getAlarmType(alarm) ==
AdcIntCfgManager::AlarmType::kVoltageAlarm) {
raw_threshold = voltageVToRaw(threshold);
}
XSysMon_SetAlarmThreshold(&xadc_driver, threshold_mask, raw_threshold);
}
void AdcInt::configureOperMode()
{
// external multiplexer connection
XSysMon_SetExtenalMux(&xadc_driver, XSM_CH_VPVN);
// single pass mode of operation
XSysMon_SetSequencerMode(&xadc_driver, XSM_SEQ_MODE_ONEPASS);
}
void AdcInt::configureInterrupts()
{
XSysMon_IntrEnable(&xadc_driver,
XSM_IPIXR_EOS_MASK | getAlarmsInterruptEnableMask());
XSysMon_IntrGlobalEnable(&xadc_driver);
platform::drivers::InterruptController::instance().connect(xadc_interrupt_id,
*this);
}
void AdcInt::initializeAnalogInputs()
{
for (uint8_t input = 0;
input < static_cast<uint8_t>(AdcIntCfgManager::Channel::kNoChannels);
input++) {
analog_inputs[input].initialize(
&xadc_driver, XSM_CH_VPVN,
configuration_manager->isChannelEnabled(
static_cast<AdcIntCfgManager::Channel>(input)),
configuration_manager->getChannelNorm(
static_cast<AdcIntCfgManager::Channel>(input)));
}
}
void AdcInt::initializeSensors()
{
for (uint8_t sensor = 0;
sensor <
static_cast<uint8_t>(AdcIntCfgManager::OnChipSensor::kNoOnChipSensors);
sensor++) {
sensors[sensor].initialize(
&xadc_driver,
getOnChipSensorAddress(
static_cast<AdcIntCfgManager::OnChipSensor>(sensor)),
configuration_manager->isOnChipSensorEnabled(
static_cast<AdcIntCfgManager::OnChipSensor>(sensor)),
configuration_manager->getSensorType(
static_cast<AdcIntCfgManager::OnChipSensor>(sensor)));
}
}
void AdcInt::initializeAlarms()
{
for (uint8_t alarm = 0;
alarm < static_cast<uint8_t>(AdcIntCfgManager::Alarm::kNoAlarms);
alarm++) {
alarms[alarm].initialize(
configuration_manager->isAlarmEnabled(
static_cast<AdcIntCfgManager::Alarm>(alarm)),
getAlarmActivateMask(static_cast<AdcIntCfgManager::Alarm>(alarm)),
getAlarmDeactivateMask(static_cast<AdcIntCfgManager::Alarm>(alarm)));
}
}
void AdcInt::notifySensors()
{
for (Sensor &sensor : sensors) {
sensor.notify();
}
}
void AdcInt::notifyAlarms(uint32_t status)
{
for (Alarm &alarm : alarms) {
alarm.notify(status);
}
}
uint64_t AdcInt::getChannelsMask()
{
uint64_t channels_mask = 0;
if (configuration_manager->isCalibrationEnabled()) {
channels_mask |= XSM_SEQ_CH_CALIB;
}
for (uint8_t sensor = 0;
sensor <
static_cast<uint8_t>(AdcIntCfgManager::OnChipSensor::kNoOnChipSensors);
sensor++) {
if (configuration_manager->isOnChipSensorEnabled(
static_cast<AdcIntCfgManager::OnChipSensor>(sensor))) {
channels_mask |= sensor_masks[sensor];
}
}
// external multiplexer connection
channels_mask |= XSM_SEQ_CH_VPVN;
return channels_mask;
}
uint16_t AdcInt::getCalibrationMask()
{
uint16_t calibration_mask = 0;
for (uint8_t calibration = 0;
calibration <
static_cast<uint8_t>(AdcIntCfgManager::Calibration::kNoCalibrations);
calibration++) {
if (configuration_manager->isCalibrationTypeEnabled(
static_cast<AdcIntCfgManager::Calibration>(calibration))) {
calibration_mask |= calibration_masks[calibration];
}
}
return calibration_mask;
}
uint32_t AdcInt::getAlarmMask()
{
uint32_t alarm_mask = 0;
for (uint8_t alarm = 0;
alarm < static_cast<uint8_t>(AdcIntCfgManager::Alarm::kNoAlarms);
alarm++) {
if (configuration_manager->isAlarmEnabled(
static_cast<AdcIntCfgManager::Alarm>(alarm))) {
alarm_mask |= alarm_masks[alarm];
}
}
return alarm_mask;
}
uint16_t AdcInt::getAlarmThresholdLowerMask(AdcIntCfgManager::Alarm alarm)
{
return (threshold_masks[static_cast<uint8_t>(
configuration_manager->getAlarmLowerThresholdName(alarm))]);
}
uint16_t AdcInt::getAlarmThresholdUpperMask(AdcIntCfgManager::Alarm alarm)
{
return (threshold_masks[static_cast<uint8_t>(
configuration_manager->getAlarmUpperThresholdName(alarm))]);
}
uint32_t AdcInt::getAlarmActivateMask(AdcIntCfgManager::Alarm alarm)
{
return alarm_activate_masks[static_cast<uint8_t>(alarm)];
}
uint32_t AdcInt::getAlarmDeactivateMask(AdcIntCfgManager::Alarm alarm)
{
return alarm_deactivate_masks[static_cast<uint8_t>(alarm)];
}
uint32_t AdcInt::getAlarmsInterruptEnableMask()
{
uint32_t alarms_interrupt_enable_mask = 0;
for (uint8_t alarm = 0;
alarm < static_cast<uint8_t>(AdcIntCfgManager::Alarm::kNoAlarms);
alarm++) {
if (configuration_manager->isAlarmEnabled(
static_cast<AdcIntCfgManager::Alarm>(alarm))) {
alarms_interrupt_enable_mask |= alarm_activate_masks[alarm];
}
}
return alarms_interrupt_enable_mask;
}
uint8_t AdcInt::getOnChipSensorAddress(AdcIntCfgManager::OnChipSensor sensor)
{
return sensors_address[static_cast<uint8_t>(sensor)];
}
</code></pre>
<p><strong>AdcIntCfgManager.h</strong></p>
<pre><code>#include <cstdint>
class AdcIntCfgManager
{
public:
enum class Channel {
kChannel00,
kChannel01,
kChannel02,
kChannel03,
kChannel04,
kChannel05,
kChannel06,
kChannel07,
kChannel08,
kChannel09,
kChannel10,
kChannel11,
kChannel12,
kNoChannels
};
enum class OnChipSensor {
kOnChipTemp,
kVccInt,
kVccAux,
kVrefP,
kVrefN,
kVBram,
kVccPInt,
kVccPAux,
kVccOddr,
kNoOnChipSensors
};
enum class ChannelType { kUnipolar, kBipolar };
enum class ChannelEnable { kChannelDisabled, kChannelEnabled };
struct ChannelCfg
{
Channel channel;
ChannelType type;
ChannelEnable enable;
float norm;
};
enum class AdcClockDivRatio {
kADCCLK_DCLK_DIV_002,
kADCCLK_DCLK_DIV_003 = 3,
kADCCLK_DCLK_DIV_004 = 4,
kADCCLK_DCLK_DIV_255 = 255
};
enum class OnChipSensorType { kVoltageSensor, kTemperatureSensor };
enum class OnChipSensorEnable { kSensorDisabled, kSensorEnabled };
struct OnChipSensorsCfg
{
OnChipSensor sensor;
OnChipSensorType type;
OnChipSensorEnable enable;
};
enum class Averaging {
kAveragingFrom_0_Samples,
kAveragingFrom_16_Samples,
kAveragingFrom_64_Samples,
kAveragingFrom_256_Samples
};
enum class Calibration {
kAdcOffsetCorrection,
kAdcOffsetGainCorrection,
kSupplySensorOffsetCorrection,
kSupplySensorOffsetGainCorrection,
kNoCalibrations
};
enum class CalibrationEnable { kCalibrationDisabled, kCalibrationEnabled };
struct CalibrationCfg
{
Calibration calibration;
CalibrationEnable enable;
};
enum class SettlingTime { kSettlingTime_4_ADCCLK, kSettlingTime_10_ADCCLK };
enum class Alarm {
kOverTemperature,
kOnChipTemperature,
kVccInt,
kVccAux,
kVBram,
kVccPInt,
kVccPAux,
kVccOddr,
kNoAlarms
};
enum class AlarmType { kTemperatureAlarm, kVoltageAlarm };
enum class AlarmEnable { kAlarmDisabled, kAlarmEnabled };
enum class AlarmThresholdName {
kOnChipTemperatureUpper,
kVccIntUpper,
kVccAuxUpper,
kOverTemperatureSet,
kOnChipTemperatureLower,
kVccIntLower,
kVccAuxLower,
kOverTemperatureReset,
kVBramUpper,
kVccPIntUpper,
kVccPAuxUpper,
kVccOddrUpper,
kVBramLower,
kVccPIntLower,
kVccPAuxLower,
kVccOddrLower,
kNoAlarmThresholdNames
};
struct AlarmThreshold
{
AlarmThresholdName name;
float value;
};
struct AlarmsCfg
{
Alarm alarm;
AlarmType type;
AlarmEnable enable;
AlarmThreshold lower_threshold;
AlarmThreshold upper_threshold;
};
struct AdcIntCfg
{
ChannelCfg channels_cfg[static_cast<uint8_t>(
Channel::
kNoChannels)];
OnChipSensorsCfg sensors_cfg[static_cast<uint8_t>(
OnChipSensor::kNoOnChipSensors)];
AdcClockDivRatio
clock_div_ratio;
SettlingTime settling_time;
Averaging averaging;
CalibrationCfg calibration_cfg[static_cast<uint8_t>(
Calibration::kNoCalibrations)];
AlarmsCfg alarms_cfg[static_cast<uint8_t>(
Alarm::
kNoAlarms)];
};
AdcIntCfgManager(const AdcIntCfg *_configuration);
uint8_t getClkDivRatio();
bool isIncreasedSettlingTimeEnabled();
uint8_t getNoAveragedSamples();
bool isCalibrationEnabled();
bool isCalibrationTypeEnabled(Calibration type);
bool isAlarmEnabled(Alarm alarm);
float getAlarmThresholdLower(Alarm alarm);
float getAlarmThresholdUpper(Alarm alarm);
AlarmType getAlarmType(Alarm alarm);
AlarmThresholdName getAlarmLowerThresholdName(Alarm alarm);
AlarmThresholdName getAlarmUpperThresholdName(Alarm alarm);
bool isChannelEnabled(Channel channel);
ChannelType getChannelType(Channel channel);
float getChannelNorm(Channel channel);
bool isOnChipSensorEnabled(OnChipSensor sensor);
OnChipSensorType getSensorType(OnChipSensor sensor);
private:
const AdcIntCfg *configuration;
};
</code></pre>
<p><strong>AdcIntCfgManager.cpp</strong></p>
<pre><code>#include "AdcIntCfgManager.h"
AdcIntCfgManager::AdcIntCfgManager(const AdcIntCfg *_configuration)
{
configuration = _configuration;
}
uint8_t AdcIntCfgManager::getClkDivRatio()
{
return static_cast<uint8_t>(configuration->clock_div_ratio);
}
bool AdcIntCfgManager::isIncreasedSettlingTimeEnabled()
{
return (configuration->settling_time ==
SettlingTime::kSettlingTime_10_ADCCLK);
}
uint8_t AdcIntCfgManager::getNoAveragedSamples()
{
return static_cast<uint8_t>(configuration->averaging);
}
bool AdcIntCfgManager::isCalibrationEnabled()
{
bool ret_val = false;
for (uint8_t i = 0; i < static_cast<uint8_t>(Calibration::kNoCalibrations);
i++) {
if (configuration->calibration_cfg[i].enable ==
CalibrationEnable::kCalibrationEnabled) {
ret_val = true;
break;
}
}
return ret_val;
}
bool AdcIntCfgManager::isCalibrationTypeEnabled(Calibration type)
{
if (configuration->calibration_cfg[static_cast<uint8_t>(type)].enable ==
CalibrationEnable::kCalibrationEnabled) {
return true;
} else {
return false;
}
}
bool AdcIntCfgManager::isAlarmEnabled(Alarm alarm)
{
return (configuration->alarms_cfg[static_cast<uint8_t>(alarm)].enable ==
AlarmEnable::kAlarmEnabled);
}
float AdcIntCfgManager::getAlarmThresholdLower(Alarm alarm)
{
return (configuration->alarms_cfg[static_cast<uint8_t>(alarm)]
.lower_threshold.value);
}
float AdcIntCfgManager::getAlarmThresholdUpper(Alarm alarm)
{
return (configuration->alarms_cfg[static_cast<uint8_t>(alarm)]
.upper_threshold.value);
}
AdcIntCfgManager::AlarmType AdcIntCfgManager::getAlarmType(Alarm alarm)
{
return (configuration->alarms_cfg[static_cast<uint8_t>(alarm)].type);
}
AdcIntCfgManager::AlarmThresholdName
AdcIntCfgManager::getAlarmLowerThresholdName(Alarm alarm)
{
return (configuration->alarms_cfg[static_cast<uint8_t>(alarm)]
.lower_threshold.name);
}
AdcIntCfgManager::AlarmThresholdName
AdcIntCfgManager::getAlarmUpperThresholdName(Alarm alarm)
{
return (configuration->alarms_cfg[static_cast<uint8_t>(alarm)]
.upper_threshold.name);
}
bool AdcIntCfgManager::isChannelEnabled(Channel channel)
{
if (configuration->channels_cfg[static_cast<uint8_t>(channel)].enable ==
ChannelEnable::kChannelEnabled) {
return true;
} else {
return false;
}
}
float AdcIntCfgManager::getChannelNorm(Channel channel)
{
return (configuration->channels_cfg[static_cast<uint8_t>(channel)].norm);
}
AdcIntCfgManager::ChannelType AdcIntCfgManager::getChannelType(Channel channel)
{
return (configuration->channels_cfg[static_cast<uint8_t>(channel)].type);
}
bool AdcIntCfgManager::isOnChipSensorEnabled(OnChipSensor sensor)
{
if (configuration->sensors_cfg[static_cast<uint8_t>(sensor)].enable ==
OnChipSensorEnable::kSensorEnabled) {
return true;
} else {
return false;
}
}
AdcIntCfgManager::OnChipSensorType
AdcIntCfgManager::getSensorType(OnChipSensor sensor)
{
return (configuration->sensors_cfg[static_cast<uint8_t>(sensor)].type);
}
</code></pre>
<p>The intended usage of the driver is following:</p>
<ul>
<li>whole the configuration information are in the <code>FpgaPeripheralsCfg</code> class</li>
<li>the instance of the AdcInt is along with instances of other drivers in the "container" <code>FpgaDrivers</code></li>
</ul>
<p><strong>FpgaPeripheralsCfg.h</strong></p>
<pre><code>#include "AdcIntCfgManager.h"
class FpgaPeripheralsCfg
{
public:
AdcIntCfgManager adc_int_cfg_manager;
FpgaPeripheralsCfg() :
adc_int_cfg_manager(&adc_int_cfg)
{
}
private:
AdcIntCfgManager::AdcIntCfg adc_int_cfg = {
{{AdcIntCfgManager::Channel::kChannel00,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel01,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel02,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel03,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel04,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel05,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel06,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel07,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel08,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel09,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel10,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel11,
AdcIntCfgManager::ChannelType::kBipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 100.0},
{AdcIntCfgManager::Channel::kChannel12,
AdcIntCfgManager::ChannelType::kUnipolar,
AdcIntCfgManager::ChannelEnable::kChannelEnabled, 3.0}},
{{AdcIntCfgManager::OnChipSensor::kOnChipTemp,
AdcIntCfgManager::OnChipSensorType::kTemperatureSensor,
AdcIntCfgManager::OnChipSensorEnable::kSensorEnabled},
{AdcIntCfgManager::OnChipSensor::kVccInt,
AdcIntCfgManager::OnChipSensorType::kVoltageSensor,
AdcIntCfgManager::OnChipSensorEnable::kSensorEnabled},
{AdcIntCfgManager::OnChipSensor::kVccAux,
AdcIntCfgManager::OnChipSensorType::kVoltageSensor,
AdcIntCfgManager::OnChipSensorEnable::kSensorEnabled},
{AdcIntCfgManager::OnChipSensor::kVrefP,
AdcIntCfgManager::OnChipSensorType::kVoltageSensor,
AdcIntCfgManager::OnChipSensorEnable::kSensorEnabled},
{AdcIntCfgManager::OnChipSensor::kVrefN,
AdcIntCfgManager::OnChipSensorType::kVoltageSensor,
AdcIntCfgManager::OnChipSensorEnable::kSensorEnabled},
{AdcIntCfgManager::OnChipSensor::kVBram,
AdcIntCfgManager::OnChipSensorType::kVoltageSensor,
AdcIntCfgManager::OnChipSensorEnable::kSensorEnabled},
{AdcIntCfgManager::OnChipSensor::kVccPInt,
AdcIntCfgManager::OnChipSensorType::kVoltageSensor,
AdcIntCfgManager::OnChipSensorEnable::kSensorEnabled},
{AdcIntCfgManager::OnChipSensor::kVccPAux,
AdcIntCfgManager::OnChipSensorType::kVoltageSensor,
AdcIntCfgManager::OnChipSensorEnable::kSensorEnabled},
{AdcIntCfgManager::OnChipSensor::kVccOddr,
AdcIntCfgManager::OnChipSensorType::kVoltageSensor,
AdcIntCfgManager::OnChipSensorEnable::kSensorEnabled}},
.clock_div_ratio =
AdcIntCfgManager::AdcClockDivRatio::kADCCLK_DCLK_DIV_002,
.settling_time = AdcIntCfgManager::SettlingTime::kSettlingTime_4_ADCCLK,
.averaging = AdcIntCfgManager::Averaging::kAveragingFrom_16_Samples,
{{AdcIntCfgManager::Calibration::kAdcOffsetCorrection,
AdcIntCfgManager::CalibrationEnable::kCalibrationEnabled},
{AdcIntCfgManager::Calibration::kAdcOffsetGainCorrection,
AdcIntCfgManager::CalibrationEnable::kCalibrationEnabled},
{AdcIntCfgManager::Calibration::kSupplySensorOffsetCorrection,
AdcIntCfgManager::CalibrationEnable::kCalibrationEnabled},
{AdcIntCfgManager::Calibration::kSupplySensorOffsetGainCorrection,
AdcIntCfgManager::CalibrationEnable::kCalibrationEnabled}},
{{AdcIntCfgManager::Alarm::kOverTemperature,
AdcIntCfgManager::AlarmType::kTemperatureAlarm,
AdcIntCfgManager::AlarmEnable::kAlarmEnabled,
{AdcIntCfgManager::AlarmThresholdName::kOverTemperatureReset, 90.0},
{AdcIntCfgManager::AlarmThresholdName::kOverTemperatureSet, 125.0}},
{AdcIntCfgManager::Alarm::kOnChipTemperature,
AdcIntCfgManager::AlarmType::kTemperatureAlarm,
AdcIntCfgManager::AlarmEnable::kAlarmEnabled,
{AdcIntCfgManager::AlarmThresholdName::kOnChipTemperatureLower, 100.0},
{AdcIntCfgManager::AlarmThresholdName::kOnChipTemperatureUpper, 125.0}},
{AdcIntCfgManager::Alarm::kVccInt,
AdcIntCfgManager::AlarmType::kVoltageAlarm,
AdcIntCfgManager::AlarmEnable::kAlarmEnabled,
{AdcIntCfgManager::AlarmThresholdName::kVccIntLower, 2.7},
{AdcIntCfgManager::AlarmThresholdName::kVccIntUpper, 2.9}},
{AdcIntCfgManager::Alarm::kVccAux,
AdcIntCfgManager::AlarmType::kVoltageAlarm,
AdcIntCfgManager::AlarmEnable::kAlarmEnabled,
{AdcIntCfgManager::AlarmThresholdName::kVccAuxLower, 2.7},
{AdcIntCfgManager::AlarmThresholdName::kVccAuxUpper, 2.9}},
{AdcIntCfgManager::Alarm::kVBram,
AdcIntCfgManager::AlarmType::kVoltageAlarm,
AdcIntCfgManager::AlarmEnable::kAlarmEnabled,
{AdcIntCfgManager::AlarmThresholdName::kVBramLower, 2.7},
{AdcIntCfgManager::AlarmThresholdName::kVBramUpper, 2.9}},
{AdcIntCfgManager::Alarm::kVccPInt,
AdcIntCfgManager::AlarmType::kVoltageAlarm,
AdcIntCfgManager::AlarmEnable::kAlarmEnabled,
{AdcIntCfgManager::AlarmThresholdName::kVccPIntLower, 2.7},
{AdcIntCfgManager::AlarmThresholdName::kVccPIntUpper, 2.9}},
{AdcIntCfgManager::Alarm::kVccPAux,
AdcIntCfgManager::AlarmType::kVoltageAlarm,
AdcIntCfgManager::AlarmEnable::kAlarmEnabled,
{AdcIntCfgManager::AlarmThresholdName::kVccPAuxLower, 2.7},
{AdcIntCfgManager::AlarmThresholdName::kVccPAuxUpper, 2.9}},
{AdcIntCfgManager::Alarm::kVccOddr,
AdcIntCfgManager::AlarmType::kVoltageAlarm,
AdcIntCfgManager::AlarmEnable::kAlarmEnabled,
{AdcIntCfgManager::AlarmThresholdName::kVccOddrLower, 2.7},
{AdcIntCfgManager::AlarmThresholdName::kVccOddrUpper, 2.9}}}};
};
</code></pre>
<p><strong>FpgaDrivers.h</strong></p>
<pre><code>#include "AdcInt.h"
class FpgaDrivers
{
public:
AdcInt adc_int;
FpgaDrivers(FpgaPeripheralsCfg &cfg);
void initialize(void);
private:
};
</code></pre>
<p><strong>FpgaDrivers.cpp</strong></p>
<pre><code>#include "FpgaDrivers.h"
FpgaDrivers::FpgaDrivers(FpgaPeripheralsCfg &cfg) :
adc_int(&(cfg.adc_int_cfg_manager), 0, 62)
{
}
void FpgaDrivers::initialize(void)
{
adc_int.initialize();
}
</code></pre>
<p><strong>main</strong></p>
<pre><code>int main(int argc, char** argv) {
float adc_value;
FpgaPeripheralsCfg fpga_peripherals_cfg;
FpgaDrivers drivers(fpga_peripherals_cfg);
drivers.initialize();
drivers.adc_int.update();
if(drivers.adc_int.isReady()) {
drivers.adc_int.getValue(platform::drivers::fpga::AdcInt::Input::kChannel00, adc_value);
}
return 0;
}
</code></pre>
<p>I would like to ask you mainly for assessment of the whole driver design i.e. how the driver is divided into the C++ classes and how those classes interact.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-18T18:04:44.700",
"Id": "502785",
"Score": "0",
"body": "It's not clear which file is which because the `#include` file names don't match the names in the question. If you could edit the file names in the question to be the full, correct names of each file, it would make the question easier to review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:09:22.227",
"Id": "502893",
"Score": "0",
"body": "I am sorry for that. This discrepancy is caused by my naming convention for the `.h` and `.cpp` modules. I have just attempted to put it into accordance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:15:13.050",
"Id": "502894",
"Score": "1",
"body": "Still unclear. It appears you have lumped the `.h` and `.cpp` files together under each heading. Better would be to label **each file** with its actual name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-19T15:25:52.430",
"Id": "502896",
"Score": "0",
"body": "I have just edited my question."
}
] |
[
{
"body": "<h2><code>const</code></h2>\n<p>You need more of it, in several places. Methods like these:</p>\n<pre><code>bool isReady();\nbool getValue(Input input, float &var);\nbool isAlarmActive(AdcIntCfgManager::Alarm alarm);\nbool isEnabled();\nfloat getValue();\nbool isReady();\n</code></pre>\n<p>should all get a <code>const</code> suffix of the form</p>\n<pre><code>bool isReady() const;\n</code></pre>\n<p>as a promise that the method does not modify <code>this</code>. If any of the above <em>do</em> modify <code>this</code>, then that means the method needs to be redesigned or at least renamed.</p>\n<p>Members like this:</p>\n<pre><code>AdcIntCfgManager::ChannelType type;\nXSysMon *xadc_driver;\n</code></pre>\n<p>should probably be</p>\n<pre><code>const AdcIntCfgManager::ChannelType type;\nXSysMon *const xadc_driver;\n</code></pre>\n<p>to indicate a guarantee that they won't change over the instance's lifetime even if other members do.</p>\n<h2>Boolean redundancy</h2>\n<pre><code>if (isBusy() == false) {\n</code></pre>\n<p>should be</p>\n<pre><code>if (!isBusy()) {\n</code></pre>\n<p>and</p>\n<pre><code> if (status & XSM_IPIXR_EOS_MASK) {\n return true;\n } else {\n return false;\n }\n</code></pre>\n<p>should be</p>\n<pre><code>return status & XSM_IPIXR_EOS_MASK != 0;\n</code></pre>\n<h2>Redundant parens</h2>\n<pre><code>return (value / 4096.0 * norm);\n</code></pre>\n<p>does not need outer parens.</p>\n<h2>Combined mask comparison</h2>\n<pre><code> if ((status & XSM_IPIXR_VBRAM_MASK) |\n (status & XSM_IPIXR_TEMP_DEACTIVE_MASK) |\n (status & XSM_IPIXR_OT_DEACTIVE_MASK) | (status & XSM_IPIXR_VCCAUX_MASK) |\n (status & XSM_IPIXR_VCCINT_MASK) | (status & XSM_IPIXR_TEMP_MASK) |\n (status & XSM_IPIXR_OT_MASK)) {\n</code></pre>\n<p>can be simplified by storing a combined mask constant somewhere else:</p>\n<pre><code>const int INTERRUPT_MASK =\n XSM_IPIXR_VBRAM_MASK\n | XSM_IPIXR_TEMP_DEACTIVE_MASK\n | XSM_IPIXR_OT_DEACTIVE_MASK\n | XSM_IPIXR_VCCAUX_MASK\n | XSM_IPIXR_VCCINT_MASK\n | XSM_IPIXR_TEMP_MASK\n | XSM_IPIXR_OT_MASK;\n// ...\nreturn status & INTERRUPT_MASK != 0;\n</code></pre>\n<h2>Early return</h2>\n<p>Rather than</p>\n<pre><code> int oper_result = XST_SUCCESS;\n if (configuration_manager->isIncreasedSettlingTimeEnabled()) {\n oper_result = XSysMon_SetSeqAcqTime(&xadc_driver, channels_mask);\n }\n return oper_result;\n</code></pre>\n<p>I usually prefer the style</p>\n<pre><code> if (configuration_manager->isIncreasedSettlingTimeEnabled()) {\n return XSysMon_SetSeqAcqTime(&xadc_driver, channels_mask);\n }\n return XST_SUCCESS;\n</code></pre>\n<p>Similarly,</p>\n<pre><code>bool AdcIntCfgManager::isCalibrationEnabled()\n{\n for (uint8_t i = 0; i < static_cast<uint8_t>(Calibration::kNoCalibrations);\n i++) {\n if (configuration->calibration_cfg[i].enable ==\n CalibrationEnable::kCalibrationEnabled) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n<h2>Void arguments</h2>\n<p>Whereas <code>(void)</code> is the preferred way of indicating no-argument functions in C, in C++ this is redundant and can simply be <code>()</code> in lines like</p>\n<pre><code>void initialize(void);\n</code></pre>\n<h2>Indentation</h2>\n<p>Consider moving to a more common four-space indentation instead of two.</p>\n<h2>Initialization</h2>\n<p>Having an <code>initialize()</code> method separated from your constructor is somewhat of an anti-pattern in C++. The implication is that between the time that your class is constructed and before it is initialized, it will be in an invalid state. Attempt to eliminate this by doing the work of <code>initialize()</code> in the constructor itself. Since none of your initialization routines seem able to detect failure, this maps easily to a constructor. If you had to indicate failure, either use exceptions - which would guarantee the non-existence of an invalid instance - or less ideally, set a failure flag.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T19:55:02.800",
"Id": "502667",
"Score": "0",
"body": "Thank you very much for your comments. They are very helpful for me but it could be said that they are more or less of cosmetic. I am more interested in your opinion regarding the architecture of the driver. May I ask you for your opinion in this aspect?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T20:01:55.783",
"Id": "502671",
"Score": "1",
"body": "Proper use of `const` is not cosmetic and will have a direct impact on how much you can be assured of program correctness. Otherwise, one more thing in my recent edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T17:34:02.177",
"Id": "254852",
"ParentId": "254850",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T16:45:02.173",
"Id": "254850",
"Score": "2",
"Tags": [
"c++",
"object-oriented",
"embedded",
"device-driver"
],
"Title": "Software driver for analog to digital converter"
}
|
254850
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.