body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I tried to create a "guess the word" game. I would appreciate to get some suggestion to improve myself, because I'm new at Python.</p> <pre><code>from random_word import RandomWords import random from translate import Translator import time import sys def hangman(): SENTINEL = 1 lang = input('What language do you choose?\nit, es, en, etc..\n&gt;: ') while SENTINEL == 1: hints = 3 answers = {'Yes':1, 'No':0} source = RandomWords() word = source.get_random_word() translator= Translator(to_lang = lang) #translates every word to a choosen language itWord = translator.translate(word).lower() print('Hello everybody and Welcome to the hangman game! Try guessing the right word before finishing your possibilities!') time.sleep(1) #I added time sleep just for slowing some parts print('Ready?') time.sleep(1) print('Go') time.sleep(1) lenght = len(itWord) + 1 #get the lenght of the picked word choice = int(lenght*(3/2)) #possibilities depend by the word lenght showIt = '_'*(lenght-1) newIt = show_it(showIt) showIt = list(newIt.split()) #creates a list that can be modified easier choices = [] #creates an empty list that has to be filled with the used letters/words print('The word has lenght', lenght,'.\nYou can call the list of used letters by writing "list", exit from the game by writing "exit", or try to guess the word, by writing first "guess"') print('Write "help" to get some hints: but you have just 3 of it!') while choice &gt;= 1: old = choice #preserves the remained chances time.sleep(1) print('You have', choice, 'possibilities and', hints,'hints. Try it up!\n', newIt) guess = (input('&gt;: ')).lower() if guess == 'help': #help is needed to get hints if hints == 0: print('Sorry, you don\'t have anymore hints') continue else: guess = random.choice(itWord) while guess in newIt: #this is needed to get a letter that was not choosen guess = random.choice(itWord) hints -= 1 #decreases the number of hints if guess in choices: #checks if the guessed letter was not choosen yet print('You\'ve already used this letter/word. Please choose another one') continue else: try: if len(guess) == 1 : if hints == 3 : choices.append(guess) #it adds just the letter guessed by the user and not randomly picked by the game elif guess != 'help' and guess != 'exit' and guess != 'guess' and guess != 'list': raise ValueError except ValueError: print('Please choose a letter, not a word') continue if guess == 'list': #needed to get the list of words/letters used print(choices) time.sleep(1) continue elif guess == 'exit': sys.exit(print('Thanks for the game')) #this closes the game elif guess == 'guess': #this option is for trying guessing the entire word guess = input('&gt;: ') if guess == itWord: #if the word is right it puts choice to 0 to go through the next while loop(But the choice value is preserved in the 'old' variable seen before) newIt = guess print('You did it!') choice = 0 else: #if the word is not right it decreases the possibility print('No way, retry') choice -= 1 continue elif guess in itWord.lower(): #if the guessed letter belongs to the randomly picked word, the program gets the index of the letter in it, the number of it and replaces the guessed letter in the right place of the showIt list index = itWord.index(guess) lettCount = itWord.count(guess) - 1 showIt[index] = guess while lettCount != 0: #if there is more than one guessed letter in the randomly picked word, the program does the same thing as before for all of them index = itWord.index(guess, index +1) showIt[index] = guess lettCount -= 1 newIt = show_it(showIt) else: time.sleep(1) print('Sorry, you wrong. Retry!') choice -= 1 if '_' not in newIt: #This removes all the spaces in newIt newIt = remove_spaces(newIt) print('All right, you found the word!', newIt.lower()) choice = 0 while choice == 0 : #the old variable preserves all remained possibilities. The different answers depends by old value time.sleep(1) if old == 0: print('Sorry, you used all your possibility') time.sleep(1) print('Do you want to restart the game?\n Yes/No') choose = input('&gt;: ').capitalize() #from this point on, the user has the opportunity to restart the game with the previous word(if not guessed) or not, or close it try: SENTINEL = answers[choose] if SENTINEL == 1: print('Do you want to use the previous word?\n Yes/No') choose = input('&gt;: ').capitalize() if choose == 'Yes': choice = int(lenght*(3/2)) choices.clear() elif choose == 'No': choice, SENTINEL = -1, 1 else: SENTINEL, choice = 0, -1 except KeyError: print('Please, insert a correct answer') choice = 0 sys.exit(print('Thanks for the game')) def show_it(word1): #The function creates dashes format like _ _ _ newIt = '' for x in word1: newIt = newIt + x + ' ' newIt = newIt.rstrip(' ') return newIt def remove_spaces(word): string = '' for x in word: if x != ' ': string += x return string </code></pre>
[]
[ { "body": "<p>Few things that I think will help ya in the long run...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>multi_line_string = \"\"\"\nDo you want to use the previous word?\n Yes/No\n\"\"\"\n\n\nprint(multi_line_string)\n</code></pre>\n\n<p>Multi-line strings maybe assigned via triple quote (either <code>\"\"\"</code> or <code>'''</code>) blocks; having the stray apostrophe becomes <em>no big deal</em>. Furthermore one can utilize <code>dedent</code> from <code>textwrap</code> while <em><code>print</code>ing</em> such that the <em>flow</em> isn't broken...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from textwrap import dedent\n\n\nsome_string = \"\"\"\n Sorry, you've used all available possibilities!\n ... taking a nap...\n\"\"\"\n\nprint(dedent(some_string))\n</code></pre>\n\n<p>Functions/Methods (<em><code>def</code>initions</em>) are super useful for repeated snippets of code...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from textwrap import dedent\nfrom translate import Translator\n\n\nto_lang = 'en'\n\ntranslator = None\nif to_lang != 'en':\n translator = Translator(to_lang = to_lang)\n\n\ndef accessibility(msg, **kwargs):\n \"\"\"\n Side note, this is a `__doc__ string` that _documents_\n how something is intended to be used. And is accessible\n via commands such as;\n\n print(accessibility.__doc__)\n help(accessibility)\n\n This is a shortcut for formatting and then translating\n passed `msg` string prior to `return`ing.\n \"\"\"\n if kwargs:\n msg = msg.format(**kwargs)\n\n if translator:\n msg = translator.translate(msg)\n\n return msg\n\n\ndef whats_wanted(msg, **kwargs):\n \"\"\"\n Simple short-cut for getting user input while also\n translating `msg` if necessary.\n \"\"\"\n return input(accessibility(msg, **kwargs))\n\n\n## ... also do __not__ be afraid of blank lines, two between\n## classes and functions, and one between blocks and/or\n## where it makes since to do so is the _rule of thumb_\n## that I use when writing. Also it's a good idea to\n## avoid comment blocks of this length, keep things _tight_\n## and use `__doc__ strings` to avoid feeling the need for'em ;-)\nthe_question = \"Shall we continue {user}?\"\nan_answer = whats_wanted(the_question,\n user = 'yourName here')\n\n\n## ... Note, defaulting instead of else-ing on a single line\n## often looks _cleaner_ when re-reading code later.\nthe_answer = an_answer\nif translator:\n reverse_translator = Translator(to_lang = 'en')\n the_answer = reverse_translator.translate(an_answer)\n\nif the_answer.lower() == 'yes':\n msg = accessibility(\"I think I heard a 'yes' from {user}\",\n user = 'yourName here')\nelse:\n msg = accessibility('What are you talking about?')\n\nprint(msg)\n</code></pre>\n\n<p>The <code>try</code> blocks may need a little rewriting, following is a <em>starting point</em>...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> ## ... Other code trimmed...\n\n if old == 0:\n _msg = \"\"\"\n Sorry, you used all your possibility\n\n Do you want to restart the game?\n Yes/No\n \"\"\"\n print(textwrap.dedent(_msg))\n choose = input('&gt;: ').capitalize()\n\n # from this point on, the user has the opportunity\n # to restart the game with the previous word(if not\n # guessed) or not, or close it\n\n try: ## To do something that may result in an exception\n SENTINEL = answers[choose]\n except KeyError: ## that some errors will occur\n msg = 'Please, insert a correct answer'\n choice = 0\n print(textwrap.dedent(msg))\n else: ## Do things when there was no exceptions\n msg = '''\n Do you want to use the previous word?\n Yes/No\n '''\n print(textwrap.dedent(msg))\n choose = input('&gt;: ').capitalize()\n finally: ## Do things when there where no un-caught exceptions\n if choose == 'Yes':\n choice = int(lenght*(3/2))\n choices.clear()\n elif choose == 'No':\n choice = -1\n SENTINEL = 1\n else:\n choice = -1\n SENTINEL = 0\n\n## ... other stuff...\n</code></pre>\n\n<p>... which'll hopefully expose bugs a bit easier; some will remain hiding though because you've got some formatting issues elsewhere as @Josay already pointed out.</p>\n\n<p>With a little debugging and some tasteful use of abstraction you'll get there, so keep at it and in a few months time your code wont be as much of a danger to sobriety.</p>\n\n<h2>Updates</h2>\n\n<p>Some other bits that sorta <em>stood out</em> to me...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># ... Things such as\nelif guess != 'help' and guess != 'exit' and guess != 'guess' and guess != 'list':\n\n# ... look _neater_ with\nelif guess not in ['help', 'exit', 'guess', 'list']:\n</code></pre>\n\n<p>And things like...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def show_it(word1): \n # The function creates dashes format like _ _ _\n newIt = ''\n for x in word1:\n newIt = newIt + x + ' '\n newIt = newIt.rstrip(' ')\n return newIt\n\ndef remove_spaces(word):\n string = ''\n for x in word:\n if x != ' ':\n string += x\n return string\n</code></pre>\n\n<p>... should be assigned prior to being used, and they may be written in a more <em>shorthand</em> way via...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>remove_spaces = lambda word: word.replace(' ', '')\n\n\ndef show_it(word): \n \"\"\"\n The function creates dashes format like _ _ _\n \"\"\"\n newIt = ' '.join('_' for _ in word)\n return newIt.rstrip(' ')\n</code></pre>\n\n<blockquote>\n <blockquote>\n <p>I don't understand what lambda does. Can you explain me ?</p>\n </blockquote>\n</blockquote>\n\n<p>I can try to explain <code>lambda</code>, when programming their a <em>handy</em> way of writing one-line functions. Borrowing a few examples from a past <a href=\"https://math.stackexchange.com/a/3168091/657433\">iteration</a>...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>edge_cost = lambda base_cost, drivers: base_cost * drivers\n\nedge_cost(base_cost = 0.7, drivers = 2)\n## -&gt; 1.4\n</code></pre>\n\n<ul>\n<li><p><code>lambda base_cost, drivers</code> declares arguments names that maybe used on the other side of the <strong><code>:</code></strong> (colon)</p></li>\n<li><p>what ever is done on the other side of the colon (<code>:</code>) should <code>return</code> something as part of the operations, in this case <code>base_cost * drivers</code></p></li>\n<li><p>and the <code>edge_cost = ...</code> is <code>def</code>ining the name that this operation can be called up with</p></li>\n</ul>\n\n<p>I'll encourage you to try'em out in an active terminal session...</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>user@host ~ $ python\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; remove_spaces = lambda word: word.replace(' ', '')\n&gt;&gt;&gt; remove_spaces(word = 'lamb spam and ham')\n'lambspamandham'\n</code></pre>\n\n<p><code>&gt;&gt;&gt;</code><kbd> Enter </kbd></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; first_class = lambda base_cost: base_cost + 0.5\n&gt;&gt;&gt; business_class = lambda base_cost: base_cost + 0.2\n&gt;&gt;&gt; first_class(0.4)\n0.9\n&gt;&gt;&gt; business_class(0.4)\n0.6\n</code></pre>\n\n<p>One thing to keep in mind when using'em is that their intended to be <strong>functional</strong> in the programming since, so please do not ever do...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>bad_idea = lambda d: [d.update({k: v * 2}) for k, v in d.items()]\n\nsome_data = {'first': 1, 'second': 2, 'third': 3}\nworse_idea = bad_idea(some_data)\n</code></pre>\n\n<p>... because <code>worse_idea</code> will then equal <code>[None, None, None]</code>, nearly useless output, and <code>some_data</code> will have mutated into something like <em><code>{'second': 4, 'third': 6, 'first': 2}</code></em>. This type of usage of <code>lambda</code> will only lead to loss of time (if not hair) during the eventual debugging process.</p>\n\n<p>Another <em>not so good</em> example would be...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>show_it = lambda i: ' '.join('_' for _ in range(0, i))\n</code></pre>\n\n<p>... which'll output <code>_ _ _ _ _</code> via <code>show_it(5)</code>, <strong>but</strong> unless you're changing changing <code>i</code> constantly it's far better to assign a variable that calculates things once...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>show_it = ' '.join('_' for _ in range(0, 5))\n</code></pre>\n\n<p>... Reasons that <code>remove_spaces</code> should be a function and not <code>show_it</code> is wonderfully obvious in this case, in the future figuring out how things should be assigned can be a little <em>murky</em>.</p>\n\n<p>Other than that though their supper useful for simple things that get reused elsewhere, as well as for prototyping because it's less key-strokes to some kind of result... Oh and ya may run across <em>lambda</em> being used in Math (if I remember correctly this is where such ideas originated), and in most cases they'll operate very much the same, however, they're not equivalent so that can sometimes cause <em>troubles</em> when translating from one to the other.</p>\n\n<hr>\n\n<h2>Even more updates</h2>\n\n<p>So I spent a little more time examining your code and other things <em>popped</em> out...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>## ...\n if guess == 'help':\n if hints == 0:\n print('Sorry, you don\\'t have anymore hints')\n continue\n else:\n guess = random.choice(itWord) \n while guess in newIt:\n guess = random.choice(itWord)\n## ...\n</code></pre>\n\n<p>... doesn't need an <code>else</code>, because when the <code>if</code> statement trips <code>continue</code> things <em>move on</em> to the next iteration. Following is a more <em>correct</em> way of expressing your intentions with a computer...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>## ...\n if guess == 'help':\n if hints == 0:\n print(\"Sorry, you don't have anymore hints\")\n continue\n\n guess = random.choice(itWord) \n while guess in newIt:\n guess = random.choice(itWord)\n## ...\n</code></pre>\n\n<p>... with a little editing other places that the code is using <code>continue</code> like this, the amount of tabbing in that's required (AKA <a href=\"https://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow noreferrer\">cyclomatic complexity</a>) could be significantly reduced.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T11:30:30.330", "Id": "428248", "Score": "0", "body": "Thank you. It is really helpful.. But I don't understand what lambda does. Can you explain me ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T21:59:00.177", "Id": "428312", "Score": "1", "body": "Most welcome @RobertaBelladonna and `lambda` is another way to `def`ine a function (an _anonymous_ one in this case) in Python; and some other languages. See the updates for example usage and a few warnings too. Generally I use `lambda` for _short-cuts_ when it doesn't subtract from readability, and/or _labeling_ some kind of transformation or math to be outputed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T15:55:15.563", "Id": "221427", "ParentId": "221414", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T13:18:03.723", "Id": "221414", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "hangman" ], "Title": "Hangman game with Python 3" }
221414
<p>I have tried to develop a simple product listing app in RxSwift with MVVM design pattern. I have managed to achieve it but I need someone to review my code, such as:</p> <ol> <li>Have I followed the proper RxSwift features?</li> <li>Is binding of <code>TableViewCell</code>s item with <code>ViewController</code>'s <code>ViewModel</code> correct?</li> <li>Anything I am missing here?</li> </ol> <p>Note: Also, it is available on <a href="https://github.com/ajaybhanushalid2k/RxSwift_MVVM" rel="nofollow noreferrer">GitHub</a>.</p> <h3>ViewController.swift</h3> <pre><code>// MARK:- View's MVVM Binding Method func configure(with viewModel: ViewModelType) { // DataSource implementation let dataSource = RxTableViewSectionedReloadDataSource&lt;SectionOfProducts&gt;( configureCell: { dataSource, tableView, indexPath, item in let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell", for: indexPath) as! ProductCell cell.prepareCell(with: item) // Binding Cell item with viewModel's input cell.buttonLike.rx.tap .map{_ in item} .bind(to: self.viewModel.input.likedProduct) .disposed(by: cell.disposeBag) return cell }) self.dataSource = dataSource // Binding reachedBottom trigger with viewModel's input for pagination of products tableViewProducts.rx.reachedBottom.asObservable() .bind(to: viewModel.input.nextPageTrigger) .disposed(by: disposeBag) // Bind refresh control to viewModel refreshControl.rx.controlEvent(.valueChanged) .bind(to: self.viewModel.input.refreshTrigger) .disposed(by: disposeBag) // Binding viewModel's output's products with tableview items viewModel.output.products.asObservable() .bind(to: tableViewProducts.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) } </code></pre> <h3>ViewModel.swift</h3> <pre><code>class ProductsViewModel: ViewModelProtocol { // Input consists of user inputs such as like any product, pull to refresh and get data for next page struct Input { let likedProduct: AnyObserver&lt;ProductModel&gt; let refreshTrigger: AnyObserver&lt;Void&gt; let nextPageTrigger: AnyObserver&lt;Void&gt; } // products are provided as output show on ViewController struct Output { let products: Driver&lt;[SectionOfProducts]&gt; } let input: Input let output: Output private let disposeBag = DisposeBag() private let likedProductSubject = PublishSubject&lt;ProductModel&gt;() private let refreshTriggerSubject = PublishSubject&lt;Void&gt;() private let loadAfterTriggerSubject = PublishSubject&lt;Void&gt;() init(_ interactor: ProductsInteractorProtocol) { // Init Output input = Input(likedProduct: likedProductSubject.asObserver(), refreshTrigger: refreshTriggerSubject.asObserver(), nextPageTrigger: loadAfterTriggerSubject.asObserver()) //&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; Please review my code from here // When ViewModel initializes products are requested from the Interactor var products = interactor.getProducts() // Detect when like button is tapped in the ViewController's tableView's cell likedProductSubject.subscribe ({ (event) in print("\(String(describing: event.element?.productName))") }).disposed(by: disposeBag) // To get next gage data I have used danielt1263/PaginationNetworkLogic.swift: Link: https://gist.github.com/danielt1263/10bc5eb821c752ad45f281c6f4e3034b let source = PaginationUISource(refresh: refreshTriggerSubject.asObservable(), loadNextPage: loadAfterTriggerSubject.asObservable(), bag: disposeBag) let sink = PaginationSink(ui: source, loadData: interactor.getNextProducts(page:)) // Concat new products with the previous products let newProducts = sink.elements.asObservable() products = Observable.concat([products, newProducts]).scan([], accumulator: +) //&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; Till here // Init Output output = Output(products: products.asDriver(onErrorJustReturn: [])) } } </code></pre> <h3>ProductsInteractor.swift</h3> <pre><code>final class ProductsInteractor: ProductsInteractorProtocol { var nextURLString: String? /// Sending a post request to get products /// /// - Returns: Array structured according to RxDataSources requirement func getProducts() -&gt; Observable&lt;[SectionOfProducts]&gt; { var products: [ProductModel]? let requestData = ProductsRQM(categoryId: 0, subCategoryId: 0, typeId: 0, customerId: "11") return Observable.create { [weak self] (observer) -&gt; Disposable in APIRequests.shared.post(requestModel: requestData, requestPath: .requestProducts) { (error, data) in let jsonDecoder = JSONDecoder() let responseModel = try? jsonDecoder.decode(ProductsBase.self, from: data!) // Products from the api are stored in products variable products = responseModel?.data?.item self?.nextURLString = responseModel?.data?.links?[0].href let section = [SectionOfProducts(header: "", items: products ?? [])] observer.onNext(section) observer.onCompleted() } return Disposables.create {} } } /// Sending a get request to get products /// /// - Returns: Array structured according to RxDataSources requirement func getNextProducts(page: Int) -&gt; Observable&lt;[SectionOfProducts]&gt; { var products: [ProductModel]? return Observable.create { [weak self] (observer) -&gt; Disposable in if self?.nextURLString != nil { APIRequests.shared.get(requestURL: self?.nextURLString ?? "", callBack: { (error, data) in let jsonDecoder = JSONDecoder() let responseModel = try? jsonDecoder.decode(ProductsBase.self, from: data!) // Products from the api are stored in products variable products = responseModel?.data?.item // If true then nextPage is available else not if responseModel?.data?.links?[0].rel != "previousPage" { self?.nextURLString = responseModel?.data?.links?[0].href } else { // Else assigning nextURLString to nil to prevent unnecessary api call self?.nextURLString = nil } let section = [SectionOfProducts(header: "", items: products ?? [])] observer.onNext(section) observer.onCompleted() }) } return Disposables.create {} } } } </code></pre>
[]
[ { "body": "<p>This is a good first attempt and a lot of good can be said about it, but I'm going to focus on what I see are problems that should be fixed. Don't let this dissuade you though!</p>\n\n<ul>\n<li><p><code>ControllerType</code> and <code>ViewModelProtocol</code> are completely useless. If you aren't going to use them to constrain some generic function then get rid of them.</p></li>\n<li><p>Your <code>APIRequests.get(requestURL:callBack:)</code> doesn't call the callBack if the requestURL can't be used to create a <code>URL</code>. This will cause silent errors. In general, make sure that all possible paths call the callBack when you are making async functions. Also, <code>RxCocoa</code> has a couple of wrappers around <code>dataTask</code>. I suggest you use them in your <code>APIRequests</code> class.</p></li>\n<li><p><code>APIRequests</code> is a class with no state. This is pointless. Move the functions out of the class and get rid of it.</p></li>\n<li><p><code>ProductsInteractor.nextURLString</code> is Optional. There is no point in making Strings optional. An empty string is the same as no string.</p></li>\n<li><p><code>APIRequest</code> doesn't need to be a protocol; it's just a data bucket. Make it a <code>struct</code> and adjust other code as necessary.</p></li>\n<li><p>Regarding <code>ProductsViewModel</code>: I'm not a fan of this style of view model; It seems like a lot of boilerplate to me. In any case, you should have unit tests for it.</p></li>\n<li><p>Your <code>ProductsInteractor.getProducts()</code> and <code>ProductsInteractor.getNextProducts(page:)</code> functions only emit if the network request was successful, they never emit errors and if <code>self?.nextURLString == nil</code> then <code>getNextProducts(page:)</code> doesn't emit anything at all. In general, make sure that all possible paths through the block of an Observable.create all call the observer.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:39:51.600", "Id": "221435", "ParentId": "221417", "Score": "1" } } ]
{ "AcceptedAnswerId": "221435", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T14:00:08.450", "Id": "221417", "Score": "3", "Tags": [ "swift", "mvvm", "pagination", "rx-swift" ], "Title": "Create Products TableView with PAGINATION and LIKE product feature in RxSwift MVVM" }
221417
<p>I've written a function in Haskell for calculating the entropy of a collection. I'd like feedback on how the function could be rewritten to be more flexible/reusable, and also how to profile the function and how it could be tuned and/or modified for better performance.</p> <pre class="lang-hs prettyprint-override"><code>import Data.List (foldl1') entropy :: [Int] -&gt; Int -&gt; Int -&gt; Double entropy itemFrequencies totalElements logarithmicBase = -(foldl1' (+) $ map (\p -&gt; p * (logBase b p)) probabilities) where is = map fromIntegral itemFrequencies l = fromIntegral totalElements b = fromIntegral logarithmicBase probabilities = map (\i -&gt; i / l) $ is </code></pre> <p>For some background, the Entropy calculation is a core function used in building decision trees. For more complex datasets and decision trees, this function would get called very often. I'm working on a sequential implementation of the ID3 algorithm, which this entropy function is a part of, that I will later make parallel/concurrent as a separate exercise, and then I will eventually also write implementations of ID3's descendants: C4.5 and C5.0.</p> <p>Please respect my desire to struggle on my own with the concurrency/parallelism aspect of rewriting this code, I'm only interested in any sequential improvements I could make for performance and any refactoring that could be done to make this code easier to maintain and reuse.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-09T22:03:49.903", "Id": "429506", "Score": "0", "body": "Since it's been a week, I'm going to go ahead and select cole's answer, even though I would have liked for someone to have provided an answer that made an attempt at looking at the potential performance improvements." } ]
[ { "body": "<h1>General Code Review</h1>\n\n<p>First, your function and my proposed changes (<code>entropy'</code>) side-by-side.</p>\n\n<pre class=\"lang-hs prettyprint-override\"><code>import Data.List (foldl1', foldl')\n\nentropy :: [Int] -&gt; Int -&gt; Int -&gt; Double\nentropy itemFrequencies totalElements logarithmicBase =\n -(foldl1' (+) $ map (\\p -&gt; p * (logBase b p)) probabilities)\n where\n is = map fromIntegral itemFrequencies\n l = fromIntegral totalElements\n b = fromIntegral logarithmicBase\n probabilities = map (\\i -&gt; i / l) $ is\n\nentropy' :: (Foldable f, Integral a, Floating b) =&gt; a -&gt; a -&gt; f a -&gt; b\nentropy' totalElems base =\n negate . foldl' (\\ent f2 -&gt; ent + freqEntropy f2) 0\n where\n freqEntropy f = let p = (fromIntegral f) / l\n in p * logBase b p\n l = fromIntegral totalElems\n b = fromIntegral base\n</code></pre>\n\n<p>My comments, in an arbitrary order:</p>\n\n<ol>\n<li>Why are you using <code>foldl1'</code>? It makes sense to use <code>foldl'</code> from a performance perspective, but it isn't clear to me why you require a nonempty list. Perhaps use a <code>Maybe</code> to encapsulate this possibility of failure, or outline why you expect a nonempty list in a comment. It's a good idea to keep tabs on where your partial functions are to avoid surprises at runtime. My function just returns 0 for a null <code>Foldable</code>.</li>\n<li>Your types can be generalized more than <code>Int</code> and <code>Double</code>, if you want this to be more flexible/reusable. What I did to find these types was track down what functions you were using and figure out what their types were (which were more general than <code>Int</code> or <code>Double</code> or <code>[]</code>). Then I resolved the overall function to its most general type. Whether this is necessary or useful depends on your application. I think the most useful generalization here is to <code>Foldable</code> in case you wanted to calculate entropy of things that were not lists.</li>\n<li>When I changed to generalize to <code>Foldable</code>, I rolled all of the <code>map</code>s into the <code>foldl'</code>. This may be more performant if the compiler doesn't combine <code>map</code>s, but it's also a tad bit more complicated to understand.</li>\n<li>I moved the <code>itemFrequencies</code> to be the last argument so I could write the function pointfree. Pointfree is kind of cute, but if you think it's more readable you can change the order and/or put the explicit <code>itemFrequencies</code> back in.</li>\n<li>I added an explicit call to <code>negate</code> (I didn't get what was going on at first with the <code>-(foldl1' ...)</code>).</li>\n<li>I shortened the names so that things are not overwhelmingly long or verbose. This is just my personal taste. I think if you're going to have descriptively long variable names, you shouldn't skimp on the description for your temporary variables. I think <code>b</code> is OK since it's a common variable for base, but I would recommend using something like <code>len</code> instead of <code>l</code> and <code>itemFreqs'</code> instead of <code>is</code>.</li>\n</ol>\n\n<h1>Performance and Profiling</h1>\n\n<p>I can't really help you on this front. GHC does have a <a href=\"https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/profiling.html\" rel=\"nofollow noreferrer\">profiler</a>, which might be useful if you want to do some serious profiling.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T22:51:25.513", "Id": "428626", "Score": "1", "body": "I thought about and researched this for a while, and I'm not sure what it means to calculate the entropy of a set with no items, or none of the items you're asking about... On the one hand, you could say, the probability of choosing something that isn't in the set is 0, and so the entropy must be 0. On the other hand, I could also see the argument for infinity or undefined since division by 0 (which you would have to do in a set of 0 items to get the probability) is undefined. That's why I'm not permitting an empty list of itemFrequencies: entropy doesn't make sense for null sets." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T22:26:52.507", "Id": "221511", "ParentId": "221418", "Score": "2" } } ]
{ "AcceptedAnswerId": "221511", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T14:00:47.960", "Id": "221418", "Score": "4", "Tags": [ "performance", "haskell", "statistics" ], "Title": "Entropy calculation function in Haskell" }
221418
<p>I'm trying to take camelCase and PascalCase strings into a function and spit them out as Title Case. This function also needs to be able to handle odd PascalCase strings with capitalized abbreviations such as "CDReceiverBox" and return a readable string - "CD Receiver Box". </p> <p>My current working solution:</p> <pre><code>function splitCamelCase(camelCaseString) { const result = camelCaseString .replace(/([A-Z][a-z])/g, " $1") .replace(/([A-Z]+)/g, " $1") .replace(/ +/g, " ") .replace(/^ +/g, ""); return result.charAt(0).toUpperCase() + result.slice(1); } </code></pre> <p>I would like to condense the amount of replace statements I'm using by at least combining the first two replace statements and the last two together since they are semi similar. The more concise I can make this the better.</p> <p>CodePen: <a href="https://codepen.io/andrewgarrison/pen/dEQrMy" rel="noreferrer">https://codepen.io/andrewgarrison/pen/dEQrMy</a></p>
[]
[ { "body": "<p>You could save one <code>.replace()</code> call by replacing the last two with:</p>\n\n<pre><code>.replace(/(^| ) +/g, \"$1\")\n</code></pre>\n\n<p>which both removes leading spaces and collapses multiple consecutive spaces to one anywhere else in the string. However, I'm not 100% sure that you <em>should</em>, since it's not really clear which way is more efficient in practice, and your way seems more readable anyway.</p>\n\n<p>If you do keep the two calls separate, however, you should optimize the first regexp to <code>/ +/g</code> (with two spaces before to <code>+</code> sign) or <code>/ {2,}/g</code> (which means \"two or more spaces\"), to avoid unnecessarily matching and replacing single spaces. Also, swapping the order of the last two calls could improve performance slightly in cases where the only extra spaces to be removed are at the beginning of the string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T15:04:47.900", "Id": "221422", "ParentId": "221419", "Score": "8" } }, { "body": "<p>I like your solution quite a bit. It's clear, easy to read and I don't see any bugs. </p>\n\n<p>There are many ways to condense the <code>replace</code> calls as you mention, but I think you're at a point where such changes can easily have a disproportionate impact on readability. That's good--it means the code is already pretty optimal from that standpoint.</p>\n\n<p>For example, here's a one-shot <code>replace</code> using alternation, but its merit is debatable:</p>\n\n<pre><code>const splitCamelCase = s =&gt; s.replace(\n /^[a-z]|^([A-Z]+)(?=[A-Z]|$)|([A-Z])+(?=[A-Z]|$)|([A-Z])(?=[a-z]+)/g,\n m =&gt; \" \" + m.toUpperCase()\n ).trim()\n;\n</code></pre>\n\n<p>The idea here is to enumerate each scenario, join the patterns with <code>|</code>s, and provide an arrow function to handle the addition of a space and a capital letter for each match.</p>\n\n<p>With the two extremes in mind, I prefer a balanced approach such as:</p>\n\n<pre><code>const splitCamelCase = s =&gt;\n s.replace(/([A-Z][a-z])/g, \" $1\")\n .replace(/\\s*([A-Z]+)/g, \" $1\")\n .replace(/./, m =&gt; m.toUpperCase())\n .trim()\n;\n</code></pre>\n\n<p>or perhaps</p>\n\n<pre><code>const splitCamelCase = s =&gt;\n s.replace(/([A-Z][a-z]|[A-Z]+(?=[A-Z]|$))/g, \" $1\")\n .replace(/./, m =&gt; m.toUpperCase())\n .trim()\n;\n</code></pre>\n\n<p>These should offer ideas as far as how far you want to go in making the succinctness versus readability tradeoff. But, failing the possibility of a shortcut I might have overlooked, keeping your code basically as-is seems like a fine option to me.</p>\n\n<p>If it's performance you're after in reducing <code>replace</code> calls, there's no guarantee that fewer calls will translate into better performance. Under the hood, the regex engine may make more passes to compensate; you can benchmark and tweak using a debugger like <a href=\"https://regex101.com/\" rel=\"noreferrer\">regex101</a>. For performance, it's likely best to avoid regex entirely and write a single-pass loop by hand.</p>\n\n<p>Here's a test runner:</p>\n\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 splitCamelCase = s =&gt;\n s.replace(/([A-Z][a-z]|[A-Z]+(?=[A-Z]|$))/g, \" $1\")\n .replace(/./, m =&gt; m.toUpperCase())\n .trim()\n;\n\n[\n \"AAABbbbbCcDddEEFffGGHhIiJ\",\n \"AaBbCcDDEeFGgHHHH\",\n \"CDBoomBoxAAAABbbbCCC\",\n \"CDBoomBox\",\n \"camelCase\",\n \"camel\",\n \"Camel\",\n \"c\",\n \"C\",\n \"Aa\",\n \"AA\",\n \"aa\",\n \"AAA\",\n \"aB\", \n \"aBC\",\n \"aBCc\",\n \"\",\n].forEach(test =&gt; \n console.log(\n splitCamelCaseOriginal(test) === splitCamelCase(test) \n ? `'${test}' -&gt; '${splitCamelCase(test)}'` \n : \"TEST FAILED\"\n )\n);\n\nfunction splitCamelCaseOriginal(camelCaseString) {\n const result = camelCaseString\n .replace(/([A-Z][a-z])/g, \" $1\")\n .replace(/([A-Z]+)/g, \" $1\")\n .replace(/ +/g, \" \")\n .replace(/^ +/g, \"\");\n\n return result.charAt(0).toUpperCase() + result.slice(1);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T18:20:00.197", "Id": "428199", "Score": "0", "body": "FWIW, your code gives different results from the OP's for inputs like `aB`, `aBC` or `aBCd` that start with a lowercase letter followed by an uppercase letter. That's the one situation where it matters whether you capitalize the first letter before or after adding the spaces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T19:08:00.460", "Id": "428202", "Score": "1", "body": "Good catch, fixed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:24:26.680", "Id": "221431", "ParentId": "221419", "Score": "11" } } ]
{ "AcceptedAnswerId": "221431", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T14:24:36.860", "Id": "221419", "Score": "16", "Tags": [ "javascript", "strings", "regex" ], "Title": "Convert camelCase and PascalCase to Title Case" }
221419
<p><strong>Background:</strong></p> <p>For several of my workbooks I run Overview sheets with charts in them. When printing the Overview sheet, I put my workbook name as header, where the workbook name includes the criteria for the generating the source data (e.g., date range and time stamp plus non-numeric strings).</p> <p>To draw attention to these numbers/dates/times, I can manually highlight on the print out, but when others print (using a button on the Overview sheet) they don't seem to remember to do that. </p> <p>I am looking to add some "flare" to my header by underlining the numeric values.</p> <hr> <p><strong>Issue:</strong></p> <p>The workbook name character length varies, so I assess character by character. In some cases the code executes after a delay (time varies, but will say that I had a 60 character length name take ~30 seconds), and other times Excel simply doesn't complete execution after several minutes (i will press escape and get the "code execution has been interupted" msgbox; this recently happened for a 48 character name).</p> <hr> <p><strong>Question:</strong></p> <p>As this is working code (sometimes), would you please help critique and possibly help resolve the time delay?</p> <p>If my approach is inferior, I am open to suggestions, though I understand that, from my time on StackOverflow, subjective questions tend to be closed.</p> <hr> <p><strong>Code in question:</strong></p> <pre><code>Option Explicit Sub underline_numbers_in_header() Dim i As Long, n As String, z As String n = ActiveWorkbook.Name 'Debug.Print Len(n) For i = 1 To Len(n) If IsNumeric(Mid(n, i, 1)) Then z = z &amp; "&amp;U" &amp; Mid(n, i, 1) &amp; "&amp;U" Else z = z &amp; Mid(n, i, 1) End If ActiveSheet.PageSetup.CenterHeader = "" &amp; z &amp; "" Next i End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T15:18:22.820", "Id": "428168", "Score": "0", "body": "\"Code execution was interrupted\" sounds like some ghost breakpoint - a VBE bug, nothing to do with your code. Try exporting the module and re-importing it again, then recompile the project." } ]
[ { "body": "<blockquote>\n<pre><code>ActiveSheet.PageSetup.CenterHeader = \"\" &amp; z &amp; \"\"\n</code></pre>\n</blockquote>\n\n<p>There's no reason to run this instruction at every single iteration as <code>z</code> is still in the process of being concatenated, is there?</p>\n\n<p>Move it out of the loop and assign <code>PageSetup.CenterHeader</code> <em>once</em>, only when you've figured out the entire final string value - this could have a dramatically positive impact on performance :)</p>\n\n<p>The name of the procedure/macro should not have underscores in it; convention is to use <code>PascalCase</code> for procedure/member names.</p>\n\n<p>The procedure is <em>implicitly</em> <code>Public</code> and could use an explicit access modifier.</p>\n\n<p>Reading the name of the procedure I was expecting it to go through page headers and underline whatever numeric values are in there... but that's not what's happening, and the variable names aren't helping much. Take the time to spell them out, and thank yourself later!</p>\n\n<p>That said I'd suggest taking in a <code>Workbook</code> parameter and removing the <code>ActiveWorkbook</code> and <code>ActiveSheet</code> dependencies, which force any VBA code calling this procedure to <code>Select</code> and <code>Activate</code> things, which as you know isn't ideal.</p>\n\n<p>Actually, the procedure has too many responsibilities, that's why its name feels wrong. It should be a function that takes a <code>String</code> argument and <em>returns</em> the formatted string: that's what I would expect a \"make numbers underline\" procedure to do. Then another procedure can be responsible for knowing what worksheet to interact with, and for setting its <code>PageSetup.CenterHeader</code>:</p>\n\n<pre><code>Dim headerText As String\nheaderText = UnderlineNumbers(ActiveWorkbook.Name)\nActiveSheet.PageSetup.CenterHeader = headerText\n</code></pre>\n\n<p>The string-valued <code>Mid$</code> function should work slightly better than the similar but variant-valued <code>Mid</code> function, and when the current character is being pulled from the string in 3 places, it's time to introduce a local variable ;-)</p>\n\n<p>This should be pretty much instant:</p>\n\n<pre><code>Private Function UnderlineNumbers(ByVal value As String) As String\n Dim result As String\n Dim i As Long\n For i = 1 To Len(value)\n Dim current As String\n current = Mid$(value, i, 1)\n If IsNumeric(current) Then\n result = result &amp; \"&amp;U\" &amp; current &amp; \"&amp;U\"\n Else\n result = result &amp; current\n End If\n Next\n UnderlineNumbers = result\nEnd Function\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:04:31.193", "Id": "428174", "Score": "0", "body": "...i left the append inside my loop... i thoguht I just verified i didn't do that and here we stand (literally the point of building z inside the loop). That alone appears to have resolved most of my issue by moving it out side of the `Next i`. Now, to look at the suggestions... I didn't know about `mid$` so that is something else to read-up on. Thanks for the thoroughly explained response! I'll work to implement the more superior code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:06:03.877", "Id": "428175", "Score": "0", "body": "@Cyril FYI Rubberduck flags uses of `Mid` with [UntypedFunctionUsage](http://rubberduckvba.com/Inspections/Details/UntypedFunctionUsage) inspection results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:08:13.443", "Id": "428176", "Score": "0", "body": "When I used to join you folks in chat as you were working through some early dev stuffs I attempted to download and use RubberDuck, but I had some... difficulties (management approval and authorization on the work comps). May try it again, as they have given me more admin rites and the sort due to some of my projects" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:08:59.967", "Id": "428177", "Score": "0", "body": "It doesn't require any admin rights to install anymore, and you can register it per-user now =)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T15:29:49.830", "Id": "221425", "ParentId": "221420", "Score": "2" } } ]
{ "AcceptedAnswerId": "221425", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T14:46:44.433", "Id": "221420", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "VBA code to underline numbers in the header takes significant time and sometimes crashes excel" }
221420
<p>I've created a generic try catch I can apply throughout my code so I'm not repeating myself.</p> <pre><code>private HttpResponseMessage TryCatch(Action action) { return TryCatch(() =&gt; { action(); return "ActionToFunc"; }); } private HttpResponseMessage TryCatch&lt;T&gt;(Func&lt;T&gt; func) { try { var result = func(); if (result.ToString() == "ActionToFunc") { return Request.CreateResponse(HttpStatusCode.OK); } return Request.CreateResponse(HttpStatusCode.OK, result); } catch (ArgumentNullException) { return Request.CreateResponse(HttpStatusCode.NotFound); } catch (Exception ex) { return Request.CreateResponse(HttpStatusCode.InternalServerError); } } </code></pre> <p>I can call it using:</p> <pre><code>TryCatch(() =&gt; myFunction(parameter)); </code></pre> <p>Is there a better way of doing achieving the same result?</p>
[]
[ { "body": "<p>Try to avoid using magic values. This one is a hack to avoid writing 2 methods.</p>\n\n<blockquote>\n<pre><code>private HttpResponseMessage TryCatch(Action action)\n{\n return TryCatch(() =&gt; { action(); return \"ActionToFunc\"; });\n}\n</code></pre>\n</blockquote>\n\n<p>You are better of splitting your methods. Dispatch error handling to its own method <code>ResolveStatusCode</code> to avoid boiler-plate error handling. In addition, perform argument checks. Since your method is <code>private</code>, I would favor <code>Debug.Assert</code> over <code>ArgumentNullException</code>.</p>\n\n<pre><code> HttpResponseMessage TryCatch(Action operation)\n {\n try\n {\n Debug.Assert(operation != null, \"invalid usage of API\");\n operation();\n return Request.CreateResponse(HttpStatusCode.OK);\n }\n catch (Exception error)\n {\n return Request.CreateResponse(ResolveStatusCode(error));\n }\n }\n\n HttpResponseMessage TryCatch&lt;T&gt;(Func&lt;T&gt; func)\n {\n try\n {\n Debug.Assert(func != null, \"invalid usage of API\");\n var result = func();\n return Request.CreateResponse(HttpStatusCode.OK, result);\n }\n catch (Exception error)\n {\n return Request.CreateResponse(ResolveStatusCode(error));\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T08:41:41.380", "Id": "428511", "Score": "0", "body": "Thanks for your suggestion. I think you're right, this is definitely the way to go. Thanks for introducing me to Debug.Assert() as well, it's something I haven't seen before and will be looking into." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T18:56:29.930", "Id": "221440", "ParentId": "221424", "Score": "3" } }, { "body": "<p>I want to start off by saying <a href=\"https://codereview.stackexchange.com/a/221440/52662\">dfhwze</a> is the correct answer. </p>\n\n<p>I just wanted to touch more on the magic string \"ActionToFunc\". Sometimes, especially with functional programming, you need to convert an Action to a Func&lt;>. I would copy what is already proven and working by borrowing from F# and Rx and create a Unit struct</p>\n\n<p>Here is documentation on F# about Unit \n<a href=\"https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/unit-type\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/unit-type</a></p>\n\n<p>and Rx info on Unit \n<a href=\"https://docs.microsoft.com/en-us/previous-versions/dotnet/reactive-extensions/hh211727(v%3Dvs.103)\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/previous-versions/dotnet/reactive-extensions/hh211727(v%3Dvs.103)</a></p>\n\n<p>Both state Unit Struct Represents void. </p>\n\n<p>And here is the Rx source code for Unit, in case you don't want to add Rx just for a struct.</p>\n\n<p><a href=\"https://github.com/dotnet/reactive/blob/f71f2d62fcec2eb44ca6eaced3b58b21e0372076/AsyncRx.NET/System.Reactive.Shared/System/Reactive/Unit.cs\" rel=\"nofollow noreferrer\">https://github.com/dotnet/reactive/blob/f71f2d62fcec2eb44ca6eaced3b58b21e0372076/AsyncRx.NET/System.Reactive.Shared/System/Reactive/Unit.cs</a></p>\n\n<p><em>Repeat</em> this isn't the case for it but for example instead of magic string would have done</p>\n\n<pre><code>if (result == Unit.Default) // Treat this as a void method\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T19:45:04.597", "Id": "221445", "ParentId": "221424", "Score": "2" } } ]
{ "AcceptedAnswerId": "221440", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T15:26:40.870", "Id": "221424", "Score": "3", "Tags": [ "c#", "error-handling", "generics", "http" ], "Title": "Generic function that accepts both Actions and Func's as parameters" }
221424
<p>Problem: <a href="https://www.hackerrank.com/challenges/the-birthday-bar/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/the-birthday-bar/problem</a> </p> <p>Lily has a chocolate bar that she wants to share it with Ron for his birthday. Each of the squares has an integer on it. She decides to share a <strong>contiguous</strong> segment of the bar selected such that the length of the segment matches Ron's birth <strong>month</strong> and the sum of the integers on the squares is equal to his birth <strong>day</strong>. You must determine how many ways she can divide the chocolate.</p> <p>Function Description</p> <p>It should return an integer denoting the number of ways Lily can divide the chocolate bar.</p> <p>s: an array of integers, the numbers on each of the squares of chocolate d: an integer, Ron's birth day m: an integer, Ron's birth month</p> <p>Print an integer denoting the total number of ways that Lily can portion her chocolate bar to share with Ron.</p> <p>Example: Lily wants to give Ron m =2 squares summing to d = 3. The following two segments meet the criteria:</p> <p><a href="https://i.stack.imgur.com/rQIYW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rQIYW.png" alt="enter image description here"></a></p> <p>Here is my brute force solution that enumerates all possibilities:</p> <pre><code>// Complete the birthday function below. static int birthday(List&lt;int&gt; s, int d, int m) { int n = 0; for(int i = 0; i &lt; s.Count; i++) { if(s.Skip(i).Take(m).Sum() == d) n++; } return n; } </code></pre> <p>Question: any non brute-force solutions to this problem?</p>
[]
[ { "body": "<p>You basically always need to use brute force here. There is no other way. However, you can do it a bit more efficiently.</p>\n\n<p>You're redoing the whole summation in every step of the loop. You don't need to. You can compute the total with one subtraction and one addition in each step of the loop. Like this:</p>\n\n<pre><code>static int birthday(List&lt;int&gt; s, int d, int m) {\n int n = 0;\n int t = s.Take(m).Sum();\n for(int i = 1; i &lt; s.Count - m; i++) {\n if (t == d) n++;\n t = t - s[i - 1] + s[i + m];\n }\n return n;\n}\n</code></pre>\n\n<p>I hope this makes sense, I never write C#. I got here because of your 'javascript' tag. The code might not work correctly, <em>it is untested</em>, but I hope you understand the intention.</p>\n\n<p>However, I do think there's <strong>a bug</strong> in your code. You loop over the whole list, all the way to the end, where you cannot take <code>m</code> squares anymore. The <code>sum()</code> there might result in unexpected matches.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:32:06.033", "Id": "428181", "Score": "0", "body": "int t = s.Skip(0).Take(m).Sum(); <-- should this be s.Take(m).Sum()?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:33:17.337", "Id": "428182", "Score": "0", "body": "You are correct. Some debate here, lol. https://stackoverflow.com/questions/56398235/non-brute-force-algorithm-for-birthday-chocolate-problem" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:36:31.907", "Id": "428183", "Score": "0", "body": "I don't know whether to remove `Skip(0)` or not, but the intention is to take the first `m` squares from the choclate bar. I'll remove it, it does seem superfluous." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:37:44.583", "Id": "428184", "Score": "0", "body": "skip(0) means to skip the first 0 element, which turns out to skip nothing, :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:38:41.733", "Id": "428186", "Score": "0", "body": "Yes, that's what I thought. Can't do any harm, but is not needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:07:15.963", "Id": "428271", "Score": "0", "body": "LINQ is awesome, but we need to be carful not to depend on it too much. +1 for thinking about using a moving sum." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:25:41.590", "Id": "221432", "ParentId": "221429", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T15:59:49.287", "Id": "221429", "Score": "3", "Tags": [ "c#", "javascript", "algorithm", "linq" ], "Title": "Non brute force algorithm for Birthday Chocolate" }
221429
<p>I came across a <a href="https://leetcode.com/problems/contains-duplicate/" rel="nofollow noreferrer">problem on LeetCode</a>. There is an input array of integers. I need to find out if there any repeating integers, then return true else false. So, I tried using <a href="http://troydhanson.github.io/uthash/userguide.html" rel="nofollow noreferrer">a hashtable library available in C</a> and wrote the code below. My run time is approximately 44ms.</p> <ol> <li>How can I optimize this code?</li> <li>Using hashtable, can I improve the logic further?</li> </ol> <pre><code>struct hash { int key; int value; UT_hash_handle hh; }; struct hash *hashtable = NULL; void addToHash(int key, int value) { struct hash *map; //I am using the array elements as hash keys HASH_FIND_INT(hashtable, &amp;key, map); if(map == NULL) { map = (struct hash*)malloc(sizeof(struct hash)); map-&gt;key = key; HASH_ADD_INT(hashtable, key, map); } map-&gt;value = value; } struct hash *findInHash(int key) { struct hash *h; HASH_FIND_INT(hashtable, &amp;key, h); return h; } bool containsDuplicate(int* nums, int numsSize) { struct hash *hPtr; int target = 0; hashtable = NULL; if((numsSize &lt;= 1) || (nums == 0)) return false; int i, index1 = 0; for(i = 0; i &lt; numsSize; i++) { /*The below statement will look if the key is already present in the hashtable*/ hPtr = findInHash(*(nums + i) - target); /*If the key is found already, then it look for the value of that key. If the value and the current array element is same, then a duplicate exist*/ if(hPtr &amp;&amp; hPtr-&gt;key == *(nums+i)) return true; addToHash(*(nums + i), i); } struct hash *temp; HASH_ITER(hh, hashtable, hPtr, temp) {free(hPtr);} return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T18:57:53.300", "Id": "428296", "Score": "2", "body": "\"How can I optimize this code?\" be specific. optimize for speed, memory usage, code footprint, clarity, ...?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T20:36:53.623", "Id": "428300", "Score": "0", "body": "Optimize for speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T06:09:17.093", "Id": "428333", "Score": "1", "body": "I'm assuming `HASH_FIND_INT`, `HASH_ITER` are library calls. But did you copy and paste the entire library source code into the Leetcode text input? Surely, this is bringing a gun to a knife fight. There are numerous `qsort` solutions that run 12ms with just a few lines of code. I don't think Leetcode runs enough tests for speed to matter on this challenge. Also, if you're using someone's library as a client, you're pretty much tied down to their implementation. More clarification about what you're trying to achieve would be helpful here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T23:07:19.063", "Id": "428471", "Score": "0", "body": "@ggorlen, not really. Leetcode suggests programmers to use that library for hashtable. I know we can solve this with qsort. But since i am learning hashtables, I want to know how else can I optimize this code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T23:49:45.440", "Id": "428476", "Score": "1", "body": "How does this teach you about hash tables? You loaded the library, called their functions and it works--there's no hashing algorithm here. All of the potential for optimization is in the library code that's not included in this post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T23:53:22.240", "Id": "428477", "Score": "0", "body": "My first step it learn how to use an existing thing. Currently, I am writing my own hash table as well which I will post here for review this week. Before that I want to get clarity with few questions about using an existing one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T14:10:51.280", "Id": "428542", "Score": "1", "body": "As @ggorlen mentioned a hash table will be overkill for this solution. Since a hash table will involve allocating small bits of memory many times it is also not going to perform as well as something using an array possibly created by `calloc()` once. Each time the algorithm adds a node it will call a system routine to allocate the memory to the process, that means the program itself will be swapped out while the memory is being allocated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T14:13:58.637", "Id": "428543", "Score": "4", "body": "You can improve this question by including the description of the problem statement from LeetCode and including the hash table functions, currently there isn't enough code here to review." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:17:05.590", "Id": "221430", "Score": "5", "Tags": [ "performance", "c", "programming-challenge", "hash-map" ], "Title": "Finding duplicates in an array using C" }
221430
<p>This is a <a href="https://leetcode.com/problems/k-similar-strings/" rel="nofollow noreferrer">Leetcode problem</a> -</p> <blockquote> <p><em>Strings <code>A</code> and <code>B</code> are <code>K</code>-similar (for some non-negative integer <code>K</code>) if we can swap the positions of two letters in <code>A</code> exactly <code>K</code> times so that the resulting string equals <code>B</code>.</em></p> <p><em>Given two anagrams <code>A</code> and <code>B</code>, return the smallest <code>K</code> for which <code>A</code> and <code>B</code> are <code>K</code>-similar.</em></p> <p><strong><em>Note -</em></strong></p> <ul> <li><em><code>1 &lt;= A.length == B.length &lt;= 20</code></em></li> <li><em><code>A</code> and <code>B</code> contain only lowercase letters from the set <code>{'a', 'b', 'c', 'd', 'e', 'f'}</code></em></li> </ul> </blockquote> <p>Here is my solution to this challenge -</p> <blockquote> <pre><code>import collections class Solution: def find_first_mismatch(self, A, B): for i in range(len(A)): if A[i] != B[i]: return i def find_candidates(self, A, B, mismatch): for i in range(mismatch + 1, len(A)): if A[i] != B[i] and A[i] == B[mismatch]: yield Solution.swap(A, mismatch, i) def swap(A, i, j): chars = list(A) chars[i], chars[j] = chars[j], chars[i] return "".join(chars) def k_similarity(self, A, B): """ :type A: str :type B: str :rtype: int """ q = collections.deque([A]) distance = 0 seen = set([A]) while q: for _ in range(len(q)): current = q.pop() if current == B: return distance mismatch = self.find_first_mismatch(current, B) for candidate in self.find_candidates(current, B, mismatch): if candidate not in seen: seen.add(candidate) q.appendleft(candidate) distance += 1 </code></pre> </blockquote> <p>Here is my idea of how to solve the challenge -</p> <p>The problem can be modeled as a graph problem of finding the shortest path between <code>A</code> and <code>B</code> where intermediate nodes are anagrams that can be formed by swapping 2 characters in a node having an edge to it. In other words, there is an edge between node <code>X</code> to node <code>Y</code> if <code>Y</code> can be formed by swapping 2 characters in <code>X</code> and vice-versa.</p> <p>Here are some example outputs -</p> <p><strong>Example 1 -</strong></p> <pre><code>Input: A = "ab", B = "ba" Output: 1 </code></pre> <p><strong>Example 2 -</strong></p> <pre><code>Input: A = "abc", B = "bca" Output: 2 </code></pre> <p><strong>Example 3 -</strong></p> <pre><code>Input: A = "abac", B = "baca" Output: 2 </code></pre> <p><strong>Example 4 -</strong></p> <pre><code>Input: A = "aabc", B = "abca" Output: 2 </code></pre> <p>Here is my Leetcode result (54 test cases) -</p> <p><a href="https://i.stack.imgur.com/FvlQe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FvlQe.png" alt="Leetcode result"></a></p> <p>So, I would like to know whether I could make this program shorter and more efficient.</p> <p>Any help would be highly appreciated. </p>
[]
[ { "body": "<p><strong>Adding a few tests</strong></p>\n\n<p>Before performing any chance, it can be a good idea to add a few tests. This is especially relevant if we plan to perform optimisations as we'll be able to measure times. In that, case, it is also great when we are able to generate arbitrarily large inputs to infer the complexity of the solution (or at least be able to compare 2 solutions).</p>\n\n<p>Here is what I wrote:</p>\n\n<pre><code>import time\n\nstart = time.time()\nfor i in range(2):\n # Examples provided\n assert Solution().kSimilarity(\"ab\", \"ba\") == 1\n assert Solution().kSimilarity(\"abc\", \"bca\") == 2\n assert Solution().kSimilarity(\"abac\", \"baca\") == 2\n assert Solution().kSimilarity(\"aabc\", \"abca\") == 2\n # Arbitrary examples\n assert Solution().kSimilarity(\"abcdefg\", \"gabdcef\") == 5\n assert Solution().kSimilarity(\"abcbcdefg\", \"gcbabdcef\") == 6\n # Big examples inspired from smaller ones\n n = 10\n assert Solution().kSimilarity(\"ab\" * n, \"ba\" * n) == 1 * n\n assert Solution().kSimilarity(\"abc\" * n, \"bca\" * n) == 2 * n\n assert Solution().kSimilarity(\"abac\" * n, \"baca\" * n) == 2 * n\n assert Solution().kSimilarity(\"aabc\" * n, \"abca\" * n) == 2 * n\n assert Solution().kSimilarity(\"abcdefg\" * n, \"gabdcef\" * n) == 5 * n\nprint(time.time() - start)\n\n</code></pre>\n\n<p>Playing with the different values of <code>n</code> below, we can see that the Solution becomes very slow very quickly (I stopped at <code>n = 4</code>).</p>\n\n<p>The timing suggest an exponential complexity.</p>\n\n<p>Maybe there's something we can do about it with a different algorithm. We'll see this at the end but in the meantime, let's try to improve the already existing code.</p>\n\n<p><strong>Code review</strong></p>\n\n<p>The code looks good and uses great ideas <a href=\"https://codereview.stackexchange.com/questions/221339/leetcode-sliding-puzzle-in-python\">that I've seen in other places</a>.</p>\n\n<p>A few details can be improved.</p>\n\n<p>I'd call <code>find_first_mismatch</code> directly from <code>find_candidates</code>.</p>\n\n<p>Actually, you could also merge the 2 functions to have a single loop and avoid messing with indices.</p>\n\n<p>With a simple rewriting we get something equivalent which could be considered less elegant but is slightly faster:</p>\n\n<pre><code>def find_candidates(self, A, B):\n mismatch = None\n for i, (a, b) in enumerate(zip(A, B)):\n if a != b:\n if mismatch is None:\n mismatch = i\n elif a == B[mismatch]:\n yield Solution.swap(A, mismatch, i)\n</code></pre>\n\n<p>Another optimisation could be to avoid converting A to list many times by inlining the code for <code>swap</code>. This is not great as far as code organisation goes but...</p>\n\n<pre><code>def find_candidates(self, A, B):\n mismatch = None\n chars = list(A)\n for i, (a, b) in enumerate(zip(A, B)):\n if a != b:\n if mismatch is None:\n mismatch = i\n elif a == B[mismatch]:\n # Swap, yield and revert swap\n chars[i], chars[mismatch] = chars[mismatch], chars[i]\n yield \"\".join(chars)\n chars[i], chars[mismatch] = chars[mismatch], chars[i]\n</code></pre>\n\n<p>Renaming and reusing known values, we'd get:</p>\n\n<pre><code>def find_candidates(self, A, B):\n mismatch = None\n A_lst = list(A)\n for i, (a, b) in enumerate(zip(A, B)):\n if a != b:\n if mismatch is None:\n mismatch = i\n elif a == B[mismatch]:\n # Swap, yield and revert swap\n c = A_lst[mismatch]\n A_lst[i], A_lst[mismatch] = c, a\n yield \"\".join(A_lst)\n A_lst[i], A_lst[mismatch] = a, c\n</code></pre>\n\n<p>Instead of having <code>q</code> via different ways (len, pop, appendleft), we could just use list and iterate over it while filling another list that will be used at next iteration. We'd get something like:</p>\n\n<pre><code> q = [A]\n distance = 0\n seen = set([A])\n while q:\n new_q = []\n for current in q:\n if current == B:\n # print(\"Return:\", distance)\n return distance\n for candidate in self.find_candidates(current, B):\n if candidate not in seen:\n seen.add(candidate)\n new_q.append(candidate)\n q = new_q\n distance += 1\n</code></pre>\n\n<p>Instead of maintaining distance at each iteration, you could use <code>itertools.count</code>.</p>\n\n<p>At this stage, the code looks like:</p>\n\n<pre><code> def find_candidates(self, A, B):\n mismatch = None\n A_lst = list(A)\n for i, (a, b) in enumerate(zip(A, B)):\n if a != b:\n if mismatch is None:\n mismatch = i\n elif a == B[mismatch]:\n # Swap, yield and revert swap\n c = A_lst[mismatch]\n A_lst[i], A_lst[mismatch] = c, a\n yield \"\".join(A_lst)\n A_lst[i], A_lst[mismatch] = a, c\n\n def kSimilarity(self, A, B):\n \"\"\"\n :type A: str\n :type B: str\n :rtype: int\n \"\"\"\n # print(\"kSimilarity:\", A, B)\n q = [A]\n seen = set([A])\n for distance in itertools.count():\n new_q = []\n for current in q:\n if current == B:\n return distance\n for candidate in self.find_candidates(current, B):\n if candidate not in seen:\n seen.add(candidate)\n new_q.append(candidate)\n q = new_q\n</code></pre>\n\n<p><strong>Different algorithm</strong></p>\n\n<p>Generating so many intermediate strings is expensive and not so efficient.</p>\n\n<p>An observation is that whenever we have elements so that: x1 should become x2, x2 should become x3, ..., xn should become x1, there is a trivial manipulation involving <code>n - 1</code> swaps which put <code>n</code> elements in their correct position. It is easy to see that things can't get more efficient that this.</p>\n\n<p>Now, the initial problem can be rewritten in a different problem where we want to find such cycles in our original strings.</p>\n\n<p>This can be done by reorganising data from our strings into a graph and writing the proper loop to visit nodes to find cycles.</p>\n\n<pre><code>class Solution:\n def kSimilarity(self, A: str, B: str) -&gt; int:\n # Building a graph where c1 -&gt; c2 means we want to change c1 for c2\n # The problem becomes a graph problem: finding cycles\n changes = dict()\n for i, (c1, c2) in enumerate(zip(A, B)):\n if c1 != c2:\n changes.setdefault(c1, []).append(c2)\n ret = 0\n while changes:\n # Find cycle\n visited = []\n node = next(iter(changes))\n while node not in visited:\n visited.append(node)\n node = changes[node][0]\n # Cycle is found - starting from node\n beg = visited.index(node)\n loop = visited[beg:]\n # print(\"Loop:\", loop)\n ret += len(loop) - 1\n # Remove corresponding elements\n for c1, c2 in zip(loop, loop[1:] + [loop[0]]):\n l = changes[c1]\n l.remove(c2)\n if not l:\n del changes[c1]\n # print(\"Return:\", ret)\n return ret\n</code></pre>\n\n<p>It seems like this behaves in a linear time or something that look similar enough.\nI was able to run the tests above with <code>n = 3000</code> in very small time.</p>\n\n<p>Note: things are not as good as expected. Trying to run the code on the leetcode tool, a test case is not handled properly</p>\n\n<pre><code>assert Solution().kSimilarity(\"aabbccddee\", \"cdacbeebad\") == 6 # Returns 7\n</code></pre>\n\n<p>I guess I based the algorithm on a wrong assumption. It seems like the cycles can't be chosen randomly as I assumed.</p>\n\n<p>For instance, in that case, we should choose:</p>\n\n<ul>\n<li>[bc] + [de] + [bad] + [cea] (with cost 6)</li>\n</ul>\n\n<p>over combinations like</p>\n\n<ul>\n<li><p>[acb] + [ade] + [cebd] (with cost 7) or</p></li>\n<li><p>[acedb] + [ade] + [bc] (with cost 7)</p></li>\n</ul>\n\n<p>At the end of the day, we want to maximise the number of cycles: the final cost will be <code>number of characters in the wrong space - number of cycles</code>.</p>\n\n<p>I have no clue how to handle this...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T23:52:45.733", "Id": "221449", "ParentId": "221434", "Score": "1" } } ]
{ "AcceptedAnswerId": "221449", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T16:31:27.433", "Id": "221434", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "breadth-first-search" ], "Title": "(Leetcode) K-similar strings in Python" }
221434
<p>I am building a web app in Django where one of the form fields is a multiplechoicefield from a many2many object that I use to select users that are allowed to edit the post. In standard form the field displays predominantly while it is only seldom required, hence I would like the field only to show under a dropdown button. As I spent considerable time to figure this out I thought it might be useful to share this little trick and to welcome any suggestions on alternatives.</p> <p>The first hurdle to take was how to access form fields individually, so to be more flexible where to put them. For this I use <a href="https://django-crispy-forms.readthedocs.io/en/latest/" rel="nofollow noreferrer">Django Crispy Forms</a>.</p> <p>You can install it by:</p> <blockquote> <p><code>pip install django-crispy-forms</code></p> </blockquote> <p>and alter a few things in <strong>settings.py</strong></p> <pre><code>INSTALLED_APPS = [ ... 'crispy_forms', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' </code></pre> <p>In my case I am using <code>bootstrap4</code>, but probably there are also other <code>CRISPY_TEMPLATE_PACKs.</code></p> <p>The relevant model <code>Post</code> in <strong>models.py</strong> looks as follows:</p> <pre><code>from martor.models import MartorField class Post(models.Model): post_subject = models.CharField(max_length=POST_SUBJECT_SIZE, null=True) message = MartorField(max_length=MESSAGE_FIELD_SIZE, help_text=f'Maximum length is {MESSAGE_FIELD_SIZE} characters', ) topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name='posts') created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='posts') created_at = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+', null=True) updated_at = models.DateTimeField(null=True) allowed_editor = models.ManyToManyField(User, blank=True) def __str__(self): return Truncator(self.post_subject).chars(30) </code></pre> <p><em>Note martorfield is a nice md editor for the message field.</em></p> <p>The fields are defined in <strong>fields.py</strong>, where I have also changed the standard <code>MultipleChoiceField</code> to a <code>CheckboxSelectMultiple</code> widget</p> <pre><code>class PostForm(forms.ModelForm): allowed_editor = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), required=False, label='', help_text='Selection is not required', queryset=User.objects.all().order_by('username')) class Meta: model = Post fields = ['allowed_editor', 'post_subject', 'message'] labels = {'post_subject': 'Post subject'} </code></pre> <p>and as an example one of the views in <strong>views.py</strong>:</p> <pre><code>@method_decorator(login_required, name='dispatch') class PostUpdateView(UpdateView): model = Post form_class = PostForm template_name = 'boards/edit_post.html' pk_url_kwarg = 'post_pk' context_object_name = 'post' def get_queryset(self): self.topic = get_object_or_404(Topic, board__pk=self.kwargs.get('board_pk'), pk=self.kwargs.get('topic_pk')) queryset = self.topic.posts.order_by('-updated_at') def form_valid(self, form): # note if commit=False, then post.save() must be followed by form.save_m2m() post = form.save(commit=False) post.updated_by = self.request.user post.updated_at = timezone.now() post.save() form.save_m2m() self.topic.last_updated = post.updated_at self.topic.save() topic_url = reverse('topic_posts', kwargs={'board_pk': self.topic.board.pk, 'topic_pk': self.topic.pk},) topic_post_url = f'{topic_url}?page={self.topic.get_page_number(post.pk)}' return redirect(topic_post_url) </code></pre> <p>Finally then the trick is in the template, where the individual form fields are placed where needed using the <code>as_crispy_field</code> tags. The <code>allowed_editor</code> field is put under a dropdown button using the below snippet.</p> <pre><code> &lt;button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown" &gt;Allowed editors&lt;span class="caret"&gt;&lt;/span&gt;&lt;/button&gt; &lt;ul class="dropdown-menu"&gt; {{ form.allowed_editor|as_crispy_field }} &lt;/ul&gt; </code></pre> <p>and the full template <strong>edit_post.html</strong></p> <pre><code>{% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block title %}Edit post{% endblock %} {% block breadcrumb %} &lt;ol class="breadcrumb my-4"&gt; &lt;li class="breadcrumb-item"&gt;&lt;a href="{% url 'home' %}"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li class="breadcrumb-item"&gt;&lt;a href="{% url 'boards' %}"&gt;Boards&lt;/a&gt;&lt;/li&gt; &lt;li class="breadcrumb-item"&gt;&lt;a href="{% url 'board_topics' post.topic.board.pk %}"&gt;{{ post.topic.board.name }}&lt;/a&gt;&lt;/li&gt; &lt;li class="breadcrumb-item"&gt;&lt;a href="{% url 'topic_posts' post.topic.board.pk post.topic.pk %}"&gt;{{ post.topic.topic_subject }}&lt;/a&gt;&lt;/li&gt; &lt;li class="breadcrumb-item active"&gt;Edit contribution&lt;/li&gt; &lt;/ol&gt; {% endblock %} {% block content %} &lt;form method="post" class="mb-4" novalidate&gt; {% csrf_token %} &lt;button type="submit" class="btn btn-primary btn-sm"&gt;Save changes&lt;/button&gt; &lt;button style="margin:1px" class="btn btn-primary btn-sm" name="deleted_post_pk" value="{{ post.pk }}" onclick="return Validate()"&gt;Delete contribtion&lt;/button&gt; &lt;button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown" &gt;Allowed editors&lt;span class="caret"&gt;&lt;/span&gt;&lt;/button&gt; &lt;ul class="dropdown-menu"&gt; {{ form.allowed_editor|as_crispy_field }} &lt;/ul&gt; &lt;a href="{% url 'topic_posts' post.topic.board.pk post.topic.pk %}" class="btn btn-outline-secondary btn-sm" role="button"&gt;Cancel&lt;/a&gt; &lt;br&gt;&lt;/br&gt; {{ form.post_subject|as_crispy_field }} {{ form.message|as_crispy_field }} &lt;/form&gt; &lt;br&gt; &lt;br&gt; {% endblock %} {% block javascript %} &lt;script src="{% static 'js/board.js' %}"&gt;&lt;/script&gt; {% endblock %} </code></pre> <p>If you are interested in all of the source code you can find these at <a href="https://github.com/bvermeulen/Django/tree/81b1d8359878d7e69cc94c8a753b05fd14947406" rel="nofollow noreferrer">github</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T18:11:29.933", "Id": "221439", "Score": "1", "Tags": [ "python", "form", "django", "markdown" ], "Title": "Putting a multichoicefield under a dropdown button" }
221439
<p>I created this shared pointer mainly to use it as RAII for handles that have to be shared between classes or threads.</p> <p>For pointers:<br> It supports raw pointers and pointer to classes and arrays and also support classes inheriting from <code>ref_base</code> to save an allocation for the reference counter.</p> <p>For non-pointers:<br> They must be nullable and aren't arrays nor inheriting from <code>ref_base</code>.</p> <pre><code>#include &lt;atomic&gt; #include &lt;type_traits&gt; #include &lt;Windows.h&gt; using namespace std; #define HAS_TYPE(NAME) \ template&lt;typename, typename = void&gt; \ struct has_type_##NAME: std::false_type \ {}; \ template&lt;typename T&gt; \ struct has_type_##NAME&lt;T, void_t&lt;typename T::NAME&gt;&gt;: std::true_type \ {} \ HAS_TYPE(pointer); template &lt;class T, bool is_it_array = false&gt; struct default_sp_deleter { void operator()(T *ptr) { delete ptr; } }; template &lt;class T&gt; struct default_sp_deleter&lt;T, true&gt; { void operator()(T *ptr) { delete[] ptr; } }; template &lt;class T, class D, bool inherit, bool has_pointer&gt; struct sp_data {}; template &lt;class T, class D&gt; struct sp_data&lt;T, D, true, true&gt; { using pointer = typename D::pointer; pointer ptr; D deleter; sp_data() : ptr(pointer()) {} sp_data(pointer p) : ptr(p) {} sp_data(pointer p, D del) : ptr(p), deleter(del) {} }; template &lt;class T, class D&gt; struct sp_data&lt;T, D, true, false&gt; { using pointer = T*; pointer ptr; D deleter; sp_data() : ptr(pointer()) {} sp_data(pointer p) : ptr(p) {} sp_data(pointer p, D del) : ptr(p), deleter(del) {} }; template &lt;class T, class D&gt; struct sp_data&lt;T, D, false, false&gt; { using pointer = T*; pointer ptr; D deleter; atomic&lt;uintptr_t&gt; *ref_count; sp_data() : ptr(pointer()), ref_count(new atomic&lt;uintptr_t&gt;(0)) {} sp_data(pointer p) : ptr(p), ref_count(new atomic&lt;uintptr_t&gt;(0)) {} sp_data(pointer p, D del) : ptr(p), deleter(del), ref_count(new atomic&lt;uintptr_t&gt;(0)) {} sp_data(const sp_data&lt;T, D, false, false&gt;&amp; data) : ptr(data.ptr), ref_count(data.ref_count) {} ~sp_data() {} sp_data&amp; operator=(const sp_data&lt;T, D, false, false&gt;&amp; data) { ptr = data.ptr; ref_count = data.ref_count; return *this; } }; template &lt;class T, class D&gt; struct sp_data&lt;T, D, false, true&gt; { using pointer = typename D::pointer; pointer ptr; D deleter; atomic&lt;uintptr_t&gt; *ref_count; sp_data() : ptr(pointer()), ref_count(new atomic&lt;uintptr_t&gt;(0)) {} sp_data(pointer p) : ptr(p), ref_count(new atomic&lt;uintptr_t&gt;(0)) {} sp_data(pointer p, D del) : ptr(p), deleter(del), ref_count(new atomic&lt;uintptr_t&gt;(0)) {} sp_data(const sp_data&lt;T, D, false, false&gt;&amp; data) : ptr(data.ptr), ref_count(data.ref_count) {} template &lt;class U&gt; sp_data(const sp_data&lt;U, D, false, false&gt;&amp; data) : ptr(data.ptr) { } ~sp_data() {} sp_data&amp; operator=(const sp_data&lt;T, D, false, false&gt;&amp; data) { ref_count = data.ref_count; ptr = data.ptr; return *this; } }; class ref_base; template &lt;class T, class Deleter = default_sp_deleter&lt;typename std::remove_all_extents&lt;T&gt;::type, std::is_array&lt;T&gt;::value&gt;&gt; class sp { using elem_type = typename std::remove_all_extents&lt;T&gt;::type; using pointer = typename sp_data&lt;elem_type, Deleter, std::is_base_of&lt;ref_base, T&gt;::value, has_type_pointer&lt;Deleter&gt;::value&gt;::pointer; sp_data&lt;elem_type, Deleter, std::is_base_of&lt;ref_base, pointer&gt;::value, has_type_pointer&lt;Deleter&gt;::value&gt; data; public : using element_type = typename std::remove_pointer_t&lt;pointer&gt;; template&lt;typename, typename&gt; friend class sp; sp() {} sp(pointer p) { data.ptr = p; if (get() != pointer()) inc_ref(); } sp(const sp&lt;T, Deleter&gt;&amp; rhs) : data(rhs.data) { if (get() != pointer()) inc_ref(); } sp(sp&lt;T, Deleter&gt;&amp;&amp; rhs) : data(rhs.data) { rhs.data.ptr = pointer(); } template &lt;class U&gt; sp(const sp&lt;U, Deleter&gt;&amp; rhs) : data(rhs.data) { if (get() != pointer()) inc_ref(); } template &lt;class U&gt; sp(sp&lt;U, Deleter&gt;&amp;&amp; rhs) : data(rhs.data) { rhs.data.ptr = pointer(); } template &lt;class U, typename std::enable_if&lt;std::is_convertible&lt;U, pointer&gt;::value &amp;&amp; !std::is_same&lt;U, pointer&gt;::value, bool&gt;::type = true&gt; sp(U value) { data.ptr = value; if (get() != pointer()) inc_ref(); } ~sp() { reset(); } sp&lt;T, Deleter&gt;&amp; operator=(const sp&lt;T, Deleter&gt;&amp; rhs) { reset(); data = rhs.data; if (get() != pointer()) inc_ref(); return *this; } sp&lt;T, Deleter&gt;&amp; operator=(sp&lt;T, Deleter&gt;&amp;&amp; rhs) { reset(); data = rhs.data; if (get() != pointer()) inc_ref(); rhs.reset(); return *this; } template &lt;class U&gt; sp&lt;T, Deleter&gt;&amp; operator=(const sp&lt;U, Deleter&gt;&amp; rhs) { reset(); data = rhs.data; if (get() != pointer()) inc_ref(); return *this; } template &lt;class U&gt; sp&lt;T, Deleter&gt;&amp; operator=(sp&lt;U, Deleter&gt;&amp;&amp; rhs) { reset(); data = rhs.data; if (get() != pointer()) inc_ref(); rhs.reset(); return *this; } pointer get() const { return data.ptr; } template &lt;class U = pointer&gt; typename std::enable_if&lt;is_pointer&lt;U&gt;::value, element_type&amp;&gt;::type operator*() { return *data.ptr; } template &lt;class U = pointer&gt; typename std::enable_if&lt;!std::is_pointer&lt;U&gt;::value, pointer&amp;&gt;::type operator&amp;() { return &amp;data.ptr; } pointer operator-&gt;() { return get(); } long use_count() { if (get() == pointer()) return 0; return private_use_count(); } bool unique() { return use_count() == 1; } operator bool() { return get() != pointer(); } Deleter&amp; get_deleter() { return data.deleter; } void reset(pointer ptr = pointer()) { if (get() == ptr) return; if (has_counter() &amp;&amp; !dec_ref()) { get_deleter()(get()); } release_ref_counter(); data.ptr = ptr; if (get() != pointer()) { setup_counter(); inc_ref(); } } private : template&lt;class U = element_type&gt; typename enable_if&lt;is_base_of&lt;ref_base, U&gt;::value &amp;&amp; std::is_pointer&lt;pointer&gt;::value&gt;::type inc_ref() { get()-&gt;inc_ref(); } // currently this type of members is broken and shouldn't be used : // if Deleter::pointer exists it mustn't inherit from ref_base template&lt;class U = element_type&gt; typename enable_if&lt;is_base_of&lt;ref_base, U&gt;::value &amp;&amp; !std::is_pointer&lt;pointer&gt;::value&gt;::type inc_ref() { data.ptr.inc_ref(); } template&lt;class U = element_type&gt; typename enable_if&lt;!is_base_of&lt;ref_base, U&gt;::value&gt;::type inc_ref() { ++(*data.ref_count); } template&lt;class U = element_type&gt; typename std::enable_if&lt;std::is_base_of&lt;ref_base, U&gt;::value &amp;&amp; std::is_pointer&lt;pointer&gt;::value, uintptr_t&gt;::type dec_ref() { return get()-&gt;dec_ref(); } template&lt;class U = element_type&gt; typename std::enable_if&lt;std::is_base_of&lt;ref_base, U&gt;::value &amp;&amp; !std::is_pointer&lt;pointer&gt;::value, uintptr_t&gt;::type dec_ref() { return data.ptr.dec_ref(); } template&lt;class U = element_type&gt; typename std::enable_if&lt;!std::is_base_of&lt;ref_base, U&gt;::value, uintptr_t&gt;::type dec_ref() { --(*data.ref_count); return data.ref_count-&gt;load(); } template&lt;class U = element_type&gt; typename std::enable_if&lt;std::is_base_of&lt;ref_base, U&gt;::value &amp;&amp; std::is_pointer&lt;pointer&gt;::value, uintptr_t&gt;::type private_use_count() { return get()-&gt;use_count(); } template&lt;class U = element_type&gt; typename std::enable_if&lt;std::is_base_of&lt;ref_base, U&gt;::value &amp;&amp; !std::is_pointer&lt;pointer&gt;::value, uintptr_t&gt;::type private_use_count() { return data.ptr.use_count(); } template&lt;class U = element_type&gt; typename std::enable_if&lt;!std::is_base_of&lt;ref_base, U&gt;::value, uintptr_t&gt;::type private_use_count() { return data.ref_count-&gt;load(); } template&lt;class U = element_type&gt; typename std::enable_if&lt;std::is_base_of&lt;ref_base, U&gt;::value&gt;::type release_ref_counter() {} template&lt;class U = element_type&gt; typename std::enable_if&lt;!std::is_base_of&lt;ref_base, U&gt;::value&gt;::type release_ref_counter() { if (data.ref_count &amp;&amp; !(*data.ref_count)) { delete data.ref_count; } data.ref_count = nullptr; } template&lt;class U = element_type&gt; typename std::enable_if&lt;std::is_base_of&lt;ref_base, U&gt;::value&gt;::type setup_counter() {} template&lt;class U = element_type&gt; typename std::enable_if&lt;!std::is_base_of&lt;ref_base, U&gt;::value&gt;::type setup_counter() { data.ref_count = new atomic&lt;uintptr_t&gt;(0); } template&lt;class U = element_type&gt; typename std::enable_if&lt;std::is_base_of&lt;ref_base, U&gt;::value, bool&gt;::type has_counter() { return get() != pointer(); } template&lt;class U = element_type&gt; typename std::enable_if&lt;!std::is_base_of&lt;ref_base, U&gt;::value, bool&gt;::type has_counter() { return data.ref_count != nullptr; } }; class ref_base { public : template&lt;typename, typename&gt; friend class sp; ref_base() : ref_count(0) {} ref_base(const ref_base&amp;) : ref_count(0) {} ref_base(ref_base&amp;&amp;) : ref_count(0) {} ~ref_base() {} ref_base&amp; operator=(const ref_base&amp;) { return *this; } ref_base&amp; operator=(ref_base&amp;&amp;) { return *this; } private : uintptr_t inc_ref() { ++ref_count; return ref_count.load(); } uintptr_t dec_ref() { --ref_count; return ref_count.load(); } long use_count() { return ref_count.load(); } atomic&lt;uintptr_t&gt; ref_count; }; class test : public ref_base { public : test() {} ~test() { cout &lt;&lt; "~test()" &lt;&lt; endl; } }; class test2 { public : test2() {} ~test2() { cout &lt;&lt; "~test2()" &lt;&lt; endl; } }; template &lt;typename T, T TNul = T(), bool pseudo = false&gt; class UniqueHandle { public: UniqueHandle(std::nullptr_t = nullptr) :m_id(TNul) { } UniqueHandle(T x) :m_id(x) { // if file handle but not process or thread one prevent -1 if (!pseudo &amp;&amp; m_id == INVALID_HANDLE_VALUE) m_id = TNul; } explicit operator bool() const { return m_id != TNul; } operator T&amp;() { return m_id; } operator T() const { return m_id; } T *operator&amp;() { return &amp;m_id; } const T *operator&amp;() const { return &amp;m_id; } friend bool operator == (UniqueHandle a, UniqueHandle b) { return a.m_id == b.m_id; } friend bool operator != (UniqueHandle a, UniqueHandle b) { return a.m_id != b.m_id; } friend bool operator == (UniqueHandle a, std::nullptr_t) { return a.m_id == TNul; } friend bool operator != (UniqueHandle a, std::nullptr_t) { return a.m_id != TNul; } friend bool operator == (std::nullptr_t, UniqueHandle b) { return TNul == b.m_id; } friend bool operator != (std::nullptr_t, UniqueHandle b) { return TNul != b.m_id; } private: T m_id; }; template &lt;class HandleType, class DeleterType, DeleterType Deleter, HandleType null_handle = HandleType(), bool pseudo = false&gt; struct UniqueHandleDeleter { using pointer = UniqueHandle&lt;HandleType, null_handle, pseudo&gt;; void operator()(pointer handle) { if (pseudo) { // pseudo handle is valid but isn't to be closed if (handle == pointer(GetCurrentProcess())) return; } Deleter(handle); } }; using SHandle = sp&lt;int, UniqueHandleDeleter &lt; HANDLE, decltype(&amp;CloseHandle), CloseHandle&gt;&gt;; using SProcHandle = sp&lt;int, UniqueHandleDeleter&lt;HANDLE, decltype(&amp;CloseHandle), CloseHandle, nullptr, true&gt;&gt;; using SRegHandle = sp&lt;int, UniqueHandleDeleter&lt;HKEY, decltype(&amp;RegCloseKey), RegCloseKey&gt;&gt;; using SSocket = sp&lt;int, UniqueHandleDeleter&lt;SOCKET, decltype(&amp;closesocket), closesocket, -1&gt;&gt;; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T19:01:31.253", "Id": "221442", "Score": "4", "Tags": [ "c++", "pointers", "raii" ], "Title": "Generalizing std::shared_ptr for all handle-types, even non-pointers" }
221442
<p>Please review how clear my code is and also comment on performance.</p> <blockquote> <p>Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai &lt; 2^31.</p> <p>Find the maximum result of ai XOR aj, where 0 ≤ i, j &lt; n.</p> <p>Could you do this in O(n) runtime?</p> <p>Example:</p> <p>Input: [3, 10, 5, 25, 2, 8]</p> <p>Output: 28</p> <p>Explanation: The maximum result is 5 ^ 25 = 28.</p> </blockquote> <p><a href="https://leetcode.com/explore/learn/card/trie/149/practical-application-ii/1057/" rel="nofollow noreferrer">LeetCode</a></p> <pre><code>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TrieQuestions { /// &lt;summary&gt; /// https://leetcode.com/explore/learn/card/trie/149/practical-application-ii/1057/ /// &lt;/summary&gt; [TestClass] public class FindMaxXorInArray { [TestMethod] public void XorTrieTreeTest() { int[] nums = {3, 10, 5, 25, 2, 8}; Assert.AreEqual(28,FindMaximumXOR(nums)); } //xor mean if the 0^0 == 0 and 1^1 == 0 // so if we want maximum we want the maximum opposites public int FindMaximumXOR(int[] nums) { XorTrieTree tree = new XorTrieTree(); tree.Insert(nums); return tree.GetMax(nums); } } public class XorTrieTree { private XorTreeNode _root; public XorTrieTree() { _root = new XorTreeNode(); } /// &lt;summary&gt; /// for each one of the numbers we find we flags are set on with right shit all of the 32 bits /// and bitwise AND to understand if the bit is set on or off /// &lt;/summary&gt; /// &lt;param name="nums"&gt;&lt;/param&gt; public void Insert(int[] nums) { foreach (var num in nums) { XorTreeNode cur = _root; for (int i = 31; i &gt;= 0; i--) { int bit = (num &gt;&gt; i) &amp; 1; if (cur.children[bit] == null) { cur.children[bit] = new XorTreeNode(); } cur = cur.children[bit]; } } } /// &lt;summary&gt; /// for each one of the numbers we try to understand which bits are set on. /// if the the bit is set on then we search for the NOT bit of that, /// we add the NOT bit to the temp xorValue variable, because the prefix of those two numbers are xor-ed /// and continue to the NOT bit next node. /// at the end we do max of current max and xorValue /// &lt;/summary&gt; /// &lt;param name="nums"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public int GetMax(int[] nums) { int max = int.MinValue; foreach (var num in nums) { XorTreeNode cur = _root; int xorValue = 0; for (int i = 31; i &gt;= 0; i--) { int bit = (num &gt;&gt; i) &amp; 1; if (cur.children[bit == 1 ? 0 : 1] != null) { xorValue += (1 &lt;&lt; i); cur = cur.children[bit == 1 ? 0 : 1]; } else { cur = cur.children[bit]; } } max = Math.Max(xorValue, max); } return max; } } //the root has 2 nodes for 0 and 1 public class XorTreeNode { public int Val; public XorTreeNode[] children; public XorTreeNode() { children = new XorTreeNode[2]; } } } </code></pre>
[]
[ { "body": "<p>In <code>XorTreeNode</code> you're not using the field <code>Val</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code>public void Insert(int[] nums)\npublic int GetMax(int[] nums)\n</code></pre>\n</blockquote>\n\n<p>Having two methods that must take the same data to operate on is hazardous and should be avoided. Either provide the data to the constructor or you should only have one public method with the data set as argument:</p>\n\n<pre><code>public int FindMaxXor(int[] nums) { Insert(nums); return GetMax(nums) }\n</code></pre>\n\n<hr>\n\n<p>You can invert a bit in the following way:</p>\n\n<pre><code>bit ^ 1\n</code></pre>\n\n<p>It can be used to simplify this:</p>\n\n<blockquote>\n<pre><code> int bit = (num &gt;&gt; i) &amp; 1;\n if (cur.children[bit == 1 ? 0 : 1] != null)\n {\n xorValue += (1 &lt;&lt; i);\n cur = cur.children[bit == 1 ? 0 : 1];\n }\n else\n {\n cur = cur.children[bit];\n }\n</code></pre>\n</blockquote>\n\n<p>to</p>\n\n<pre><code> int bit = ((num &gt;&gt; i) &amp; 1) ^ 1;\n if (cur.children[bit] != null)\n {\n xorValue += (1 &lt;&lt; i);\n cur = cur.children[bit];\n }\n else\n {\n cur = cur.children[bit ^ 1];\n }\n</code></pre>\n\n<hr>\n\n<p>You can insert numbers and search for max in the same operation, because every new number only need to compare with already existing numbers.</p>\n\n<p>So you can change <code>GetMax(...)</code> to:</p>\n\n<pre><code>private int GetMax(int num)\n{\n XorTreeNode cur = _root;\n int xorValue = 0;\n for (int i = _numBits; cur != null &amp;&amp; i &gt;= 0; i--)\n {\n int bit = ((num &gt;&gt; i) &amp; 1) ^ 1;\n if (cur.children[bit] != null)\n {\n xorValue += (1 &lt;&lt; i);\n cur = cur.children[bit];\n }\n else\n {\n cur = cur.children[bit ^ 1];\n }\n }\n\n return xorValue;\n}\n</code></pre>\n\n<p>and <code>Insert(...)</code> to:</p>\n\n<pre><code>public int FindMaxXor(int[] nums)\n{\n int result = int.MinValue;\n\n foreach (var num in nums)\n {\n result = Math.Max(result, GetMax(num));\n\n XorTreeNode cur = _root;\n for (int i = _numBits; i &gt;= 0; i--)\n {\n int bit = (num &gt;&gt; i) &amp; 1;\n if (cur.children[bit] == null)\n {\n cur.children[bit] = new XorTreeNode();\n }\n cur = cur.children[bit];\n }\n }\n\n return result;\n}\n</code></pre>\n\n<p>where <code>_numBits</code> is defined as a class const field:</p>\n\n<pre><code>private const int _numBits = 31;\n</code></pre>\n\n<hr>\n\n<p>If you know that the <code>nums</code> array contains only small values there might be a significant performance improvement in finding the leftmost significant bit:</p>\n\n<pre><code> int max = nums.Max();\n while (max &gt; 0)\n {\n _numBits++;\n max &gt;&gt;= 1;\n }\n</code></pre>\n\n<p>in the start of the <code>Insert(...)</code> method. <code>_numBits</code> should then not be const and initialized to zero obviously. \nIf the numbers span over the entire <code>int+</code> domain this may slow the entire process.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T11:48:59.233", "Id": "221584", "ParentId": "221444", "Score": "2" } } ]
{ "AcceptedAnswerId": "221584", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T19:41:09.963", "Id": "221444", "Score": "2", "Tags": [ "c#", "programming-challenge", "trie" ], "Title": "LeetCode: Maximum XOR of Two Numbers in an Array" }
221444
<p>I have tried to work out the Frog Jump task on Codility. The algorithm for solving this is rather simple but the maximum score I am able to achieve is 55% (also 44% with modulus operations).</p> <blockquote> <p>A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.</p> <p>Count the minimal number of jumps that the small frog must perform to reach its target.</p> <p>Write a function: <code>class Solution { public int solution(int X, int Y, int D); }</code> that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.</p> </blockquote> <pre><code>public static int solution(int X, int Y, int D) { int count = 0; //55% if (X == Y) { return 0; } else { while (X &lt; Y) { X += D; count++; } return count; } } </code></pre> <p>I have read in a place that switch statements can outperform if conditions but couldn't find a way to make a switch statement out of this, also tried to get the answer recursively, but was only able to put down the base case..</p> <p>Appreciate hints, help, suggestions at what should I look for to be optimal with this method.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T20:26:01.150", "Id": "428209", "Score": "4", "body": "Wouldn't this be `return (int)Math.Ceiling((float)(Y - X) / D);`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T20:50:29.843", "Id": "428211", "Score": "0", "body": "It is.. I have definitely have to read thoroughly the Math class.. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T20:52:33.777", "Id": "428212", "Score": "0", "body": "No problem, glad it helped. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T11:48:46.593", "Id": "428253", "Score": "0", "body": "@DerKommissar could you please explain in terms of time complexity why using Math.Ceiling is better in terms of if/else conditions? And also add your comment as an answers so I can mark it as such. Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-03T10:35:55.423", "Id": "480909", "Score": "1", "body": "@Kris `Math.Ceiling` is `O(1)` as well as the expression passed to it. Your algorithm is `O(solution(X,Y,D)) = O(ceil((Y - X) / D))` because it is linearily dependent on the output value itself." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T20:10:36.787", "Id": "221447", "Score": "2", "Tags": [ "c#", "programming-challenge", "complexity" ], "Title": "Frog Jump time complexity" }
221447
<p>Please comment about performance</p> <p><a href="https://leetcode.com/problems/leaf-similar-trees/" rel="nofollow noreferrer">https://leetcode.com/problems/leaf-similar-trees/</a></p> <blockquote> <p>Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.</p> <p><a href="https://i.stack.imgur.com/P6cqu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P6cqu.png" alt="enter image description here"></a></p> <p>For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8).</p> <p>Two binary trees are considered leaf-similar if their leaf value sequence is the same.</p> <p>Return true if and only if the two given trees with head nodes root1 and root2 are leaf-similar.</p> <p>Note:</p> <p>Both of the given trees will have between 1 and 100 nodes.</p> </blockquote> <pre><code>using System.Collections.Generic; using GraphsQuestions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TreeQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/leaf-similar-trees/ /// &lt;/summary&gt; [TestClass] public class LeafSimilarTrees { [TestMethod] public void LeafSimilarTreesTest() { TreeNode root1 = new TreeNode(3); root1.left = new TreeNode(5); root1.left.left = new TreeNode(6); root1.left.right = new TreeNode(2); root1.left.right.left = new TreeNode(7); root1.left.right.right = new TreeNode(4); root1.right = new TreeNode(1); root1.right.left = new TreeNode(9); root1.right.right = new TreeNode(8); TreeNode root2 = new TreeNode(3); root2.left = new TreeNode(1); root2.left.left = new TreeNode(6); root2.left.right = new TreeNode(2); root2.left.right.left = new TreeNode(7); root2.left.right.right = new TreeNode(4); root2.right = new TreeNode(5); root2.right.left = new TreeNode(9); root2.right.right = new TreeNode(8); Assert.IsTrue(LeafSimilar(root1,root2)); } public bool LeafSimilar(TreeNode root1, TreeNode root2) { List&lt;int&gt; tree1 = new List&lt;int&gt;(); List&lt;int&gt; tree2 = new List&lt;int&gt;(); DFS(root1, tree1); DFS(root2, tree2); if (tree1.Count != tree2.Count) { return false; } for (int i = 0; i &lt; tree1.Count; i++) { if (tree1[i] != tree2[i]) { return false; } } return true; } public void DFS(TreeNode root, List&lt;int&gt; list) { if (root == null) { return; } if (root.left != null) { DFS(root.left, list); } if (root.right != null) { DFS(root.right, list); } if (root.left == null &amp;&amp; root.right == null) { list.Add(root.val); } } } } </code></pre>
[]
[ { "body": "<p>In <code>LeafSimilar</code>, you could replace the manual comparison of the list elements with:</p>\n\n<pre><code>return tree1.SequenceEqual(tree2);\n</code></pre>\n\n<p>In <code>DFS</code>, I would call the parameter <code>node</code> instead of <code>root</code>,\nto avoid confusion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:59:36.643", "Id": "428448", "Score": "0", "body": "SequenceEqual I always forget using that one! thanks Janos" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T06:18:34.387", "Id": "221462", "ParentId": "221448", "Score": "3" } }, { "body": "<p>There's a problem with your approach: it always visits all nodes to build value lists, even when the trees aren't similar at all. By obtaining leaf-node values lazily, you'll prevent a lot of unnecessary traversal work if the trees are different.</p>\n\n<p>This can be achieved by changing <code>DFS</code> to a generator method (using <code>yield</code>), and comparing the results with <code>SequenceEqual</code>, as janos already pointed out. You'll want to use an explicit stack instead of recursion though, to avoid incurring too much overhead.</p>\n\n<p>However, for trees that are leaf-similar, the added overhead ends up making things slower. The fastest approach is probably a recursive method that does a depth-first traversal of both trees at the same time, bailing out as soon as it finds a leaf-node difference.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:59:04.770", "Id": "428447", "Score": "0", "body": "Witveot thanks for the code review, sounds very problematic to do that in a coding interview. anyway I like the yield idea thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T08:22:32.777", "Id": "428507", "Score": "0", "body": "In an interview I would write a general-purpose `yield`-based traversal method that yields all nodes. Leaf nodes can then easily be selected with a `Where(IsLeafNode)` call. This results in reusable code that's both readable and still quite performant. I would mention more complex alternatives, and the trade-offs that come with them (expected performance gain versus additional complexity and maintanance, etc.), but only implement them when specifically asked to do so." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T09:54:35.483", "Id": "221476", "ParentId": "221448", "Score": "5" } } ]
{ "AcceptedAnswerId": "221476", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-31T20:29:25.633", "Id": "221448", "Score": "3", "Tags": [ "c#", "performance", "programming-challenge", "tree" ], "Title": "LeetCode: Leaf-similar trees C#" }
221448
<p>I have written out the following code in the head section of my document, which should load 3 separate style sheets for each page based on the URL/URI that the user is visiting. It is working as intended as tested with the comment in the code but I am wondering if there is a more efficient way to do this. I initially started writing out a <code>switch</code> statement, but chose to try <code>if else</code> statements before.</p> <p>Also I have added this part:</p> <pre class="lang-php prettyprint-override"><code> || $_SERVER['PHP_URL_PATH'] </code></pre> <p>to each statement in case there is an error of some kind with the first expression. It seems to be working whether I use just <code>['PHP_URL_PATH']</code> or the full <code>$_SERVER['PHP_URL_PATH']</code>.</p> <p>My questions are:</p> <ol> <li>Which out of the two would be more efficient (<code>switch</code> or <code>if else</code>)?</li> <li>Is the second declaration of $_SERVER actually necessary, or will it work without this specificity? </li> </ol> <p>Any improvements that people could point me to would be greatly appreciated. </p> <p>PS: I have removed all the <code>echo</code>'s for including the actually <code>&lt;link&gt;</code>'s to the CSS files.</p> <p>This has been tested and is showing to work in Firefox Developer Edition so guessing it's ok, but could be improved maybe; what about scalability, or any security concerns? I am new so please advise or help.</p> <pre class="lang-php prettyprint-override"><code>// Create Logic here to include various different style sheets. if($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/mainHubV8.1.php"){ echo "Loading Styles for MainHubV8.1.php"; } else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/advSearchV8.1.php"){ echo "Loading Styles for advSearchV8.1.php"; } else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/loginOrSignUpV8.1.php"){ echo "Loading Styles for loginOrSignUpV8.1.php"; } else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/profilePageV8.1.php"){ echo "Loading Styles for profilePageV8.1.php"; } else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/chatApllicationV8.1.php"){ echo "Loading Styles for chatApllicationV8.1.php"; } else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/onlineUsersV8.1.php"){ echo "Loading Styles for onlineUsersV8.1.php"; } else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/index.php"){ echo "Loading Styles for index.php"; } else if ($_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === "/404"){ echo "Loading Styles for error page"; } </code></pre> <p>Is there a better alternative to achieving the same goal? If so could you please provide reference or articles/Question &amp; answers anywhere on Stack Exchange or some other resource. Plus I do not want to use Javascript or JQuery really as these can be turned off and disabled. So PHP seems more appropriate.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T15:24:05.150", "Id": "428268", "Score": "1", "body": "What would you want the code to do if `$_SERVER['PHP_SELF']` matched one case while `$_SERVER['PHP_URL_PATH']` matched a different one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T18:33:33.833", "Id": "428290", "Score": "2", "body": "Also, isn't this what maps are for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T18:40:34.813", "Id": "428293", "Score": "0", "body": "@Mooing Duck can you elaborate?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T18:43:20.550", "Id": "428294", "Score": "1", "body": "@RyanStone: https://www.php.net/manual/en/language.types.array.php" } ]
[ { "body": "<p>I wonder if you are asking the right question. I can't help but wonder where this code block could possibly run in order to make sense.</p>\n\n<p>I will have to assume a lot, so here we go:</p>\n\n<p>Why don't you create an associative array where the keys are the endpoint and the values are a string of your stylesheet.</p>\n\n<p>This way you will be able to read that from a database one day.</p>\n\n<p>Now take your endpoint (a note here: you want to look into <code>REQUEST_URI</code> and/or <code>parse_url</code>) and simply get your values out:</p>\n\n<pre><code>$styleSheets =['index.php'=&gt;'style.css'];\n$styleSheets[$currentRoute]\n</code></pre>\n\n<p>That said, feel free to share your code-base as I think you might want to get some feedback on your general structure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T03:47:53.573", "Id": "428223", "Score": "0", "body": "The Code block I have provided, is currently set in the head section of a dedicated head file which will load on every page load for all pages, only the body, footer and css & or scripts will change with different URLs, i did look into parse_url but it confused me quite alot, still trying to learn php, step by step." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T02:33:32.777", "Id": "221453", "ParentId": "221450", "Score": "1" } }, { "body": "<p>Most of questions you are asking are not fit for this site and your code <strong>does not</strong> work as intended but this is an interesting case to review</p>\n<h1>The grave mistake</h1>\n<p>Adding anything to your code just in case there would be some imaginary &quot;error of some kind&quot; is <strong>the worst thing a programmer could do ever</strong>. You effectively ruined your code with adding that <code>|| $_SERVER['PHP_URL_PATH']</code> stuff:</p>\n<ul>\n<li>there is no such thing <code>$_SERVER['PHP_URL_PATH']</code> for starter: such a variable just <strong>doesn't exist</strong></li>\n<li>of course <code>['PHP_URL_PATH']</code> without the <code>$_SERVER</code> part makes no sense</li>\n<li>neither the whole condition returns anything sensible due to PHP syntax rules you are yet to learn.</li>\n</ul>\n<p>Yet this code works somehow, albeit not the way you expect.</p>\n<h1>The operator precedence</h1>\n<p>The way this code executes is a very interesting matter, once I wrote an article that explains it in detail, <a href=\"https://phpdelusions.net/articles/or_die\" rel=\"noreferrer\">Operator precedence or how does 'or die()' work</a>. Given you only started learning it could be too complex for you for the moment to wrap your head around, but in time you will find it very interesting to read.</p>\n<p><code>$_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === &quot;/mainHubV8.1.php&quot;</code> doesn't mean &quot;if either PHP_SELF or PHP_URL_PATH equal to /mainHubV8.1.php&quot;. It means &quot;if PHP_SELF contains any value OR PHP_URL_PATH is equal to /mainHubV8.1.php&quot;.</p>\n<p>In short, an expression <code>$_SERVER['PHP_SELF'] || $_SERVER['PHP_URL_PATH'] === &quot;/mainHubV8.1.php&quot;</code> evaluates to <code>true</code> when <code>$_SERVER['PHP_SELF']</code> contains <em>any</em> value. Which means <strong>always</strong>.</p>\n<p>Given PHP already has it's answer, it <em>ceases to execute the further condition</em>. This is why you can write either <code>$_SERVER['PHP_URL_PATH']</code> or <code>['PHP_URL_PATH']</code> or don't even get a notice for the non-existent array index - this code is just never executed.</p>\n<p>As a result, this code will always output just <code>&quot;Loading Styles for MainHubV8.1.php&quot;</code> no matter which page it is called on.</p>\n<h1>The right way</h1>\n<p>To elaborate on the Neoan's answer, given you have 3 styles to load, here is the proposed array structure</p>\n<pre><code>$stylesheets = [\n '/mainHubV8.1.php' =&gt; [\n 'style1.css',\n 'style2.css',\n 'style3.css',\n ],\n '/advSearchV8.1.php' =&gt; [\n 'style4.css',\n 'style5.css',\n 'style6.css',\n ],\n // and so on\n];\n</code></pre>\n<p>given this structure, you will be able to get the correct styles right from <code>$_SERVER['PHP_SELF']</code>:</p>\n<pre><code>foreach($stylesheets[$_SERVER['PHP_SELF']] as $file) {\n echo &quot;&lt;link rel='stylesheet' type='text/css' href='$file'&gt;\\n&quot;;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:20:21.387", "Id": "428273", "Score": "0", "body": "Thank you for your reply, I will read through it carefully.. How does $_SERVER['PHP_URL_PATH'] not exist when I have clearly found documentation to support that it does? & also I have only asked 2 questions so far so that is a bit of an unfair statement, how is anyone supposed to learn when the restriction on stack exchange basically block anyone from actually asking wrong or mis-construed questions. That is the whole point of learning. I can't ask any more questions on stack-overflow so its like hitting a brick wall in my learning experience." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:35:21.373", "Id": "428276", "Score": "0", "body": "Oh, I see your point on line 18/19 yes, Thank you for pointing this out. Trying to understand you answer a bit better in the first block you have made an array called $stylesheets, but how does this link into the foreach statement as your not specifying $stylesheets anywhere & where is this $file pulling its value from? Not sure I fully grasp this answer yet, but I will continue to bash my head against it until i do..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:46:53.767", "Id": "428280", "Score": "0", "body": "Copied the code in your first block exactly as it is as a template to be edited & CPanel text editor is throwing an error: Syntax Error, unexpected T_DOUBLE_ARROW, expecting '']'............... ? is inside the php tags also? i removed the trailing , on each 'list' but this did not fix it. is on line 2?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:54:14.503", "Id": "428282", "Score": "0", "body": "I think i do understand the article you have included similar to how (Brackets) in maths means execute this part first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T17:10:40.260", "Id": "428284", "Score": "0", "body": "I fixed the code on both regards" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T17:20:19.230", "Id": "428285", "Score": "1", "body": "On the first line, you have a syntax error. It has `$stylesheets [` but should be `$stylesheets = [`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T17:22:53.783", "Id": "428286", "Score": "0", "body": "still same error, is = necessary after the first variable? @Ismael Miguel beat me. lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T18:19:56.540", "Id": "428289", "Score": "0", "body": "@YourCommonSense You have mentioned \"As a result, this code will always output just 'Loading Styles for MainHubV8.1.php' no matter which page it is called on.\", but this is not entirely true, different pages where out-putting different results? So the logik was correct just without the \"|| $_SERVER['PHP_URL_PATH']\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T20:00:07.440", "Id": "428298", "Score": "0", "body": "@RyanStone Then it wasnt correct." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T07:35:06.523", "Id": "221464", "ParentId": "221450", "Score": "8" } }, { "body": "<p>Your current battery of if conditions needs a re-think. <code>$_SERVER['PHP_SELF']</code> -- as long as it has a non-falsey value will evauate to <code>true</code>, satisfy the first expression, will never even reach <code>$_SERVER['PHP_URL_PATH'] === \"/mainHubV8.1.php\"</code>, execute <code>echo \"Loading Styles for MainHubV8.1.php\";</code>, and nothing else will ever get a look.</p>\n\n<p>It is unclear to me if you ever want to load multiple stylesheets. If so this would a second reason to opt for a <code>switch</code> block versus an <code>if-elseif...</code> block.</p>\n\n<p>You probably intend to check if the string is found in <code>$_SERVER['PHP_SELF']</code> or <code>$_SERVER['PHP_URL_PATH']</code>. Each variable must be separately checked (there are different techniques to perform that process).</p>\n\n<p>I think you should choose one reliable source to make your comparison on.</p>\n\n<p>To streamline your code without abandoning secure practices, I recommend a \"whitelist\" array of valid css filenames. If the incoming value exists in the whitelist, include the css file(s) by directly writing the <code>$_SERVER</code> value into the echo line(s).</p>\n\n<p>If you cannot manage to get the 1-to-1 literal variable string to match your css file, then I recommend a lookup array instead of a switch block (because I hate how verbose all those <code>break</code> lines make the script).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:18:33.127", "Id": "428272", "Score": "0", "body": "When you say I recommend a \"whitelist\" array, would this be stored as php Variables inside the actual function or as a json list, if in php does it matter if these are public or private? Can you give any working examples of any such switch statements? With similar goals" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:38:53.383", "Id": "428277", "Score": "0", "body": "I have seen this terminology a few times in different refernces to coding and never really understood it \"\"Truthy or Falsey\" Surely if its true, then its true, false then false. evaluates to 1 || 0 there is no 0.75 in terms of truth? can you give an example of a falsey question &/or a truthy one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T23:36:59.593", "Id": "428320", "Score": "1", "body": "Your whitelist array can be declared as a variable; or because you won't be making any changes to the data, you can declare it as a constant. A constant will be global (will be available everywhere -- no scope-related issues). I can't see any benefit to making the whitelist private. What does php consider to be loosely true or false: https://stackoverflow.com/a/80649/2943403 The execution of my advice is suitably presented at the end of YCS's answer; with exception that I would perform an `isset()` check when accessing the lookup array and issue a fallback action." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T07:43:51.403", "Id": "221465", "ParentId": "221450", "Score": "5" } } ]
{ "AcceptedAnswerId": "221464", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T00:18:26.827", "Id": "221450", "Score": "6", "Tags": [ "php", "css", "security", "url", "dynamic-loading" ], "Title": "Dynamically loading CSS files based on URL or URI in PHP" }
221450
<p>I just started reading <em>Introduction to Algorithms</em> and the first algorithm introduced is the insertion sort.</p> <p>Even though the sort seems to work, I thought I'd ask for feedback right at the start since this is a really new topic to me.</p> <p>This is the JS implementation I came up with based on the pseudo code:</p> <pre><code>function insertionSort(arr) { for (let j = 1; j &lt; arr.length; j++) { let key = arr[j] let i = j - 1 while (i &gt;= 0 &amp;&amp; key &lt; arr[i]) { i-- } arr.splice(i + 1, 0, key) arr.splice(j + 1, 1) console.log(arr) } } const arr = [0, 12, 55, 0, 33333, 5, 1, 7, 2, 3, 3] insertionSort(arr) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T00:58:54.793", "Id": "428220", "Score": "1", "body": "What is the runtime of arr.splice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T01:13:22.590", "Id": "428221", "Score": "0", "body": "@trognanders I don't know... Apart from this, I guess using built in functions kind of defeats the purpose of studying algorithms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T07:03:53.880", "Id": "428234", "Score": "0", "body": "One way of looking a arrays is that they have _keys_ and _values_. I'm sure you're familiar with this. Why then do you have a line where the name of an array value is \"key\"? This line: `let key = arr[j]`. Should this not be: `let value = arr[j];`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T08:02:27.587", "Id": "428235", "Score": "0", "body": "@KIKOSoftware The pseudocode in the book uses the name key, so it might not be that misguided." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T08:15:24.350", "Id": "428237", "Score": "0", "body": "@trognanders Good point. I can understand why they chose it, it's the thing that gets moved, they \"insert the key\", but I still think it is an unfortunate choice." } ]
[ { "body": "<blockquote>\n <p>I just started reading Introduction to Algorithms</p>\n</blockquote>\n\n<p>Do you mean the popular textbook from MIT Press? In a course taught using this book, it would likely not be acceptable to use other library functions like <code>Array.prototype.splice</code>. Here it glosses over a significant part of insertion sort, which is making space for the next value in the already sorted half of the array. It hides what might be an essential factor in runtime analysis. </p>\n\n<p>In the book pseudocode, it shifts the numbers in the while loop using the assignment <code>A[i + 1] = A[i]</code>. That is more standard array usage and should work just fine in JS.</p>\n\n<p>Pragmatically, using JS arrays for analysis of algorithms is problematic because they can quietly increase in size more like an ArrayList in Java than a regular array. The usage of <code>splice</code> in this code causes the array to change size from n to n+1, then back to n, which is not necessarily trivial at runtime.</p>\n\n<blockquote>\n <p>I thought I'd ask for feedback right at the start since this is a really new topic to me.</p>\n</blockquote>\n\n<p>The courses based on this book are often not very heavy on coding, focusing more on reasoning and proofs. As I recall, the book exercises do not feature programming. For hands-on experience implementing algorithms, there may be better books.</p>\n\n<p>In the CS program that I attended, there was an earlier class that used a book like <em>Data Structures and Algorithms in Java</em> by Goodrich and Tamassia which focused heavily on implementation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T08:14:26.003", "Id": "428236", "Score": "1", "body": "Here's [a link to the pseudo code](https://stackoverflow.com/questions/6788987/cant-get-insertion-sort-from-introduction-to-algorithms-3rd-ed-right-where-is), so we can all see what this is about." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T08:12:25.860", "Id": "221469", "ParentId": "221452", "Score": "1" } }, { "body": "<p>What you implemented is good, you can test your implementation thinking all the different inputs you can have:</p>\n\n<ol>\n<li>Array is empty [ ]</li>\n<li>Array is already sorted [1,2] or [1,2,3]</li>\n<li>Array is not sorted [2,1] or [2,1,3]</li>\n</ol>\n\n<p>I have also red the book for school and I can you suggest to not use built in function (it's not the goal of algorithms to learn how to use built in function but how to implement an efficient way to solve a problem. You can simple swap elements with a temporary variable although I think splice() is a in place function. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T08:25:58.093", "Id": "221470", "ParentId": "221452", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T00:56:01.267", "Id": "221452", "Score": "4", "Tags": [ "javascript", "algorithm", "insertion-sort" ], "Title": "JavaScript implementation of insertion sort" }
221452
<p>I never programmed in my life, and I am currently self teaching myself some C++ by reading books, online free classes and googling. After beginning to read about OOP and classes, and after seeing that a Blackjack game would be something simple to implement using the console, I created the following program to play Blackjack on the console (No graphics, just text narrating what's going on).</p> <p>Features:</p> <ul> <li>Aces can be worth 1 or 11, depending on what's better for the score.</li> <li>Dealer forced to hit if it has a soft 17 (score of 17 with at least one Ace).</li> </ul> <p>Not implemented:</p> <ul> <li>Betting system - The player ether lose, tie or win.</li> <li>Split system - The player can't split his hand if dealt a pair.</li> </ul> <hr> <p>card.h</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef CARD_H #define CARD_H #include &lt;iostream&gt; class Card { public: enum CardSuit { CS_S, CS_D, CS_C, CS_H, CS_MAX }; enum CardRank { CR_2, CR_3, CR_4, CR_5, CR_6, CR_7, CR_8, CR_9, CR_T, CR_J, CR_Q, CR_K, CR_A, CR_MAX }; private: CardSuit m_suit; CardRank m_rank; public: Card(CardSuit suit = CS_S, CardRank rank = CR_A) : m_suit {suit}, m_rank {rank} { } void printCard() const; int getCardValue() const; }; #endif </code></pre> <p>card.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include "card.h" void Card::printCard() const { switch (m_rank) { case CR_2: std::cout &lt;&lt; '2'; break; case CR_3: std::cout &lt;&lt; '3'; break; case CR_4: std::cout &lt;&lt; '4'; break; case CR_5: std::cout &lt;&lt; '5'; break; case CR_6: std::cout &lt;&lt; '6'; break; case CR_7: std::cout &lt;&lt; '7'; break; case CR_8: std::cout &lt;&lt; '8'; break; case CR_9: std::cout &lt;&lt; '9'; break; case CR_T: std::cout &lt;&lt; 'T'; break; case CR_J: std::cout &lt;&lt; 'J'; break; case CR_Q: std::cout &lt;&lt; 'Q'; break; case CR_K: std::cout &lt;&lt; 'K'; break; case CR_A: std::cout &lt;&lt; 'A'; break; } switch (m_suit) { case CS_S: std::cout &lt;&lt; 'S'; break; case CS_D: std::cout &lt;&lt; 'D'; break; case CS_C: std::cout &lt;&lt; 'C'; break; case CS_H: std::cout &lt;&lt; 'H'; break; } } int Card::getCardValue() const { switch (m_rank) { case CR_2: return 2; case CR_3: return 3; case CR_4: return 4; case CR_5: return 5; case CR_6: return 6; case CR_7: return 7; case CR_8: return 8; case CR_9: return 9; case CR_T: return 10; case CR_J: return 10; case CR_Q: return 10; case CR_K: return 10; case CR_A: return 11; } return 0; } </code></pre> <p>deck.h</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef DECK_H #define DECK_H #include "card.h" #include &lt;array&gt; #include &lt;vector&gt; #include &lt;iostream&gt; class Deck { private: std::array&lt;Card, 52&gt; m_card; int m_cardIndex; void swapCard(Card &amp;a, Card &amp;b); inline Card* dealCard(); public: std::vector&lt;Card*&gt; m_playerHand; std::vector&lt;Card*&gt; m_dealerHand; Deck() : m_cardIndex {0}, m_playerHand {}, m_dealerHand {} { int index {0}; for (int iii {0}; iii &lt; Card::CS_MAX; ++iii) { for (int jjj {0}; jjj &lt; Card::CR_MAX; ++jjj) { m_card[index] = Card(static_cast&lt;Card::CardSuit&gt;(iii), static_cast&lt;Card::CardRank&gt;(jjj)); ++index; } } } void printDeck() const; void shuffleDeck(int xTimes); void dealPlayer(); void dealDealer(); }; inline Card* Deck::dealCard() { return &amp;m_card[m_cardIndex++]; } #endif </code></pre> <p>deck.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include "deck.h" #include &lt;random&gt; #include &lt;chrono&gt; namespace Rng { const auto seed {std::chrono::high_resolution_clock::now().time_since_epoch().count()}; std::mt19937 mt {static_cast&lt;unsigned long int&gt;(seed)}; int rng(int min, int max) { std::uniform_int_distribution&lt;&gt; rng {min, max}; return rng(mt); } } void Deck::swapCard(Card &amp;a, Card &amp;b) { Card temp {a}; a = b; b = temp; } void Deck::printDeck() const { for (int iii {0}; iii &lt; 52; ++iii) { m_card[iii].printCard(); if (((iii + 1) % 13 == 0) &amp;&amp; iii != 0) std::cout &lt;&lt; '\n'; else std::cout &lt;&lt; ' '; } } void Deck::shuffleDeck(int xTimes = 1) { for (int iii {0}; iii &lt; xTimes; ++iii) { for (int jjj {0}; jjj &lt; 52; ++jjj) { swapCard(m_card[jjj], m_card[Rng::rng(0, 51)]); } } m_cardIndex = 0; m_playerHand.clear(); m_dealerHand.clear(); } void Deck::dealPlayer() { int index {static_cast&lt;int&gt;(m_playerHand.size())}; m_playerHand.resize(index + 1); m_playerHand[index] = dealCard(); } void Deck::dealDealer() { int index {static_cast&lt;int&gt;(m_dealerHand.size())}; m_dealerHand.resize(index + 1); m_dealerHand[index] = dealCard(); } </code></pre> <p>main.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include "card.h" #include "deck.h" #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; int getPoints(std::vector&lt;Card*&gt; &amp;hand) { int score {0}; int acesCount {0}; for (auto &amp;card : hand) { score += card-&gt;getCardValue(); if (card-&gt;getCardValue() == 11) ++acesCount; } if (score &gt; 21 &amp;&amp; acesCount != 0) { do { score -= 10; --acesCount; } while (score &gt; 21 &amp;&amp; acesCount &gt; 0); } return score; } void playGame(Deck &amp;gameDeck) { gameDeck.shuffleDeck(20); gameDeck.dealPlayer(); gameDeck.dealDealer(); gameDeck.dealPlayer(); gameDeck.dealDealer(); std::cout &lt;&lt; "You were dealt |"; gameDeck.m_playerHand[0]-&gt;printCard(); std::cout &lt;&lt; "| |"; gameDeck.m_playerHand[1]-&gt;printCard(); std::cout &lt;&lt; "|\nDealer was dealt |"; gameDeck.m_dealerHand[0]-&gt;printCard(); std::cout &lt;&lt; "| and a card facing down\nThe dealer peaks at the hole card.\n"; int playerScore {getPoints(gameDeck.m_playerHand)}; int dealerScore {getPoints(gameDeck.m_dealerHand)}; if (playerScore == 21 &amp;&amp; dealerScore != 21) { std::cout &lt;&lt; "You have a Blackjack!\n" "You win the game."; return; } else if (dealerScore == 21 &amp;&amp; playerScore != 21) { std::cout &lt;&lt; "The dealer flips the hole card to reveal " "a Blackjack with cards |"; gameDeck.m_dealerHand[0]-&gt;printCard(); std::cout &lt;&lt; "| and |"; gameDeck.m_dealerHand[1]-&gt;printCard(); std::cout &lt;&lt; "|\nYou lose the game.\n"; return; } else if (playerScore == 21 &amp;&amp; dealerScore == 21) { std::cout &lt;&lt; "You have a Blackjack.\n" "The dealer flips the hole card to reveal" "a Blackjack with cards |"; gameDeck.m_dealerHand[0]-&gt;printCard(); std::cout &lt;&lt; "| and |"; gameDeck.m_dealerHand[1]-&gt;printCard(); std::cout &lt;&lt; "|\nThe game is a tie\n."; return; } // Player Hit loop: bool exitPlayerLoop {false}; while (!exitPlayerLoop) { std::cout &lt;&lt; "Choose your action: [H]it or [S]tand\n"; std::string action {}; std::cin &gt;&gt; action; switch (action.front()) { case 'h': case 'H': { gameDeck.dealPlayer(); std::cout &lt;&lt; "You were dealt a |"; gameDeck.m_playerHand[gameDeck.m_playerHand.size() - 1]-&gt;printCard(); std::cout &lt;&lt; "|\nYour hand is"; for (auto &amp;card : gameDeck.m_playerHand) { std::cout &lt;&lt; " |"; card-&gt;printCard(); std::cout &lt;&lt; '|'; } std::cout &lt;&lt; '\n'; playerScore = getPoints(gameDeck.m_playerHand); if (playerScore &gt; 21) { std::cout &lt;&lt; "You busted. You lose the game.\n\n"; return; } } break; case 's': case 'S': { std::cout &lt;&lt; "You stood. Your hand is"; for (auto &amp;card : gameDeck.m_playerHand) { std::cout &lt;&lt; " |"; card-&gt;printCard(); std::cout &lt;&lt; '|'; } exitPlayerLoop = true; } break; default: std::cout &lt;&lt; "Invalid input\n"; } } std::cout &lt;&lt; "\nThe dealer flips the hole card. It reveals a |"; gameDeck.m_dealerHand[1]-&gt;printCard(); std::cout &lt;&lt; "|\n"; // Dealer hit loop: bool exitDealerLoop {false}; while (!exitDealerLoop) { int dealerAcesCount {0}; for (auto &amp;card : gameDeck.m_dealerHand) { if (card-&gt;getCardValue() == 11) ++dealerAcesCount; } dealerScore = getPoints(gameDeck.m_dealerHand); if (dealerScore &lt; 17 || (dealerScore == 17 &amp;&amp; dealerAcesCount &gt; 0)) { gameDeck.dealDealer(); std::cout &lt;&lt; "Dealer hits and was dealt a |"; gameDeck.m_dealerHand[gameDeck.m_dealerHand.size() - 1]-&gt;printCard(); std::cout &lt;&lt; "|\n"; continue; } std::cout &lt;&lt; "Dealer hand:"; for (auto &amp;card : gameDeck.m_dealerHand) { std::cout &lt;&lt; " |"; card-&gt;printCard(); std::cout &lt;&lt; '|'; } std::cout &lt;&lt; '\n'; exitDealerLoop = true; } playerScore = getPoints(gameDeck.m_playerHand); dealerScore = getPoints(gameDeck.m_dealerHand); if (dealerScore &gt; 21) { std::cout &lt;&lt; "The dealer busted. You win the game!\n\n"; } else if (playerScore &gt; dealerScore) { std::cout &lt;&lt; "You win the game!\n\n"; } else if (playerScore &lt; dealerScore) { std::cout &lt;&lt; "You lose the game.\n\n"; } else if (playerScore == dealerScore) { std::cout &lt;&lt; "The game is a draw.\n\n"; } return; } int main() { std::cout &lt;&lt; " Welcome to Blackjack!\n" "* * RULES: Dealer must hit soft 17 * *\n\n"; Deck gameDeck; bool exitLoop {false}; while (!exitLoop) { playGame(gameDeck); bool validChoice = false; while (!validChoice) { std::cout &lt;&lt; "Play again? &lt;Y/N&gt;\n"; std::string choice {}; std::cin &gt;&gt; choice; switch (choice.front()) { case 'y': case 'Y': validChoice = true; break; case 'n': case 'N': validChoice = true; exitLoop = true; break; default: std::cout &lt;&lt; "Invalid choice.\n"; } } } std::cout &lt;&lt; "\nThank you for playing!\n"; return 0; } </code></pre> <hr> <p>I tried to put in functions the methods that were used more than once only, hence the long <code>void playGame(Deck &amp;gameDeck)</code> function.</p> <p>Considering that I am just beginning to learn the language, I want some improvement advice: What are my bad habits? What are my rookie mistakes? Should I separate the huge <code>void playGame(Deck &amp;gameDeck)</code> function into smaller ones? Am I doing the multi file division the right way? I aimed for a file and header per class. Anything you guys would change to this particular program? Any advice to me in general?</p> <p>PS: Can I move those enums out of the header file? I tried but with no success. They look ugly in a header file...</p> <p><strong>EDIT:</strong> I lied about never programming in my life. I did some RPGs with Rpg Maker 2000 during my youth. It had a basic scripting language. </p>
[]
[ { "body": "<p>In C++ <code>&amp;</code>/<code>*</code> belongs with type. E.g. <code>void swapCard(Card&amp; a, Card&amp; b);</code></p>\n\n<hr>\n\n<p>The CTOR member init list becomes easier to read (IMO) when formatted like this:</p>\n\n<pre><code>Deck() \n : m_cardIndex {0}\n , m_playerHand {}\n , m_dealerHand {}\n</code></pre>\n\n<hr>\n\n<p>You can and should use <code>enum class</code> over the \"normal\" one.<br>\n(Taken from <a href=\"https://stackoverflow.com/questions/18335861/why-is-enum-class-preferred-over-plain-enum\">here</a>):</p>\n\n<blockquote>\n <p><strong>What is the difference between two?</strong></p>\n \n <ul>\n <li><p>enum classes - enumerator names are local to the enum and their values do not implicitly convert to other types (like another enum or int)</p></li>\n <li><p>Plain enums - where enumerator names are in the same scope as the enum and their values implicitly convert to integers and other types</p></li>\n </ul>\n \n <p>enum classes should be preferred because they cause fewer surprises that could potentially lead to bugs.</p>\n</blockquote>\n\n<hr>\n\n<p>You're already wrapping your random number generation in a separate namespace so why not your own classes in general?<br>\nE.g.:</p>\n\n<pre><code>namespace ConsoleBlackjack\n{\n\nclass Card\n{\n[...]\n\n} // namespace ConsoleBlackjack\n</code></pre>\n\n<hr>\n\n<p>Subjective but <code>iii</code>/<code>jjj</code> seem unusual for a loop variable. Any specific reason for doing it this way?</p>\n\n<hr>\n\n<p>Perhaps you could make use of <a href=\"https://en.cppreference.com/w/cpp/algorithm/random_shuffle\" rel=\"nofollow noreferrer\">std::shuffle</a> instead of having to roll your own.</p>\n\n<hr>\n\n<p>It would be good to get rid of your magic numbers (e.g. 5, 13, 17, 21, 52, 51 etc.). Instead turn them into named constants.<br>\n<code>CS_MAX</code> and <code>CR_MAX</code> should IMO also be turned into separate named constants instead of riding with the enums. </p>\n\n<hr>\n\n<p>Use compiler warnings. I'm not sure which compiler you use but you should always enable and try to fix the compiler warnings.\nThe way you enable them differs by compiler. It's best to look this up based on your compiler.</p>\n\n<hr>\n\n<p>You're missing a <code>default</code> statement in your <code>switch</code>es. This is a good reason to use compiler warnings. In this case you didn't miss any fields but it still complains because you put constants in there that should be separate (see above).</p>\n\n<hr>\n\n<p>You should declare the RNG parts <code>static</code> as they are expensive. Have a look at <a href=\"https://codereview.stackexchange.com/questions/213842/rock-paper-scissors-engine\">this excellent code</a> to see how it can be done (specifically the <code>RockPaperScissors RockPaperScissors::random()</code> part).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T12:27:06.470", "Id": "428257", "Score": "0", "body": "this is the kind of answer I was expecting! I usually code with my phone using c4droid, because I don't have much home free time, so I use my mobile to learn it. The compiler it uses is g++ +Bionic. Don't know what to do, because the code doesn't throw me any warnings... When I move the code to visual studio it also doesn't show any warnings... Hmmm" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T13:04:06.143", "Id": "428259", "Score": "0", "body": "@msmilkshake Usually warnings have to be explicitly enabled. I don't have much experience with visual studio but maybe this can help: https://www.learncpp.com/cpp-tutorial/configuring-your-compiler-warning-and-error-levels/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T13:45:22.273", "Id": "428263", "Score": "0", "body": "about your answer: `You're already wrapping your random number generation in a separate namespace so why not your own classes in general?` Whad to you mean? create a namespace for my classes? ; I use iii and jjj because I learned that using i, j, k alone ca be hard to find using ctrl+f. iii, jjj, kkk as counters are easier to find using ctrl+f" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T14:06:56.877", "Id": "428264", "Score": "0", "body": "@msmilkshake (1) I meant just using namespaces for your classes, I updated the answer to hopefully make this clearer. (2) I've never heard of that advice but then again I also never tried searching for my loop variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T19:32:51.043", "Id": "428297", "Score": "0", "body": "What warning argument should I add to my compiler to detect the missing default case?" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T08:03:01.687", "Id": "221466", "ParentId": "221454", "Score": "5" } }, { "body": "<blockquote>\n <p>I never programmed in my life, and I am currently self teaching myself some C++ by reading books, online free classes and googling.</p>\n</blockquote>\n\n<p>If that is true, then I applaud you. This code is better than some code I've seen from people who \"know what they're doing\". For one thing, I understood it and could tell what you were trying to do. Of course, you can still improve a lot. Don't take this as a \"okay, I don't need to learn anything more\". Everyone can get better, except people who mistakenly think they're already the best. But for a first try, not bad. Anyway, on with the review.</p>\n\n<blockquote>\n <p>PS: Can I move those enums out of the header file? I tried but with no success. They look ugly in a header file...</p>\n</blockquote>\n\n<p>Short answer no. It is necessary in the header file because you use the enums almost immediately on the next couple lines:</p>\n\n<pre><code>private:\n CardSuit m_suit;\n CardRank m_rank;\n</code></pre>\n\n<p>So you can't just remove them. If you don't like how they look, you will have to come up with another solution for <code>m_suit</code> and <code>m_rank</code>.</p>\n\n<p>Not that you want them out of the header. If they are not in the header, then other things like your <code>main()</code> function can't use them. If they are in the header, it makes using them easier.</p>\n\n<blockquote>\n <p>I tried to put in functions the methods that were used more than once only, hence the long void playGame(Deck &amp;gameDeck) function.</p>\n</blockquote>\n\n<p>If what you're saying is that only functions that get used more than once become part of the class, then I say you're on the right track.</p>\n\n<p>Generally, you want functions that are specific to the data in the class to be methods of that class. You don't want anything that has nothing to do with the class, or is program specific being part of that class.</p>\n\n<p>The reason is let's say you decide to make a Solitaire game for example. Well, you've already written a <code>Card</code> class and a <code>Deck</code> class. Those classes you could probably use again in solitaire. Thus, anything that you think might find use in Solitaire, you might want to make part of the class. So <code>Deck::shuffleDeck()</code> for example, might find use in Solitaire, so it's a good fit to make part of the class. <code>playGame()</code>, however, is program specific. It has no use in a Solitaire game, on in Blackjack. Thus, it's a bad candidate to make part of the class.</p>\n\n<p>All of that to say, I guess, is that <code>playGame()</code> doesn't need to be part of <code>Deck</code>. Good choice.</p>\n\n<blockquote>\n <p>Am I doing the multi file division the right way? I aimed for a file and header per class.</p>\n</blockquote>\n\n<p>Yup. Your headers are great in my opinion. However, others may say that they are just good.</p>\n\n<blockquote>\n <p>Should I separate the huge void playGame(Deck &amp;gameDeck) function into smaller ones?</p>\n</blockquote>\n\n<p>It does seem a little big. Sub-functions would reduce repeated code. Not fully sure how you can reduce at the moment, other than maybe if there was a was a way to not repeat the dealer and player hit process. Again, not sure how exactly you could do that at the moment, but that would help. Any place you've repeated the same basic code, a function will help.</p>\n\n<blockquote>\n <p>What are my bad habits? What are my rookie mistakes?</p>\n</blockquote>\n\n<p>I didn't look at the code closely enough to give a complete answer, but one I did catch was this:</p>\n\n<pre><code>public:\n std::vector&lt;Card*&gt; m_playerHand;\n std::vector&lt;Card*&gt; m_dealerHand;\n</code></pre>\n\n<p>Generally, it's better to keep these private if you can. Then, make a public interface for them. So, you could do, for instance:</p>\n\n<pre><code>class Deck {\n private:\n std::vector&lt;Card*&gt; m_playerHand;\n public:\n std::vector&lt;Card*&gt;&amp; getPlayerHand() { return m_playerHand; }\n}\n</code></pre>\n\n<p>You may have a good reason to make them public, or it may be just easier to make them public. But, if you can make them private, it is usually better to do so.</p>\n\n<blockquote>\n <p>Anything you guys would change to this particular program? Any advice to me in general?</p>\n</blockquote>\n\n<p>This one I have several points for improvements:</p>\n\n<ol>\n<li>Consider adding a <code>ostream&amp;</code> parameter to <code>Card::PrintCard()</code></li>\n</ol>\n\n<p>The reason I am suggesting this is because right now there is no way to re-direct the print of card. It only goes to <code>std::cout</code>. If you want to make it go to <code>std::cerr</code> or a <code>fstream</code>, for instance, you can't. Your code would be much more flexible if it accepted a <code>ostream</code> like this:</p>\n\n<pre><code>void Card::printCard(ostream&amp; stream) const\n{\n switch (m_rank)\n {\n case CR_2: stream &lt;&lt; '2'; break;\n case CR_3: stream &lt;&lt; '3'; break;\n case CR_4: stream &lt;&lt; '4'; break;\n case CR_5: stream &lt;&lt; '5'; break;\n case CR_6: stream &lt;&lt; '6'; break;\n case CR_7: stream &lt;&lt; '7'; break;\n case CR_8: stream &lt;&lt; '8'; break;\n case CR_9: stream &lt;&lt; '9'; break;\n case CR_T: stream &lt;&lt; 'T'; break;\n case CR_J: stream &lt;&lt; 'J'; break;\n case CR_Q: stream &lt;&lt; 'Q'; break;\n case CR_K: stream &lt;&lt; 'K'; break;\n case CR_A: stream &lt;&lt; 'A'; break;\n }\n\n switch (m_suit)\n {\n case CS_S: stream &lt;&lt; 'S'; break;\n case CS_D: stream &lt;&lt; 'D'; break;\n case CS_C: stream &lt;&lt; 'C'; break;\n case CS_H: stream &lt;&lt; 'H'; break;\n }\n}\n</code></pre>\n\n<p>Of course, this breaks current code, since the current code isn't expecting a parameter, so you can overload the function lie this if you want:</p>\n\n<pre><code>void Card::printCard() const\n{\n printCard(std:cout);\n}\n</code></pre>\n\n<p>That will make current code continue to work while making your printing far more flexible.</p>\n\n<ol start=\"2\">\n<li>Consider adding a stream operator</li>\n</ol>\n\n<p>Now, all I said about #1 is good, but there's another reason to implement a <code>printCard()</code> function that takes a <code>ostream</code> as a parameter. That is because creating a stream operator for our card class really easy:</p>\n\n<pre><code>ostream&amp; operator &lt;&lt;(ostream&amp; stream, Card c) {\n c.printCard(stream);\n\n return stream;\n}\n</code></pre>\n\n<p>Now, with that in place, you have a new way to print to <code>std::cout</code>, and it looks like this:</p>\n\n<pre><code>std::cout &lt;&lt; myCard;\nstg::cout &lt;&lt; \"We can even put a message here: \" &lt;&lt; myCard &lt;&lt; \" and even put a message after, if we want too!\\n\";\n</code></pre>\n\n<p>In fact, <code>std::cerr</code> and <code>fstreams</code> work this way too. It makes things a lot easier.</p>\n\n<ol start=\"3\">\n<li>Consider making a <code>Hand</code> class</li>\n</ol>\n\n<p>Instead of using <code>std::vector&lt;Card*&gt;</code>, it would be much easier if you made a <code>Hand</code> class, or even a using or typedef name called <code>Hand</code>. It would look something like this:</p>\n\n<pre><code>class Hand {\n // Option 1: create a class\n};\n// Or...\n// Option 2: use using.\nusing Hand = std::vector&lt;Card*&gt;;\n// or...\n// Option 3: use a typedef\ntypedef std::vector&lt;Card*&gt; Hand;\n\n</code></pre>\n\n<p>Options 1 and 2 are preferred. Use 3 if you have to for some crazy unforseen reason.</p>\n\n<p>This way, you can make a general purpose <code>Deck::deal()</code> function that would replace <code>Deck::dealPlayer()</code> and <code>Deck::dealDealer()</code>:</p>\n\n<pre><code>void Deck::deal(Hand&amp; hand) {\n // implementation...\n}\n</code></pre>\n\n<p>And turn the dealer and player hands into a <code>Hand</code>:</p>\n\n<pre><code>public:\n Hand m_playerHand;\n Hand m_dealerHand;\n</code></pre>\n\n<p>You know, this leads me to my next point:</p>\n\n<ol start=\"4\">\n<li><code>m_playerHand</code> and <code>m_dealerHand</code> seem unneeded as members of <code>Deck</code></li>\n</ol>\n\n<p>Instead, it feels like you should use them as member variables in <code>playGame()</code> instead:</p>\n\n<pre><code>void playGame(Deck &amp;gameDeck)\n{\n Hand playerHand;\n Hand dealerHand;\n\n // implementation...\n\n // then, if you take suggestion number 3, you can fill it like this:\n gameDeck.deal(playerHand);\n gameDeck.deal(dealerHand);\n\n}\n</code></pre>\n\n<p>I'm sure there are lots of other things you could do, but I think this will get you started. Once you take my suggestions and yuri's suggestions, it will probably become more apparent how you could reduce your code even more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T00:05:49.953", "Id": "428479", "Score": "0", "body": "I should also note that once you take our suggestions, [you can ask a new question with the new code](https://codereview.stackexchange.com/help/someone-answers) if you want more feedback. If not, that's okay too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T06:26:20.190", "Id": "428654", "Score": "0", "body": "Hey. Great answer! Never thought anybody would put this much work in reviewing code for rookies! I am mostly learning from learncpp.com and I haven't reached the operator overloading lessons yet, but I saw that those are gonna be discussed after where I am, so I didn't do any overloading because I simply didn't discuss it. There are a lot of good improvements in this answer and I am going to try to put them all in action. Things look way cleaner with them. That hand class looks like a really good adittion! To see if I got it: I would instantiate two hand objects, one for the dealer and one" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T06:30:40.820", "Id": "428656", "Score": "0", "body": "... For the player? Oh, I also don't know how templates work yet. I have a lot to learn and gotta keep reading those learcpp lessons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T06:33:25.040", "Id": "428658", "Score": "0", "body": "Yes. One for the dealer and player." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T06:34:32.157", "Id": "428659", "Score": "0", "body": "Also, that's totally fine to not know operator overloading yet. It was a suggestion just in case you knew how to do that. Glad you're continuing to learn." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T06:46:42.103", "Id": "428662", "Score": "0", "body": "Will probably take two plus weeks for me to improve this program, because my free time is... Short... But once I've done it, I will definitely put it in a new question as suggested." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T00:04:17.120", "Id": "221565", "ParentId": "221454", "Score": "4" } }, { "body": "<p>Adding onto @Chipster's answer, I'd like to suggest some improvements for the Deck class:</p>\n\n<pre><code>class Deck\n{\nprivate:\n std::array&lt;Card, 52&gt; m_card;\n int m_cardIndex;\n\n void swapCard(Card &amp;a, Card &amp;b);\n inline Card* dealCard();\n\npublic:\n std::vector&lt;Card*&gt; m_playerHand;\n std::vector&lt;Card*&gt; m_dealerHand;\n\n ...\n\n void printDeck() const;\n void shuffleDeck(int xTimes);\n void dealPlayer();\n void dealDealer();\n};\n</code></pre>\n\n<ol>\n<li><p>As @yuri suggested, make a <code>DECK_SIZE</code> variable that maybe gets set via a constructor to get rid of the magic number of 52 (you could use templates for this), even though that's the standard deck size. Also, <code>m_card</code> in the singular doesn't make sense to me. I'd say <code>m_cards</code> (or simply <code>cards</code> to get rid of the <a href=\"https://softwareengineering.stackexchange.com/a/102690/333842\">unnecessary Hungarian notation</a> altogether).</p></li>\n<li><p>From an object-oriented perspective, it doesn't make sense for a <code>Deck</code> to have <code>m_playerHand</code> and <code>m_dealerHand</code>. It makes more sense for these to be part of player and dealer classes (but players and dealers share a lot of common functionality, so a class hierarchy may make sense here—maybe an abstract base class of <code>BlackjackEntity</code>).</p></li>\n<li><p><code>printDeck()</code> is fine, but it can be replaced with the following <a href=\"http://www.cplusplus.com/doc/tutorial/inheritance/\" rel=\"nofollow noreferrer\">friend function</a>:</p></li>\n</ol>\n\n<p><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Deck&amp; deck)</code></p>\n\n<p>This would allow you to simply <code>std::cout &lt;&lt; referenceToDeck</code>.</p>\n\n<ol start=\"4\">\n<li>And finally, <code>dealPlayer</code> and <code>dealDealer</code> do exactly the same thing, just to different entities. Moreover, it makes more sense to move the <code>dealTo</code> method to the <code>Dealer</code> class (assuming you go down that route) and change its signature to be:</li>\n</ol>\n\n<p><code>void Dealer::dealTo(Deck&amp; deck, BlackjackEntity&amp; recipient)</code></p>\n\n<p>After all, it's the <code>Dealer</code> who deals, not the deck. The deck simply has the capacity to be dealt. This method would then call <code>deck.dealCard()</code> to get the card and give it to <code>recipient</code>, which is either <code>this</code> or a reference to the player. For this to work, both <code>Dealer</code> and <code>Player</code> would have to subclass <code>BlackjackEntity</code>. That base class would provide all methods common to <code>Dealer</code>s and <code>Player</code>s. The subclasses would add any methods unique to their respective entities (like dealing for the <code>Dealer</code>).</p>\n\n<p>Hope that helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T06:39:29.910", "Id": "428660", "Score": "0", "body": "Never heard of the Hungarian notation term before. I'm gonna Google that. The free lessons I'm reading online suggest that member functions should be written with prefix m_ just so people can tell they are member variables. To the rest of your answer, that all makes a lot of sense. I can picture it in my head now what methods belong to classes and what methods don't belong and would better live in their own classes. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T13:20:02.117", "Id": "428719", "Score": "0", "body": "No problem! Yeah, the link I sent to the answer discusses some notable problems with Hungarian notation. Mainly, it makes your code very noisy (and, on bigger projects, much harder to maintain and write). It was originally intended for non-statically-typed languages (e.g., Python)—in other words, languages whose type is determined at runtime (as the program is running) as opposed to compile time. But with C++, this isn't a problem because the language is statically typed :) You have to say `int x`. Besides, if you're using an IDE, it should be easy to verify the type of a variable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T01:18:56.783", "Id": "221566", "ParentId": "221454", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T02:52:00.703", "Id": "221454", "Score": "9", "Tags": [ "c++", "beginner", "object-oriented", "c++11", "playing-cards" ], "Title": "Console Blackjack game, without split or betting system for now" }
221454
<p>I'm finally learning Haskell this summer and I have a few questions about conventions. I made a simple prime factorization program which is surprisingly fast, much faster than the ones I made in C++ (though to be fair I made those non-recursively). </p> <p>It consists of three functions: one checks if a num is prime, one finds the prime factors, and one checks if a list's length is less than a number. The last one is because I was worried that take and length would be too slow and the <a href="https://wiki.haskell.org/Haskell_programming_tips#Don.27t_ask_for_the_length_of_a_list_when_you_don.27t_need_it" rel="noreferrer">Haskell wiki</a> agreed. I just copied and pasted their at least function and reversed it. </p> <pre><code>import Data.List import Data.Ord isPrime :: Integer -&gt; Bool primes :: Integer -&gt;[Integer] isLengthLessThan :: Int -&gt; [a] -&gt; Bool isLengthLessThan 0 _ = False isLengthLessThan _ [] = True isLengthLessThan n (_:ys) = isLengthLessThan (n-1) ys isPrime x | x == 2 = True | mod x 2 == 0 = False | otherwise = isLengthLessThan 2 [y | y &lt;- [1,3.. roof], mod x y == 0] where roof = 1 + truncate (sqrt $fromIntegral x) primes x | isPrime x = [x] | otherwise = factor : primes(div x factor) where factor = head $filter checkdiv [2..] checkdiv n = x `mod` n == 0 </code></pre> <p>Finally the questions: </p> <ul> <li><p>Should <code>isLengthLessThan</code> be in a <code>where</code> under <code>isPrime</code>?</p></li> <li><p>Is <code>isLengthLessThan</code>'s name too verbose?</p></li> <li><p>What should I name my "primes" function?</p></li> <li><p>Are the function type specifications called that or declarations?</p></li> <li><p>Should I put the type specifications right before the function or should I put it at the start?</p></li> <li><p>Do specifications help speed or do they only help us by giving us better errors?</p></li> <li><p>Do parenthesis make compilation faster or do they only muddle code up?</p></li> </ul>
[]
[ { "body": "<ul>\n<li>Yes, but you don't need it.</li>\n<li>It is good that your intuition tells you to give this function this long a name: It tells you to get rid of it. While you can't get rid of it, keep the name long as a symbol of shame.</li>\n<li><code>factors</code>.</li>\n<li>Annotations.</li>\n<li>Right before. If all goes well, your definition will have form <code>foo = bar $ _</code> where <code>bar</code> is some library function that tells the experienced reader what sort of definition he's looking at, much like the type does.</li>\n<li>They do not directly help speed, but in my estimation can make it easy to make code simple/short, and therefore easy to improve in any direction.</li>\n<li>Parentheses do not influence compilation noticably. Optimize for readability.</li>\n</ul>\n\n\n\n<pre><code>isPrime = null [y | y &lt;- 2:[3,5..floor $ sqrt $ fromIntegral x], mod x y == 0]\n</code></pre>\n\n<p>Or rather:</p>\n\n<pre><code>primes 1 = []\nprimes x = factor : primes (div x factor) where\n factor = head $ [y | y &lt;- 2:[3,5..floor $ sqrt $ fromIntegral x], mod x y == 0] ++ [x]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T14:54:20.893", "Id": "221488", "ParentId": "221455", "Score": "3" } }, { "body": "<p>First, a few stylistic points:</p>\n\n<ul>\n<li>It's more common to write the <code>div</code> and <code>mod</code> functions in infix, as <code>x `mod` y == 0</code>, etc.</li>\n<li>A parenthesized argument to a function is <em>never</em> written <code>f(x)</code>. It's always with a separating space like <code>f (x)</code>, so you want <code>primes (x `div` factor)</code>.</li>\n<li>The infix operator <code>$</code> is pretty much always both preceded and followed by a space.</li>\n<li>Similarly, in the <code>[x..y]</code> syntax, the <code>..</code> is normally <em>not</em> surrounded by any space, though when it is, it is <em>both</em> preceded and followed by space, so either <code>[1,3..roof]</code> or <code>[1, 3 .. roof]</code> would be more common than <code>[1,3.. roof]</code>.</li>\n</ul>\n\n<p>and some advice on functions:</p>\n\n<ul>\n<li><code>even x</code> is preferred to <code>x `mod` 2 == 0</code></li>\n<li>For positive values, <code>1 + truncate x</code> can be replaced with <code>ceiling x</code>. Technically, though, you don't need to check any numbers greater than the square root, so <code>floor (sqrt $ fromIntegral x)</code> works in your case.</li>\n<li><p>Also for positive values, the function pair <code>quot/rem</code> is equivalent to <code>div/mod</code> and the former can compile to faster code on x86_64 (e.g., <code>quot</code> on <code>Int</code>s can be a single machine instruction), so many Haskellers will get in the habit of using them whenever the substitution works. (Alternatively, this is a ridiculous micro-optimization here, so sticking with the <code>div/mod</code> pair is fine if it looks more natural.)</p>\n\n<p>However, it might be even better to introduce a predicate:</p>\n\n<pre><code>divides :: (Integral a) =&gt; a -&gt; a -&gt; Bool\ndivides d n = n `rem` d == 0\n</code></pre>\n\n<p>so you can write <code>y `divides` x</code> in your list comprehension, and use the section <code>(`divides` x)</code> in your <code>filter</code>.</p></li>\n</ul>\n\n<p>Finally, it's usual practice to provide type signatures that are more general than the ones you've provided. Certainly, generalizing <code>primes</code> and <code>isPrime</code> to all integral types would be usual:</p>\n\n<pre><code>isPrime :: (Integral a) =&gt; a -&gt; Bool\nprimes :: (Integral a) =&gt; a -&gt; [a]\n</code></pre>\n\n<p>On the other hand, <code>isLengthLessThan</code> is probably fine the way it as, as it's usual to assume list lengths will fit in a 64-bit <code>Int</code>, for obvious reasons.</p>\n\n<p>Now, with respect to your questions:</p>\n\n<blockquote>\n <p>Should <code>isLengthLessThan</code> be in a where under <code>isPrime</code>?</p>\n</blockquote>\n\n<p>That's up to you. A utility function that's used in only one function is often included in a <code>where</code> clause, though if the function seems \"independently useful\", it's sometimes kept at top-level. In this small module, keeping it at top level seems reasonable. In a bigger module, you might stick it in a <code>where</code> clause to reduce clutter.</p>\n\n<p>Rearranging the functions can also help. If you put <code>primes</code> at the top and then put utility functions after the functions that use them (e.g., <code>primes</code>, then <code>isPrime</code>, then <code>isLengthLessThan</code>), it can make it easier to follow the program's organization.</p>\n\n<blockquote>\n <p>Is <code>isLengthLessThan</code>'s name too verbose?</p>\n</blockquote>\n\n<p>I'd say so. Maybe <code>shorterThan</code>? Note that the character count is probably less of an issue than the word count -- <code>shorterThan</code> is simple to read and understand; <code>isLengthLessThan</code> belongs in a Java program as a method in the <code>ListLengthCheckerFactory</code> class. But also, see below for how to eliminate this function entirely.</p>\n\n<blockquote>\n <p>What should I name my \"primes\" function?</p>\n</blockquote>\n\n<p>I'd say <code>factors</code> -- I mean, it's obviously going to be the prime factorization, because what other <code>factors</code> function would make sense?</p>\n\n<blockquote>\n <p>Are the function type specifications called that or declarations?</p>\n</blockquote>\n\n<p>According to the <a href=\"https://www.haskell.org/definition/haskell2010.pdf\" rel=\"nofollow noreferrer\">Haskell 2010 Report</a>, they're called \"type signatures\", and the corresponding function definitions <code>f x = ...</code> are called \"bindings\". <strong>Both</strong> type signatures and bindings are examples of \"declarations\", so <code>isPrime :: Int -&gt; Bool</code> is a declaration, but so is <code>isPrime x = ...</code>. However, in informal speech, if you asked \"should this binding have a type declaration?\", everyone would know what you meant.</p>\n\n<blockquote>\n <p>Should I put the type specifications right before the function or should I put it at the start?</p>\n</blockquote>\n\n<p>Almost universally in Haskell code, type signatures are placed immediately preceding the corresponding binding rather than collected together at the beginning of the module. While collecting them together probably seems like a nice way of documenting the \"interface\" at the top of the module, it has the drawback that someone stumbling across the definition may assume there's no type signature (as signatures are often optional) and so never see it, and what's more the standard Haddock documentation tool is set up to have the signature and definition of each binding in the same place.</p>\n\n<blockquote>\n <p>Do specifications help speed or do they only help us by giving us better errors?</p>\n</blockquote>\n\n<p>If the type signature matches what would be inferred by GHC if it was missing (which is often the most general possible type), then there is no effect on generated code. Moreover, GHC is designed to generate efficient code even when highly generalized signatures are used, by specializing and inlining functions aggressively. You could most likely drop your signatures, or use the signatures I suggested above with no effect on performance.</p>\n\n<p>So, yes, type signatures are primarily useful for generating better error messages, occasionally for catching certain design errors, and -- when the code is finished -- for documenting the interface.</p>\n\n<blockquote>\n <p>Do parenthesis make compilation faster or do they only muddle code up?</p>\n</blockquote>\n\n<p>Any effect of parentheses on compilation speed will be miniscule, and it's standard Haskell style to omit them except where they are necessary.</p>\n\n<p>Anyway, incorporating the advice I gave above, my version of your program currently looks like the following. Note that I turned on <code>-Wall</code>, which reminded me that your program doesn't actually need the modules it imports, and let me know that there was a type defaulting going on in the <code>sqrt</code> call that I thought should be made explicit. I also ran <code>hlint</code> on it, which didn't have any hints for me.</p>\n\n<pre><code>{-# OPTIONS_GHC -Wall #-}\n\nmodule MorePrimes where\n\nfactors :: (Integral a) =&gt; a -&gt; [a]\nfactors x\n | isPrime x = [x]\n | otherwise = factor : factors (x `div` factor)\n where factor = head $ filter (`divides` x) [2..]\n\nisPrime :: (Integral a) =&gt; a -&gt; Bool\nisPrime x\n | x == 2 = True\n | even x = False\n | otherwise = shorterThan 2 [y | y &lt;- [1,3..roof], y `divides` x]\n where roof = floor $ sqrt (fromIntegral x :: Double)\n\nshorterThan :: Int -&gt; [a] -&gt; Bool\nshorterThan 0 _ = False\nshorterThan _ [] = True\nshorterThan n (_:ys) = shorterThan (n-1) ys\n\ndivides :: (Integral a) =&gt; a -&gt; a -&gt; Bool\ndivides d n = n `rem` d == 0\n</code></pre>\n\n<p>Finally, some additional optimizations.</p>\n\n<p>Your test in the third case of <code>isPrime</code> can be simplified. Since <code>1</code> always divides <code>x</code>, you can replace the test with:</p>\n\n<pre><code>shorterThan 1 [y | y &lt;- [3,5..roof], y `divides` x]\n</code></pre>\n\n<p>which is equivalent to:</p>\n\n<pre><code>null [y | y &lt;- [3,5..roof], y `divides` x]\n</code></pre>\n\n<p>which would more usually be written:</p>\n\n<pre><code>not $ any (`divides` x) [1,3..roof]\n</code></pre>\n\n<p>allowing you to drop the definition of <code>shorterThan</code> entirely and use:</p>\n\n<pre><code>isPrime :: (Integral a) =&gt; a -&gt; Bool\nisPrime x\n | x == 2 = True\n | even x = False\n | otherwise = not $ any (`divides` x) [3,5..roof]\n where roof = floor $ sqrt (fromIntegral x :: Double)\n</code></pre>\n\n<p>The other problem is that <code>factors</code> is doing extra work here -- it's using <code>isPrime</code> to check if <code>x</code> is prime using an algorithm that handles even numbers specially for efficiency, but then it turns around and does trial division by all numbers <code>[2..]</code> for composites. Instead, you could replace <code>isPrime</code> with a function to find the first prime factor of <code>x</code>, like so:</p>\n\n<pre><code>firstPrime :: (Integral a) =&gt; a -&gt; a\nfirstPrime x\n | even x = 2\n | otherwise = head [y | y &lt;- [3,5..roof]++[x], y `divides` x]\n where roof = floor $ sqrt (fromIntegral x :: Double)\n</code></pre>\n\n<p>This finds the first prime factor below <code>roof</code>, but throws in <code>x</code> itself as a last resort. (There's an unnecessary check here that <code>x</code> divides itself, so we could improve this code to avoid that, but it might not be worth the trouble.)</p>\n\n<p>Then, <code>factors</code> can grab this first prime factor, and see if it was <code>x</code> itself (in which case <code>x</code> is prime and we're done) or else look for more factors. The complete code for this version looks like:</p>\n\n<pre><code>{-# OPTIONS_GHC -Wall #-}\n\nmodule MorePrimes where\n\nfactors :: (Integral a) =&gt; a -&gt; [a]\nfactors x = case firstPrime x of\n factor | factor == x -&gt; [x]\n | otherwise -&gt; factor : factors (x `div` factor)\n\nfirstPrime :: (Integral a) =&gt; a -&gt; a\nfirstPrime x\n | even x = 2\n | otherwise = head [y | y &lt;- [3,5..roof]++[x], y `divides` x]\n where roof = floor $ sqrt (fromIntegral x :: Double)\n\ndivides :: (Integral a) =&gt; a -&gt; a -&gt; Bool\ndivides d n = n `rem` d == 0\n</code></pre>\n\n<p>Obviously, further optimization is possible, as illustrated by @Gurkenglas's answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T15:22:25.960", "Id": "221491", "ParentId": "221455", "Score": "4" } } ]
{ "AcceptedAnswerId": "221491", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T03:19:29.967", "Id": "221455", "Score": "6", "Tags": [ "beginner", "haskell", "primes" ], "Title": "Simple prime factorization program in Haskell" }
221455
<p>I've got a project where I get product data and need to get the prices which come in, in different formats.</p> <p>Some examples would be: US$17, USD17.00, 17,00€, 17€, GBP17, Only 17,-€, 17.000,00€, 17,000.00$ etc. </p> <p>So at the beginning I started with one specific string to float function and kept on adding code for specific use cases. I'm sure the code looks horrible and I can see already ways to improve it, but I wanted to get your opinions in the first place.</p> <pre><code>def convertPriceIntoFloat ( myString ): myString = myString.strip() # 1.298,90 € if "€" in myString and "." in myString and "," in myString: myString = (myString.replace('€', '')).strip() myString = (myString.replace('.', '')).strip() float_price = float(myString.replace(',', '.')) return(float_price) if "€" in myString and "*" in myString and "ab" in myString: myString = (myString.replace('€', '')).strip() myString = (myString.replace('*', '')).strip() myString = (myString.replace('ab', '')).strip() float_price = float(myString.replace(',', '.')) return(float_price) if "€" in myString and "ab" in myString: myString = (myString.replace('€', '')).strip() myString = (myString.replace('ab', '')).strip() if re.match('^\d{1,3}\.\d{3}\,\d{2}$', myString) is not None: # thousand EURO or more myString = (myString.replace('.', '')).strip() float_price = float(myString.replace(',', '.')) else: float_price = float(myString.replace(',', '.')) return(float_price) # 599,- € if ",-" in myString and "€" in myString: myString = (myString.replace('€', '')).strip() myString = (myString.replace(',-', '.00')).strip() if re.match('^\d{1,3}\.\d{3}\,\d{2}$', myString) is not None: # thousand EURO or more myString = (myString.replace('.', '')).strip() float_price = float(myString.replace(',', '.')) else: float_price = float(myString.replace(',', '.')) return(float_price) # ↵179,89 €↵*↵ if "€" in myString and "*" in myString: myString = (myString.replace('€', '')).strip() myString = (myString.replace('*', '')).strip() if re.match('^\d{1,3}\.\d{3}\,\d{2}$', myString) is not None: # thousand EURO or more myString = (myString.replace('.', '')).strip() float_price = float(myString.replace(',', '.')) else: float_price = float(myString.replace(',', '.')) return(float_price) # ab 223,90 EUR if "EUR" in myString and "ab" in myString: myString = (myString.replace('EUR', '')).strip() myString = (myString.replace('ab', '')).strip() if re.match('^\d{1,3}\.\d{3}\,\d{2}$', myString) is not None: # thousand EURO or more myString = (myString.replace('.', '')).strip() float_price = float(myString.replace(',', '.')) else: float_price = float(myString.replace(',', '.')) return(float_price) if "EUR" in myString: # GB Pound myString = (myString.replace('EUR', '')).strip() if re.match('^\d{1,3}\.\d{3}\,\d{2}$', myString) is not None: # thousand EURO or more myString = (myString.replace('.', '')).strip() float_price = float(myString.replace(',', '.')) else: float_price = float(myString.replace(',', '.')) return(float_price) if "CHF" in myString: # CHF Schweiz myString = (myString.replace('CHF', '')).strip() if re.match('^\d{1,3}\.\d{3}\,\d{2}$', myString) is not None: # thousand Franks or more myString = (myString.replace('.', '')).strip() float_price = float(myString.replace(',', '.')) else: float_price = float(myString.replace(',', '.')) return(float_price) if re.match('^\d{1,3}\.\d{3}\,\d{2}$', myString) is not None: # thousand EURO or more, coming in as a float already myString = (myString.replace('.', '')).strip() float_price = float(myString.replace(',', '.')) return(float_price) # 122,60 £ if "£" in myString: # remove GB Pound sign myString = (myString.replace('£', '')).strip() if re.match('^\d{1,3}\.\d{3}\,\d{2}$', myString) is not None: # thousand GB Pounds or more myString = (myString.replace('.', '')).strip() float_price = float(myString.replace(',', '.')) # 122,60 £ if re.match('^\d{1,3}\,\d{2}$', myString) is not None: # myString = (myString.replace('.', '')).strip() float_price = float(myString.replace(',', '.')) return(float_price) if "$" in myString: # GB Pound myString = (myString.replace('$', '')).strip() float_price = float(myString.replace(',', '')) return(float_price) if ",-" in myString: float_price = float(myString.replace(',-', '.00')) return(float_price) if re.match('^\d{1,3}\,\d{2}$', myString) is not None: float_price = float(myString.replace(',', '.')) return(float_price) if " " in myString and "&amp;#8364" in myString: return ( getPriceFromCommaString ( myString ) ) # UVP: 44,95 EURO if "UVP:" in myString and "EURO" in myString: myString = (myString.replace('UVP:', '')).strip() myString = (myString.replace('EURO', '')).strip() float_price = float(myString.replace(',', '.')) return(float_price) # 22,99 € # € 1.199,99 if "€" in myString: myString = (myString.replace('€', '')).strip() if re.match('^\d{1,3}\.\d{3}\,\d{2}$', myString) is not None: # thousand EURO or more myString = (myString.replace('.', '')).strip() float_price = float(myString.replace(',', '.')) else: float_price = float(myString.replace(',', '.')) return(float_price) else: return(myString) </code></pre> <p>If anybody knows a Python library that does the same thing, I'd be happy to flip as well.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T04:35:34.767", "Id": "428224", "Score": "0", "body": "What does your program actually do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T04:40:17.277", "Id": "428225", "Score": "0", "body": "It's a Function to extract float values from price strings. \nThose strings can have different formats." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T04:47:01.293", "Id": "428226", "Score": "0", "body": "So for `1.298,90 €` should the output be `1298.9`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T05:22:10.083", "Id": "428228", "Score": "0", "body": "Exactly. And then there are different currencies, different ways of displaying prices etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T11:52:13.017", "Id": "428364", "Score": "0", "body": "I don't have experience with Python, but if I understood your problem correctly, isn't it the easiest way to just extract those characters that are a number and parse them as a float? Either with a simple regex or string functions." } ]
[ { "body": "<p>I agree that this is a little complicated.</p>\n\n<p>I'd recommend you write a set of tests, and let those guide the complexity of the code. The tests would be simple, like,</p>\n\n<pre><code>assertEq convertPriceIntoFloat(\"1298,90\"), 1298.9\nassertEq convertPriceIntoFloat(\"1.298,90\"), 1298.9\nassertEq convertPriceIntoFloat(\"1.298,90 €\"), 1298.9\n...\n</code></pre>\n\n<p>Then, start out with a simple <code>float</code> conversion in your code, and see if that works, then add test cases and only add code as you need it. If things do seem to be getting overly complicated, refactor... you'll have tests that let you do that easily.</p>\n\n<p>Good luck.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T05:04:24.013", "Id": "221459", "ParentId": "221456", "Score": "7" } }, { "body": "<blockquote>\n <p><em>If anybody knows a Python library that does the same thing, I'd be happy to flip as well.</em></p>\n</blockquote>\n\n<p>I suggest you use the \"<a href=\"https://pypi.org/project/money-parser/\" rel=\"nofollow noreferrer\">Price and currency parsing utility</a>\" -</p>\n\n<blockquote>\n <p><em>Money Parser is a price and currency parsing utility.</em></p>\n \n <p><em>It provides methods to extract price and currency information from the\n raw string.</em></p>\n \n <p><em>There is a lot of different price and currency formats that present\n values with separators, spacing, etc.</em></p>\n \n <p><em>This library may help you to parse such data.</em></p>\n</blockquote>\n\n<p>Here are some examples of what it can do -</p>\n\n<pre><code>&gt;&gt;&gt; price_str(\"1.298,90 €\")\n'1298.90'\n\n&gt;&gt;&gt; price_str(\"599,- €\")\n'599'\n\n&gt;&gt;&gt; price_str(\"↵179,89 €↵*↵\")\n'179.89'\n\n&gt;&gt;&gt; price_str(\"ab 223,90 EUR\")\n'223.90'\n\n&gt;&gt;&gt; price_str(\"122,60 £\")\n'122.60'\n\n&gt;&gt;&gt; price_str(\"UVP: 44,95 EURO\")\n'44.95'\n\n&gt;&gt;&gt; price_str(\"22,99 €\")\n'22.99'\n\n&gt;&gt;&gt; price_str(None, default='0')\n'0'\n\n&gt;&gt;&gt; price_str(\"€ 1.199,99\")\n'1199.99'\n</code></pre>\n\n<p><strong>NOTES -</strong></p>\n\n<p>Open <code>Command Prompt</code> and, if you have Python version >= 3.4, then install the Money Parser module using - <code>pip install money-parser</code>.</p>\n\n<p>Open the Python IDLE and call the module - <code>from money_parser import price_str</code></p>\n\n<p>Try out an example from above and you'll know that you have achieved your desired results.</p>\n\n<p>Hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T06:48:33.357", "Id": "221463", "ParentId": "221456", "Score": "3" } }, { "body": "<ul>\n<li><p>From my untrained eye it looks like a simple regex would help ease the problem.</p>\n\n<pre><code>^(.*?)([\\d\\.,]+)(.*)$\n</code></pre>\n\n<p>This is as it results in the following output:</p>\n\n<pre><code>&gt;&gt;&gt; pprint([re.match('^(.*?)([\\d\\.,]+)(.*)$', i).groups() for i in ('US$17', 'USD17.00', '17,00€', '17€', 'GBP17', 'Only 17,-€', '17.000,00€', '17,000.00$')])\n[('US$', '17', ''),\n ('USD', '17.00', ''),\n ('', '17,00', '€'),\n ('', '17', '€'),\n ('GBP', '17', ''),\n ('Only ', '17,', '-€'),\n ('', '17.000,00', '€'),\n ('', '17,000.00', '$')]\n</code></pre></li>\n<li><p>Now that we have the money all that is left is to convert it to a float.</p>\n\n<p>Since you have thousands separators then you can't just use <code>float</code>. And so if you pass the 'thousand separator' and the 'decimal place' to the function and use <code>str.translate</code> then you can convert the code into the form you want.</p></li>\n</ul>\n\n<pre><code>import re\n\n\ndef _extract_price(value):\n match = re.match('^(.*?)([\\d\\.,]+)(.*)$', value)\n if match is None:\n raise ValueError(\"Can't extract price\")\n return match.groups()\n\n\ndef _parse_price(price, thousand, decimal):\n trans = str.maketrans(decimal, '.', thousand)\n return float(price.translate(trans))\n\n\ndef parse_price(value):\n prefix, price, suffix = _extract_price(value)\n if '€' in prefix + suffix:\n thousand = '.'\n decimal = ','\n else:\n thousand = ','\n decimal = '.'\n return _parse_price(price, thousand, decimal)\n</code></pre>\n\n<pre><code>&gt;&gt;&gt; [parse_price(i) for i in ('US$17', 'USD17.00', '17,00€', '17€', 'GBP17', 'Only 17,-€', '17.000,00€', '17,000.00$')]\n[17.0, 17.0, 17.0, 17.0, 17.0, 17.0, 17000.0, 17000.0]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:53:36.110", "Id": "428281", "Score": "0", "body": "I would favor this approach if we have a simple language to deal with. If the examples as presented by the OP represent the full sample space, go for the regex! The more complex the language, the sooner writing your own parser/compiler wins from a regex, no matter how smartly written." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T17:42:21.800", "Id": "428287", "Score": "0", "body": "@dfhwze Yes, regex isn't good with large complex grammar. For simple grammar like the this it's better than writing a parser." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:29:11.103", "Id": "221495", "ParentId": "221456", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T04:28:25.207", "Id": "221456", "Score": "6", "Tags": [ "python", "python-3.x", "parsing", "floating-point", "i18n" ], "Title": "Function to extract float from different price patterns" }
221456
<h1>Edit</h1> <p>I've added a second pass at this problem based on the answers that have been posted by other users so far: <a href="https://codereview.stackexchange.com/a/221525/75659">https://codereview.stackexchange.com/a/221525/75659</a></p> <hr> <p><br></p> <h1>Context</h1> <p>Before presenting the code for review, I want to be clear that I am not looking for recommendations on how to avoid having to solve the issue that the code is trying to solve in the first place</p> <p>This is not production code, this is purely for exploratory purposes, and I would prefer answers that remain within the provided requirements.</p> <p>With that said, let's suppose I have this contrived interface:</p> <pre><code>public interface IFoo&lt;T&gt; { event Action&lt;T&gt; ChangeValue; event Action&lt;object&gt; ChangeObject; event Action ChangeEmpty; void InvokeChange(T value); } </code></pre> <p>With the following contrived requirements:</p> <ul> <li><p>Calling <code>InvokeChange</code> with a value of type <code>T</code> that <code>Foo</code> was constructed with will invoke the three events </p> <ul> <li><code>ChangeValue</code> is invoked with the given value as type <code>T</code></li> <li><code>ChangeObject</code> is invoked with the given value as type <code>object</code></li> <li><code>ChangeEmpty</code> is invoked with no arguments</li> </ul></li> <li><p>Handlers that listen to any of the three events are invoked in the <strong><em>global order</em></strong> they were added, <strong><em>regardless of what event they were added to</em></strong>.</p> <ul> <li>Effectively there is only a single event here - some 'change' happened - but 3 event signatures that can be utilized by listeners as needed.</li> </ul></li> <li><p>The implementation can take any form, but must implement <code>IFoo&lt;T&gt;</code> as it is specified above.</p></li> <li><p>The implementation does not need to be thread safe and can allocate memory, but no memory should leak when it is used correctly.</p></li> </ul> <h1>Example 1</h1> <p>The order that event listeners are called should correspond to the order in which they were added, regardless of which event they were added to: </p> <pre><code>IFoo&lt;int&gt; test = new Foo&lt;int&gt;(); test.ChangeEmpty += () =&gt; Console.WriteLine("0) Empty!"); test.ChangeObject += (o) =&gt; Console.WriteLine("1) Object: {0}", o); test.ChangeValue += (v) =&gt; Console.WriteLine("2) Value: {0}", v); test.ChangeObject += (o) =&gt; Console.WriteLine("3) Object: {0}", o); test.ChangeEmpty += () =&gt; Console.WriteLine("4) Empty!"); test.InvokeChange(123); </code></pre> <p>Should print the following to the Console:</p> <pre><code>0) Empty! 1) Object: 123 2) Value: 123 3) Object: 123 4) Empty! </code></pre> <h1>Example 2</h1> <p>Adding/Removing event Listeners should work as expected, while still maintaining the same order:</p> <pre><code>public static void Main() { IFoo&lt;int&gt; test = new Foo&lt;int&gt;(); test.ChangeEmpty += EmptyHandler; test.ChangeObject += ObjectHandler; Console.WriteLine("1) EMPTY, OBJECT"); test.InvokeChange(1); test.ChangeEmpty -= EmptyHandler; test.ChangeValue += ValueHandler; Console.WriteLine("2) OBJECT, VALUE"); test.InvokeChange(2); test.ChangeObject -= ObjectHandler; Console.WriteLine("3) VALUE "); test.InvokeChange(3); test.ChangeObject += ObjectHandler; test.ChangeEmpty += EmptyHandler; test.ChangeValue += ValueHandler; Console.WriteLine("4) VALUE, OBJECT, EMPTY, VALUE"); test.InvokeChange(4); test.ChangeValue -= ValueHandler; test.ChangeValue -= ValueHandler; test.ChangeEmpty -= EmptyHandler; test.ChangeObject -= ObjectHandler; Console.WriteLine("5) &lt;NONE&gt;"); test.InvokeChange(5); } static void EmptyHandler() { Console.WriteLine(" - Empty!"); } static void ObjectHandler(object val) { Console.WriteLine(" - Object: {0}", val); } static void ValueHandler(int val) { Console.WriteLine(" - Value: {0}", val); } </code></pre> <p>Should print the following to the Console:</p> <pre><code>1) EMPTY, OBJECT - Empty! - Object: 1 2) OBJECT, VALUE - Object: 2 - Value: 2 3) VALUE - Value: 3 4) VALUE, OBJECT, EMPTY, VALUE - Value: 4 - Object: 4 - Empty! - Value: 4 5) &lt;NONE&gt; </code></pre> <p>Effectively it should perform as if there is a single invokation list that backs all 3 events.</p> <p>This code is not required to be particularly performant or thread safe, but 'correct'. In other words, invocation order and frequency is correct regardless of how many times a given handler is added/removed from one of the three events.</p> <hr> <h1>Code For Review</h1> <p>With all that in mind, the solution I came up with is:</p> <ul> <li><code>ChangeValue</code> is a standard event backed by an <code>Action&lt;T&gt;</code></li> <li><code>ChangeObject</code> and <code>ChangeEmpty</code> are custom event accessors that provide a custom <code>add</code> and <code>remove</code> implementation which are ultimately also backed by <code>ChangeValue</code>. <ul> <li>The <code>value</code> of <code>ChangeObject.add</code> and <code>ChangeEmpty.add</code> is wrapped in a lambda 'proxy' of signature <code>Action&lt;T&gt;</code></li> <li>To ensure that the event accessors are able to also remove the corresponding proxy when in <code>ChangeObject.remove</code> and <code>ChangeEmpty.remove</code>, a dictionary is used for each to track a stack of proxies that have been bound for each value added. <ul> <li><code>add</code> pushes a proxy to the stack and is then added with <code>ChangeValue += proxy</code></li> <li><code>remove</code> pops a proxy from the stack and is then removed with <code>ChangeValue -= proxy</code></li> </ul></li> </ul></li> </ul> <p>Here is the relevant code for one of the events:</p> <pre><code>public event Action&lt;T&gt; ChangeValue = delegate {}; private Dictionary&lt;Action&lt;object&gt;, List&lt;Action&lt;T&gt;&gt;&gt; ObjectEventProxies = new Dictionary&lt;Action&lt;object&gt;, List&lt;Action&lt;T&gt;&gt;&gt;(); public event Action&lt;object&gt; ChangeObject { add { List&lt;Action&lt;T&gt;&gt; eventProxies; if(!ObjectEventProxies.TryGetValue(value, out eventProxies)) { eventProxies = new List&lt;Action&lt;T&gt;&gt;(); ObjectEventProxies.Add(value, eventProxies); } Action&lt;T&gt; proxy = (T v) =&gt; value.Invoke(v); eventProxies.Add(proxy); ChangeValue += proxy; } remove { List&lt;Action&lt;T&gt;&gt; eventProxies; if (ObjectEventProxies.TryGetValue(value, out eventProxies)) { Action&lt;T&gt; proxy = eventProxies[eventProxies.Count - 1]; eventProxies.RemoveAt(eventProxies.Count - 1); ChangeValue -= proxy; } } } </code></pre> <p>And the full code, including the above examples: <a href="https://dotnetfiddle.net/u7NGMJ" rel="nofollow noreferrer">https://dotnetfiddle.net/u7NGMJ</a></p> <h1>Question</h1> <p>This code fulfills the given requirements but my question is, can this be simplified? There's a fair bit of boilerplate here for something that feels like it should be simpler to do.</p> <hr> <p>To re-iterate, I am looking specifically for answers that still meet all of the listed requirements, regardless of how contrived or unnecessary they might seem. I should be able to swap out my <code>IFoo&lt;T&gt;</code> implementation for yours and have the output be identical.</p> <p>I am aware I could just use a single <code>Action&lt;object&gt;</code> if I wanted a single signature to work for all cases. That is not what this question is asking.</p> <hr> <h1>Edit</h1> <p>I've added a second pass at this problem based on the answers that have been posted by other users so far: <a href="https://codereview.stackexchange.com/a/221525/75659">https://codereview.stackexchange.com/a/221525/75659</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T08:22:53.270", "Id": "428238", "Score": "0", "body": "You are very specific in what you don't want. But I do have a question about what you do want. You don't want to use a Action<Object>, but you do wrap all your event callers to Action<T>. Is this a requirement or can we use - let's say - 'object' as base class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T04:38:33.057", "Id": "428328", "Score": "0", "body": "For clarity (although I see you already added an answer): What I want is that IFoo<T> is usable exactly as specified, and that any implementation meets the requirements I listed, specifically that the examples I provide have identical output. Everything else is implementation details that do not matter within the context of this question." } ]
[ { "body": "<h2>Review</h2>\n<p>You wrap all event signatures into <code>Action&lt;T&gt;</code>. I would instead store all event listeners as their common base type <code>Object</code>. This way you don't need to create wrapper delegates.</p>\n<blockquote>\n<pre><code>add\n {\n // ..\n Action&lt;T&gt; proxy = (T v) =&gt; value.Invoke(v);\n eventProxies.Add(proxy);\n ChangeValue += proxy;\n }\n</code></pre>\n</blockquote>\n<p>The proxies seem overkill to me. No need for storing listeners in more than 1 backing collection.</p>\n<blockquote>\n<pre><code>private Dictionary&lt;Action&lt;object&gt;, List&lt;Action&lt;T&gt;&gt;&gt; ObjectEventProxies\n = new Dictionary&lt;Action&lt;object&gt;, List&lt;Action&lt;T&gt;&gt;&gt;();\n</code></pre>\n</blockquote>\n<h2>Proposed Solution</h2>\n<p>There is an elegant solution that meets all of your contrived requirements which takes advantage of the runtime for finding method overloads using the <code>dynamic</code> keyword.</p>\n<p>Store all listeners in a <code>LinkedList</code> (allow for duplicates).</p>\n<pre><code> private LinkedList&lt;object&gt; listeners = new LinkedList&lt;object&gt;();\n</code></pre>\n<p>Register/Unregister event listeners without using boiler-plate code.</p>\n<pre><code> private void Register(object listener)\n {\n if (listener == null) return;\n listeners.AddFirst(listener);\n }\n\n private void Unregister(object listener)\n {\n if (listener == null) return;\n listeners.Remove(listener);\n }\n\n public event Action&lt;T&gt; ChangeValue\n {\n add =&gt; Register(value);\n remove =&gt; Unregister(value);\n }\n\n public event Action&lt;object&gt; ChangeObject\n {\n add =&gt; Register(value);\n remove =&gt; Unregister(value);\n }\n\n public event Action ChangeEmpty\n {\n add =&gt; Register(value);\n remove =&gt; Unregister(value);\n }\n</code></pre>\n<p>Invoke event listeners using the <code>dynamic</code> keyword. The runtime knows which overload of <code>InvokeChange</code> to call. I have added one overload to take any <code>Object</code> as a fallback to avoid runtime exceptions, but this should be unreachable code. The combination of <code>Reverse()</code>, <code>AddFirst()</code> and <code>Remove()</code> ensures correct behavior. Performance is another thing though ..</p>\n<pre><code> public void InvokeChange(T value)\n {\n foreach (var listener in listeners.Reverse())\n {\n Invoke((dynamic)listener, value);\n }\n }\n\n // these methods require equivalent method signatures -&gt;\n // -&gt; see comments that Action&lt;T&gt; and Action&lt;object&gt; can be combined!\n\n private void Invoke(Action&lt;T&gt; action, T value)\n {\n action.Invoke(value);\n }\n\n private void Invoke(Action&lt;object&gt; action, T value)\n {\n action.Invoke(value);\n }\n\n private void Invoke(Action action, T value)\n {\n action.Invoke();\n }\n\n private void Invoke(Object unsupportedEventListenerType, T value)\n {\n // ignore or throw exception ..\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T10:55:05.690", "Id": "428243", "Score": "1", "body": "This solution is not doing exactly what's required, because if you bind the same delegate instance twice or more, it'll only be called once and hence the global call order is somewhat broken. But why he wants to have a possible handler called more times in the same invocation is not clear from the question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T10:58:56.053", "Id": "428244", "Score": "1", "body": "You can combine `Invoke(Action<T> action, T value)` and `Invoke(Action<object> action, T value)` in one: `Invoke<S>(Action<S> action, S value)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T11:14:42.597", "Id": "428245", "Score": "2", "body": "@HenrikHansen (1) If he wants the exact same handler registered more than once, the hash set must be replaced with an ordinary list. I overlooked this as a requirement. (2) Nice one!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T05:50:38.630", "Id": "428330", "Score": "0", "body": "As it stands the list implementation also does not meet the requirements. Calling `List.Remove` with a given value that exists multiple times in the list will remove the fist instance of that value. The desired behavior here is to remove the last instance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T07:07:42.100", "Id": "428337", "Score": "1", "body": "@Johannes Thanks for the clarification. I will no longer update my anwer because I feel better answers are available now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T07:42:50.930", "Id": "428341", "Score": "1", "body": "@Johannes That being said, I had to change it one more time just to meet the requirements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T07:57:45.637", "Id": "428342", "Score": "0", "body": "I do believe that this would meet my original requirements now. That being said, I've taken parts of each answer posted so far and added my own second iteration. Thank you for taking the time to answer in the first place, and so shortly after my original question was posted :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T07:59:10.950", "Id": "428343", "Score": "0", "body": "@Johannes No problem. It was a fun challenge! My goal was to meet the requirements, and I finally made it :-p" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T09:12:24.180", "Id": "221474", "ParentId": "221457", "Score": "5" } }, { "body": "<p>IMO your events should accommodate the C# standard for events:</p>\n\n<pre><code> public interface IFoo&lt;T&gt;\n {\n event EventHandler&lt;T&gt; ChangeValue;\n event EventHandler&lt;object&gt; ChangeObject;\n event EventHandler ChangeEmpty;\n\n void InvokeChange(T value);\n }\n</code></pre>\n\n<p>The <code>EventHandler</code> delegate takes a source object as argument, which may be useful when consuming the event.</p>\n\n<hr>\n\n<p>You can modify dfhwze's solution slightly to meet all your requirements to:</p>\n\n<pre><code> public class Foo&lt;T&gt; : IFoo&lt;T&gt;\n {\n\n private List&lt;object&gt; handlers = new List&lt;object&gt;();\n\n void AddHandler(object handler)\n {\n handlers.Add(handler);\n }\n\n void RemoveHandler(object handler)\n {\n int index = handlers.LastIndexOf(handler);\n if (index &gt;= 0)\n handlers.RemoveAt(index);\n }\n\n public event EventHandler&lt;T&gt; ChangeValue { add =&gt; AddHandler(value); remove =&gt; RemoveHandler(value); }\n public event EventHandler&lt;object&gt; ChangeObject { add =&gt; AddHandler(value); remove =&gt; RemoveHandler(value); }\n public event EventHandler ChangeEmpty { add =&gt; AddHandler(value); remove =&gt; RemoveHandler(value); }\n\n public void InvokeChange(T value)\n {\n foreach (object handler in handlers)\n {\n Invoke((dynamic)handler, value);\n }\n }\n\n public void Invoke(EventHandler handler, T value)\n {\n handler?.Invoke(this, EventArgs.Empty);\n }\n\n public void Invoke&lt;S&gt;(EventHandler&lt;S&gt; handler, S value)\n {\n handler?.Invoke(this, value);\n }\n }\n</code></pre>\n\n<p>A <code>List&lt;object&gt;</code> may not be the most effective container, if you have many listeners. In that case you'll have to find another.</p>\n\n<hr>\n\n<p>Another solution building on your own could be: </p>\n\n<pre><code> public class Foo&lt;T&gt; : IFoo&lt;T&gt;\n {\n private event EventHandler&lt;T&gt; AllEvents;\n private Dictionary&lt;Delegate, (EventHandler&lt;T&gt; Handler, int Count)&gt; allHandlers = new Dictionary&lt;Delegate, (EventHandler&lt;T&gt;, int)&gt;();\n\n void AddHandler(Delegate source, Func&lt;EventHandler&lt;T&gt;&gt; handlerFactory)\n {\n if (!allHandlers.TryGetValue(source, out var handler))\n {\n handler = (handlerFactory(), 1);\n }\n else\n {\n handler.Count++;\n }\n\n allHandlers[source] = handler;\n AllEvents += handler.Handler;\n }\n\n void RemoveHandler(Delegate source)\n {\n if (allHandlers.TryGetValue(source, out var handler))\n {\n handler.Count--;\n AllEvents -= handler.Handler;\n if (handler.Count &lt;= 0)\n allHandlers.Remove(source);\n else\n allHandlers[source] = handler;\n }\n }\n\n public event EventHandler&lt;T&gt; ChangeValue { add =&gt; AddHandler(value, () =&gt; value); remove =&gt; RemoveHandler(value); }\n public event EventHandler&lt;object&gt; ChangeObject { add =&gt; AddHandler(value, () =&gt; (src, v) =&gt; value.Invoke(src, v)); remove =&gt; RemoveHandler(value); }\n public event EventHandler ChangeEmpty { add =&gt; AddHandler(value, () =&gt; (src, v) =&gt; value.Invoke(src, EventArgs.Empty)); remove =&gt; RemoveHandler(value); }\n\n public void InvokeChange(T value)\n {\n AllEvents?.Invoke(this, value);\n }\n\n public void Clear()\n {\n allHandlers.Clear();\n AllEvents = null;\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T06:00:54.693", "Id": "428331", "Score": "0", "body": "Your point regarding the C# event standard is valid, but this does modify the `IFoo<T>` interface, which for the sake of this specific question means it's insufficient. I do like the simpler approach of effectively reference counting the proxy" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T11:15:10.783", "Id": "221477", "ParentId": "221457", "Score": "8" } }, { "body": "<blockquote>\n <p>no memory should leak when it is used correctly.</p>\n</blockquote>\n\n<p>Adding and removing a handler results in an empty <code>List&lt;T&gt;</code> lingering in the <code>Dictionary</code>. It seems odd to use a list at all... (I'll come back to that).</p>\n\n<hr />\n\n<p>dfhwze presents a good alternative solution which loads the complexity in one place. I would be inclined to consider the same, but perform conventional type checks instead of relying on <code>dynamic</code>. A simple change to dfhwze's code could be:</p>\n\n<pre><code>public void InvokeChange(T value)\n{\n foreach (var listener in listeners)\n {\n if (listener is Action a)\n a();\n else if (listener is Action&lt;T&gt; aT)\n aT(value);\n else if (listener is Action&lt;object&gt; aObject)\n aObject((object)value);\n else\n throw new InvalidOperationException(\"&lt;&lt; Suitable exception text here, telling the user to shout at the maintainer &gt;&gt;\")\n }\n}\n</code></pre>\n\n<p>This requires no more repetition, and is more explicit about what is going on. It aso avoids <code>dynamic</code>, which makes it more maintainable because all dependencies are statically declared.</p>\n\n<p>Using a sorted dictionary/list, you could put everything in the dictionary, and enumerate its values instead of maintain two collections (the dictionary and generic event). This would reduce redundancy (good), improve add/remove complexity, but increase the overhead of calling the event.</p>\n\n<hr />\n\n<p>Personally I like the proxy approach, but I couldn't bare to have all that code repeated in the events: you might consider packaging it (and <code>ObjectEventProxies</code>) in a class somewhere so that you can reuse it tidily. That said, most of the code is spent implementing a dictionary which stores an ordered list of values (which is a perfectly generic data structure), so you could just throw one of those together, and that would reduce the amount of repetition (and so fragility) significantly without the effort and risk inherent in trying anything more interesting. This would leave the event handler as more like:</p>\n\n<pre><code>add\n{\n Action&lt;T&gt; proxy = /* whatever */;\n WhateverEventProxies.Add(value, proxy);\n ChangeValue += proxy;\n}\nremove\n{\n var proxity = WhateverEventProxies.Remove(value);\n ChangeValue -= proxy;\n}\n</code></pre>\n\n<p>All of the complexity of managing the dictionary is gone, and now the intention of these accessors is clear.</p>\n\n<p>One significant advantage of stuffing everything into another class would be that it would be easier to make thread safe; though, in this case, you could probably just use a thread-safe dictionary with a count, since any event handlers added more than once are equivalent (the ordering doesn't matter).</p>\n\n<hr />\n\n<p>Since you are stuffing everything in <code>ChangeValue</code> to preserve the order, it's possible to add something with, for example <code>ChangeObject</code> only to remove it with <code>ChangeValue</code>, but since delegates provide exactly one method, there is no problem, and this means you can just use one dictionary (with <code>object</code> as the key) to track all the proxies in a single class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T13:44:47.083", "Id": "428262", "Score": "0", "body": "For enterprise applications, I find the switch also a better alternative than the dynamic approach. But for the sake of this challenge, I wanted to point out this unorthodox possibility." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T06:07:26.823", "Id": "428332", "Score": "0", "body": "Explicitly checking for the type is definitely the best approach for that specifically since (at least within the scope of this question) there are only 3 valid types: `Action<T>`, `Action<object>` and `Action`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T08:37:18.897", "Id": "428346", "Score": "0", "body": "I really like the idea of moving all the boilerplate logic to a helper object. I've taken parts of each answer posted so far and added my own second iteration - I've realized that in my specific use case you can handle add type checking in Add/Remove and don't have to worry about that in Invoke. Thank you for taking the time to post your answer, it was very useful :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T13:34:43.627", "Id": "221485", "ParentId": "221457", "Score": "6" } }, { "body": "<p>Thank you for the answers that have been posted so far. Each contributed something that I wanted to incorporate in my second iteration of this problem.</p>\n\n<p>Thank you specifically for solutions by</p>\n\n<ul>\n<li><a href=\"https://codereview.stackexchange.com/a/221474/75659\">dfhwze</a> - using a single backing collection instead of one for each event</li>\n<li><a href=\"https://codereview.stackexchange.com/a/221477/75659\">Henrik Hansen</a> - using reference counting to avoid needing a proxy <code>List</code> for each handler.</li>\n<li><a href=\"https://codereview.stackexchange.com/a/221485/75659\">VisualMelon</a> - separating proxy management logic as its own object.</li>\n</ul>\n\n<p>I've compiled my own approach that pulls from each of these answers</p>\n\n<hr>\n\n<h1>A Utility for Managing the event proxies</h1>\n\n<p>I'm realizing that this is a very specific use case - A single <code>Action&lt;T&gt;</code> event that should also fire as <code>Action&lt;object&gt;</code> and <code>Action</code> depending on what the listener needs - that I could see using in a few areas, and so chose to implement it as a separate utility class.</p>\n\n<p>As was pointed out by <a href=\"https://codereview.stackexchange.com/a/221477/75659\">Henrik Hansen</a>, C#'s <code>EventHandler</code> is arguably preferable but its use would require changing the signature of the events and therefore the signature of any event handler functions that are Added to them, which in this specific case I am trying to avoid.</p>\n\n<p>My implementation of the Event Proxy Utility object is:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public struct EventProxyContainer&lt;T&gt;\n{\n private struct EventProxy\n {\n public Action&lt;T&gt; proxy;\n public int count;\n }\n private Dictionary&lt;object, EventProxy&gt; handlerProxies;\n\n public Action&lt;T&gt; Add(object handler) { /* See Below */ }\n\n public Action&lt;T&gt; Remove(object handler) { /* See Below */ }\n}\n\n</code></pre>\n\n<p>Instead of performing the type check in the Invoke, I chose to handle that in the <code>Add</code> function itself. My intuition is that we will be invoking events more than adding them so this should give a bit of performance benefit.</p>\n\n<p>This also means we can actually avoid having to construct a proxy at all for <code>Action&lt;T&gt;</code> handlers.</p>\n\n<h2><code>Add</code> Implementation</h2>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public Action&lt;T&gt; Add(object handler)\n{\n if(!(handler is Action&lt;object&gt;) &amp;&amp; !(handler is Action)) return (Action&lt;T&gt;)handler;\n handlerProxies = handlerProxies ?? new Dictionary&lt;object, EventProxy&gt;();\n\n EventProxy entry;\n if(handlerProxies.TryGetValue(handler, out entry))\n {\n entry.count += 1;\n handlerProxies[handler] = entry;\n }\n else\n {\n entry = new EventProxy() { count = 1 };\n if(handler is Action&lt;object&gt;)\n entry.proxy = (v) =&gt; ((Action&lt;object&gt;)handler).Invoke(v);\n else if (handler is Action)\n entry.proxy = (v) =&gt; ((Action)handler).Invoke();\n handlerProxies.Add(handler, entry);\n }\n return entry.proxy;\n}\n</code></pre>\n\n<h2><code>Remove</code> implementation</h2>\n\n<p>Again we early out if the handler is <code>Action&lt;T&gt;</code></p>\n\n<pre><code>public Action&lt;T&gt; Remove(object handler)\n{\n if(!(handler is Action&lt;object&gt;) &amp;&amp; !(handler is Action)) return (Action&lt;T&gt;)handler;\n handlerProxies = handlerProxies ?? new Dictionary&lt;object, EventProxy&gt;();\n\n EventProxy entry;\n if(handlerProxies.TryGetValue(handler, out entry))\n {\n entry.count -= 1;\n if(entry.count == 0) \n handlerProxies.Remove(handler);\n else\n handlerProxies[handler] = entry;\n }\n return entry.proxy;\n}\n</code></pre>\n\n<hr>\n\n<h1><code>Foo&lt;T&gt;</code> Implementation</h1>\n\n<p>This really cleans up the <code>Foo&lt;T&gt;</code> implementation quite nicely:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class Foo&lt;T&gt; : IFoo&lt;T&gt;\n{\n private EventProxyContainer&lt;T&gt; changeProxy;\n\n public event Action&lt;T&gt; ChangeValue = delegate {};\n\n public event Action&lt;object&gt; ChangeObject \n { \n add =&gt; ChangeValue += changeProxy.Add(value); \n remove =&gt; ChangeValue -= changeProxy.Remove(value); \n }\n\n public event Action ChangeEmpty \n { \n add =&gt; ChangeValue += changeProxy.Add(value); \n remove =&gt; ChangeValue -= changeProxy.Remove(value);\n }\n\n public void InvokeChange(T value) \n {\n ChangeValue.Invoke(value);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>I like this approach because</p>\n\n<ul>\n<li>It still satisfies all the original requirements, and produces the same output as my original examples.</li>\n<li>It can be retrofitted in any case where you have an event of type <code>Action&lt;T&gt;</code> where you also want event listeners to be able to use it as <code>Action&lt;object&gt;</code> and <code>Action</code> instead.</li>\n<li>The proxy handling logic is well contained to a single utility object and separate from whatever else might exist in <code>IFoo</code>.</li>\n<li>Reference counting our proxies allows us to limit one memory allocation per Unique Handler</li>\n<li>We only construct a proxy for <code>Action&lt;object&gt;</code> and <code>Action</code> handlers - <code>Action&lt;T&gt;</code> handlers are added to the backing event object as normal.</li>\n<li><code>Add</code> and <code>Remove</code> whitelist only <code>Action&lt;object&gt;</code> and <code>Action</code>, and return null in all other cases, which <code>event +=</code> and <code>event -=</code> handles gracefully.</li>\n</ul>\n\n<p>The updated code with examples can be found <a href=\"https://dotnetfiddle.net/UHbNpD\" rel=\"nofollow noreferrer\">as a DotNetFiddle here</a>, and <a href=\"https://gist.github.com/JohannesMP/dc6b8c1461167fa8eae3a092872b8b9a\" rel=\"nofollow noreferrer\">as a gist here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T08:05:05.257", "Id": "428344", "Score": "1", "body": "Since Action<T> is your main signature, I can understand why you would convert the others to this one, leaving you no problems whatsoever on invocation. I can live with that :-p" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T05:37:58.273", "Id": "434983", "Score": "0", "body": "I case you wonder why the downvote... I find you should have accepted one of the other answers instead of your own especially that they all very good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T18:54:54.643", "Id": "435037", "Score": "0", "body": "@t3chb0t That is completely valid. If I could select multiple answers I would have done so. I chose to combine them and credit each of the original authors at the top of my answer as opposed to having to choose one. I felt each of them had something valid to contribute and not one of them was \"better\" than the rest." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T07:53:36.437", "Id": "221525", "ParentId": "221457", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T04:28:56.297", "Id": "221457", "Score": "9", "Tags": [ "c#", "event-handling" ], "Title": "Making an Action<T> event also usable as Action<object> and Action in C#" }
221457
<p>any help with optimizing following code to make it run faster.</p> <p>Tried making function inline, tried cin.TIE(NULL), tried ios_base::sync_with_stdio(false);</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; using namespace std; class gfg { public: bool satisfiable(std::vector&lt;int&gt; a, std::vector&lt;int&gt; b) { while (!a.empty()) { std::sort(b.begin(), b.end(), std::greater&lt;int&gt;()); int k = a.back(); a.pop_back(); if (k &gt; b.size()) return false; if (k == 0) continue; if (b[k - 1] == 0) return false; for (int i = 0; i &lt; k; i++) b[i]--; } for (std::vector&lt;int&gt;::iterator i = b.begin(); i != b.end(); i++) if (*i != 0) return false; return true; } }; int main() { gfg g; ios_base::sync_with_stdio(false); cin.tie(NULL); int r,c,n,cnt=0; cin &gt;&gt; n; while(cnt&lt;n){ cnt++; cin &gt;&gt; r &gt;&gt; c; int x; vector&lt;int&gt; a; vector&lt;int&gt; b; for(int i=0;i&lt;r;i++){ cin &gt;&gt; x; a.push_back(x); } for(int j=0;j&lt;c;j++){ cin &gt;&gt; x; b.push_back(x); } if(g.satisfiable(a,b)) cout &lt;&lt; "YES\n"; else cout &lt;&lt; "NO\n"; } return 0; } </code></pre> <p>Expected : Average 1s or less processing time per test case Actual : Average 2s to 2.5s processing time per test case</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T05:15:45.173", "Id": "428227", "Score": "4", "body": "Welcome to Code Review. This question is currently a \"code dump\". Please explain what task this code accomplishes. See [ask]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T06:35:25.843", "Id": "428231", "Score": "2", "body": "Did you try using a profiler? What did it say was taking up the time? Also, it would help to see an example of the input data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T18:38:23.850", "Id": "428292", "Score": "1", "body": "As is typical with any performance related question, _are you compiling with optimizations enabled_?" } ]
[ { "body": "<p>General points:</p>\n\n<ul>\n<li><p>We need to include <code>&lt;functional&gt;</code> for <code>std::greater&lt;&gt;</code>.</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Don't do <code>using namespace std;</code></a>.</p></li>\n<li><p>The <code>gfg</code> class has no state, so we can use a free function for <code>satisfiable</code>.</p></li>\n<li><p>Variables should be declared as close as possible to their point of use. If possible they should also be initialized to a valid value, and not a placeholder \"invalid value\". e.g. <code>r</code>, and <code>c</code> should be declared inside the outer <code>while</code> loop.</p></li>\n<li><p>Reading input can be made much neater by factoring it into a separate function. We should also check for errors by testing <code>cin.fail()</code>.</p></li>\n</ul>\n\n<p>Performance:</p>\n\n<ul>\n<li><p>There is no need to modify the vector <code>a</code>. We are just iterating through it in reverse, which can be done with... reverse iterators:</p>\n\n<pre><code>for (auto r = a.rbegin(); r != a.rend(); ++r) { int k = *r; ... }\n</code></pre></li>\n<li><p>This means that <code>satisfiable</code> can take <code>a</code> by const reference and avoid copying it:</p>\n\n<pre><code>bool satisfiable(std::vector&lt;int&gt; const&amp; a, std::vector&lt;int&gt; b) { ... }\n</code></pre></li>\n<li><p>The vector <code>b</code> is modified inside the function, so we should still accept the parameter by value. However, since we don't use the vector in <code>main</code> afterwards we can still avoid copying it:</p>\n\n<pre><code>satisfiable(a, std::move(b))\n</code></pre></li>\n</ul>\n\n<p>Modified code:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;functional&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n\nbool satisfiable(std::vector&lt;int&gt; const&amp; a, std::vector&lt;int&gt; b) {\n\n for (auto r = a.rbegin(); r != a.rend(); ++r) {\n\n std::sort(b.begin(), b.end(), std::greater&lt;int&gt;());\n\n int k = *r;\n\n if (k &gt; b.size()) return false;\n if (k == 0) continue;\n if (b[k - 1] == 0) return false;\n\n for (int i = 0; i != k; ++i)\n b[i]--;\n }\n\n auto is_zero = [] (int x) { return x == 0; };\n return std::all_of(b.begin(), b.end(), is_zero);\n}\n\nint read_int()\n{\n int x = 0;\n std::cin &gt;&gt; x;\n\n if (std::cin.fail()) {\n std::cout &lt;&lt; \"invalid input!\\n\";\n exit(1);\n }\n\n return x;\n}\n\nint main()\n{\n std::ios_base::sync_with_stdio(false);\n std::cin.tie(NULL);\n\n int n = read_int();\n\n for (int cnt = 0; cnt != n; ++cnt) {\n\n int r = read_int();\n int c = read_int();\n\n std::vector&lt;int&gt; a;\n for (int i = 0; i != r; ++i)\n a.push_back(read_int());\n\n std::vector&lt;int&gt; b;\n for (int j = 0; j != c; ++j)\n b.push_back(read_int());\n\n std::cout &lt;&lt; (satisfiable(a, std::move(b)) ? \"YES\" : \"NO\") &lt;&lt; \"\\n\";\n }\n}\n</code></pre>\n\n<p>These changes may not fix your performance issues. I suspect that with large inputs, most of the time will be taken up by <code>std::sort</code> (you should profile it and find out!). Without more details on what the algorithm does, or what the input looks like, it's hard to make further suggestions.</p>\n\n<p>However, it looks like we don't need to sort the entire <code>b</code> vector with every iteration:</p>\n\n<ul>\n<li><p>If the item at <code>k-1</code> is greater than the item at <code>k</code> before the decrement, it will be equal to the item at <code>k</code> after the decrement (i.e. the <code>b</code> vector is still sorted correctly).</p></li>\n<li><p>If the item at <code>k-1</code> is equal to the item at <code>k</code> before the decrement, it will be less than the item at <code>k</code> after the decrement (i.e. the <code>b</code> vector is no longer ordered).</p>\n\n<p>However, we still don't need to sort the whole vector, we can just move any equal items from <code>k</code> onwards to the correct point (perhaps using <a href=\"https://en.cppreference.com/w/cpp/algorithm/rotate\" rel=\"nofollow noreferrer\"><code>std::rotate</code></a>). In this case you may also find the <a href=\"https://en.cppreference.com/w/cpp/algorithm/lower_bound\" rel=\"nofollow noreferrer\"><code>std::lower_bound</code></a> and <a href=\"https://en.cppreference.com/w/cpp/algorithm/upper_bound\" rel=\"nofollow noreferrer\"><code>std::upper_bound</code></a> algorithms useful.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T11:29:33.267", "Id": "428247", "Score": "0", "body": "The Idea behind the program is to tell whether a matrix exists or not (yes or no) given list of values in each row and column\nFor ex.\n\n3 2 - dimensions\n2 1 0 - row values\n1 2 - col values\nYES (Matrix Exists)\n\n\n\n3 3 - dimensions\n3 2 1 - row values\n1 2 2 - col values\nNO(Matrix wont Exists)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:46:33.740", "Id": "428279", "Score": "0", "body": "I tried above modified code by you ( with all suggested improvements by you however i was not able to get performance below 2s average, seems like the sort is bottelneck). maybe i am trying the wrong approach while sorting or doing it in wrong way can you please show the kind of sorting you are takling about." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T08:06:57.287", "Id": "221468", "ParentId": "221460", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T05:07:10.717", "Id": "221460", "Score": "-1", "Tags": [ "c++", "c++11", "c++14" ], "Title": "Determine if matrix exists or not" }
221460
<p>Here is my attempt at converting hex strings to byte arrays and converting byte arrays to hex strings:</p> <p><strong><em><code>net.coderodde.util.ByteStringConverter</code></em></strong></p> <pre><code>package net.coderodde.util; import java.util.Scanner; public class ByteStringConverter { /** * Converts the given byte array to its textual hex representation. * @param bytes the byte array to stringify. * @return the string representing the input byte array. */ public static String convertByteArrayToHexString(byte[] bytes) { StringBuilder stringBuilder = new StringBuilder(2 * bytes.length); for (byte b : bytes) { stringBuilder.append(convertByteToHexString(b)); } return stringBuilder.toString(); } /** * Converts the given hex string to the byte array it represents. * @param hexString the hex string to convert. * @return the byte array represented by the input hex string. */ public static byte[] convertHexStringToByteArray(String hexString) { byte[] byteArray = new byte[hexString.length() / 2]; for (int i = 0; i &lt; hexString.length(); i += 2) { byteArray[i / 2] = convertHexByteStringToByte( hexString.substring(i, i + 2)); } return byteArray; } /** * Converts the input character {@code c} to the nibble it represents. This * method assumes that {@code c} is numeric or within range * {@code a, b, c, d, e, f}. * @param c the character to convert to a nibble. * @return the byte value of the textual representation of a nibble. */ private static byte convertHexCharToNibble(char c) { c = Character.toLowerCase(c); switch (c) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': return 10; case 'b': return 11; case 'c': return 12; case 'd': return 13; case 'e': return 14; case 'f': return 15; default: throw new IllegalArgumentException("Not a hex digit: " + c); } } /** * Converts the input hex byte string to the byte it represents. * @param hexByteString the hex byte string to convert. * @return the byte value represented by {@code hexByteString}. */ private static byte convertHexByteStringToByte(String hexByteString) { char lo = hexByteString.charAt(1); char hi = hexByteString.charAt(0); byte lob = convertHexCharToNibble(lo); byte hib = convertHexCharToNibble(hi); return (byte)((hib &lt;&lt; 4) | lob); } /** * Converts the given byte to its textual hex representation. * @param b the byte to convert. * @return the textual representation of the byte {@code b}. */ private static String convertByteToHexString(byte b) { byte lo = (byte)(b &amp; (byte) 0xf); byte hi = (byte)((b &gt;&gt;&gt; 4) &amp; (byte) 0xf); StringBuilder stringBuilder = new StringBuilder(2); appendNibbleToStringBuilder(stringBuilder, hi); appendNibbleToStringBuilder(stringBuilder, lo); return stringBuilder.toString(); } /** * Appends the textual representation of {@code nibble} to * {@code stringBuilder}. * @param stringBuilder the target string builder. * @param nibble the nibble to append. */ private static void appendNibbleToStringBuilder(StringBuilder stringBuilder, byte nibble) { switch (nibble) { case 0: stringBuilder.append('0'); break; case 1: stringBuilder.append('1'); break; case 2: stringBuilder.append('2'); break; case 3: stringBuilder.append('3'); break; case 4: stringBuilder.append('4'); break; case 5: stringBuilder.append('5'); break; case 6: stringBuilder.append('6'); break; case 7: stringBuilder.append('7'); break; case 8: stringBuilder.append('8'); break; case 9: stringBuilder.append('9'); break; case 10: stringBuilder.append('a'); break; case 11: stringBuilder.append('b'); break; case 12: stringBuilder.append('c'); break; case 13: stringBuilder.append('d'); break; case 14: stringBuilder.append('e'); break; case 15: stringBuilder.append('f'); break; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (true) { String hexString = scanner.next(); byte[] hexBytes = convertHexStringToByteArray(hexString); String newHexString = convertByteArrayToHexString(hexBytes); System.out.println(newHexString); } } } </code></pre> <p>As always, any critique is much appreciated!</p>
[]
[ { "body": "<p>You implemented <code>convertByteArrayToHexString</code> really inefficiently because you allocate a new string for each byte that is converted.</p>\n\n<p>Also, there's no need for a StringBuilder since a character array suffices. The idiomatic code for converting a byte array to a hex string is:</p>\n\n<pre><code>public static String toHex(byte[] bytes) {\n char[] chars = new char[2 * bytes.length];\n for (int i = 0; i &lt; bytes.length; i++) {\n chars[2 * i] = \"0123456789abcdef\".charAt((bytes[i] &amp; 0xf0) &gt;&gt; 4);\n chars[2 * i + 1] = \"0123456789abcdef\".charAt(bytes[i] &amp; 0x0f);\n }\n return new String(chars);\n}\n</code></pre>\n\n<p>I wonder why you chose the inefficient variant over this straightforward code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T08:50:01.873", "Id": "221471", "ParentId": "221461", "Score": "3" } } ]
{ "AcceptedAnswerId": "221471", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T06:05:57.667", "Id": "221461", "Score": "2", "Tags": [ "java", "strings", "reinventing-the-wheel", "serialization" ], "Title": "Converting hex strings to byte arrays and back to hex strings in Java" }
221461
<p>I have just returned to college to finish my associate's in programming. The language my school uses for all of the programming classes is java, so I've been trying to get used to the language.</p> <p>The code I've posted below works as far as I can tell, I am hoping some of you can give some constructive criticism to my code as far as the style and general improvements I could have made.</p> <p>I am very new to the OOP concept, so I am also wondering if I declared everything right, I know global variables are normally bad practice, but since the global variables I used are in a class I wasn't sure if that was really the same thing since they are all local variables anyway. </p> <p>Also, the main function isn't included here because all it does is call the public function playGame(), but if you really need it I can add it later.</p> <pre><code>import java.util.Random; import java.util.Scanner; /** * Title: GameFunctions * Author: Dev * Date: 6/1/2019 * Purpose: This class contains - * -all the functions for the game * */ public class GameFunctions { private static int attempts; private static int randomNumber; private static int guessRange; private static int userGuess; private static boolean gameRunning = true; /* * Takes care of the setup aspects of the game like * Generating a new random number and finding how * Many attemps the player will have */ private static void gameInit() { setRandomNumber(); setAttemptsAndRange(); } /* Sets randomNumber to a value between 1 and 100 */ private static void setRandomNumber() { Random random = new Random(); int low = 0; int high = 100; randomNumber = random.nextInt(high - low) + low; } /* Sets the attempts value based on how large the randomNumber is */ private static void setAttemptsAndRange() { if (randomNumber &lt;= 10) {attempts = 2; guessRange = 10; } else if (randomNumber &lt;= 25) { attempts = 4; guessRange = 25; } else if (randomNumber &lt;= 50) { attempts = 5; guessRange = 50; } else if (randomNumber &lt;= 75) { attempts = 7; guessRange = 75; } else { attempts = 10; guessRange = 100; } } /* Displays the number of attempts the user has left */ private static void getAttempts() { System.out.println("Attempts remaining: " + attempts); } /* Displays the random number, used at the end of the game */ private static void getRandomNumber() { System.out.println("The random number is " + randomNumber); } /* Gets input from the user */ private static void getInput() { Scanner scanner = new Scanner(System.in); while (true) { try { getAttempts(); System.out.println("Enter a number between 0 and " + guessRange); userGuess = scanner.nextInt(); if ( userGuess &lt;= 100 &amp;&amp; userGuess &gt; 0) { break; } else { System.out.println("Number is out of guess range"); } } catch (java.util.InputMismatchException e) { System.out.println("Invalid input"); scanner.nextLine(); } } } /* * Checks to see if the guess is correct * If it is not correct it will decrement the attempts value */ private static void checkGuess() { if (userGuess != randomNumber) { if (userGuess &lt; randomNumber) { System.out.println("Too Low!"); } else { System.out.println("Too High!"); } attempts--; } } /* Tells the user their win/loss status and asks them to play again */ private static void playAgain() { String userInput; Scanner scanner = new Scanner(System.in); if (attempts &gt; 0) { System.out.println("You won!"); } else { System.out.println("You Lost!"); }; getRandomNumber(); while (true) { try { System.out.println("Play Again? yes/no"); userInput = scanner.next(); if (userInput.equals("yes") || userInput.equals("no")) { if (userInput.equals("yes")) { break; } else { gameRunning = false; break; } } else { System.out.println("Invalid Input"); } } catch (java.util.InputMismatchException e) { System.out.println("Invalid input, try again"); } } } /* Main game loop */ public static void playGame() { while (gameRunning) { gameInit(); while (attempts &gt; 0 &amp;&amp; userGuess != randomNumber) { getInput(); checkGuess(); } playAgain(); } } } </code></pre>
[]
[ { "body": "<p>I have some observations.</p>\n\n<ol>\n<li><strong>All your methods &amp; fields are static</strong>: This is not required. You can remove the static modifier.</li>\n<li><p><strong>Getter Methods</strong>:</p>\n\n<pre><code>private static void getAttempts()\n{\n System.out.println(\"Attempts remaining: \" + attempts);\n}\n</code></pre></li>\n</ol>\n\n<p>A getter method is expected to return some value and not print some value. If you want to print attempts then rename method to <code>printAttempts()</code>.</p>\n\n<ol start=\"3\">\n<li><p><strong>Formatting in if/else blocks</strong>: No formatting in if/else block of your code</p>\n\n<p><code>if (randomNumber &lt;= 10) {attempts = 2; guessRange = 10; }</code></p></li>\n</ol>\n\n<p>should be </p>\n\n<pre><code>if(randomNumber &lt;= 10){\n attempts = 2;\n guessRange = 10;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T11:34:59.817", "Id": "428249", "Score": "0", "body": "Thanks for the tip. So the formatting if/else blocks, was it just bad practice to do it that way or does it cause some type of weird bug or other problem? I was just doing it to save space, but I guess it does look a little weird." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T11:37:59.140", "Id": "428250", "Score": "1", "body": "Formatting if/else blocks will make your code more readable and less clumsy. It will not cause any bug however, it will increase the complexity while understanding the code block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T11:44:26.180", "Id": "428251", "Score": "0", "body": "Okay cool, I'll keep that in mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T07:53:26.020", "Id": "428504", "Score": "0", "body": "I'd challenge your observation number 1: Keeping methods and fields non-static is not required either, and the OP can keep the static modifier. I would even say that making them static by default should be considered, because there is no abstraction in the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T09:17:04.450", "Id": "428513", "Score": "0", "body": "Please refer to @Tman1677 answer in this thread before challenging, he has explained the use of static variable beautifully." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T11:25:03.277", "Id": "221479", "ParentId": "221467", "Score": "8" } }, { "body": "<p>In addition to Himanshu's answer.</p>\n\n<p><strong>Move the instantiation of Random to the class level.</strong></p>\n\n<pre><code> private static void setRandomNumber()\n {\n Random random = new Random();\n int low = 0;\n int high = 100;\n randomNumber = random.nextInt(high - low) + low;\n } \n</code></pre>\n\n<p>You are creating new instance of Random every time you call the method. Move the instantiation to the class level and only call it from the method, otherwise you are creating objects that are used only once.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T11:55:48.570", "Id": "221481", "ParentId": "221467", "Score": "4" } }, { "body": "<p>I do not know if it is a good tip ( I am a beginner too), but I think it would be a better practice to initialize other classes at the very top using constructor.</p>\n\n<p>You instantiate scanner twice, together with removing all static modifiers, you could instantiate scanner and random automatically when you instantiate GameFunctions class in main class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T15:36:21.913", "Id": "221493", "ParentId": "221467", "Score": "3" } }, { "body": "<p>Let's take this from the top down:</p>\n\n<blockquote>\n<pre><code>/**\n * Title: GameFunctions\n * Author: Dev\n * Date: 6/1/2019\n * Purpose: This class contains -\n * -all the functions for the game\n * */\npublic class GameFunctions\n</code></pre>\n</blockquote>\n\n<p>This comment doesn't tell me anything new:</p>\n\n<ul>\n<li><code>Title</code> is already mentioned in the class declaration that follows</li>\n<li><code>Author</code> and <code>Date</code> are already kept in version control software</li>\n<li><code>Purpose</code> simply restates the class name</li>\n</ul>\n\n<p>I recommend writing a useful comment, or none at all.</p>\n\n<blockquote>\n<pre><code>{\n</code></pre>\n</blockquote>\n\n<p>All major coding standards for Java put opening braces at the end of the preceeding line, not a line of their own.</p>\n\n<pre><code>private static int attempts;\nprivate static int randomNumber;\nprivate static int guessRange;\nprivate static int userGuess;\n</code></pre>\n\n<p>Keeping mutable state in static fields is unusual because it needlessly inhibits code reuse (prevents several instances of the game from running concurrently), and is somewhat verbose due to having to repeat <code>static</code> everywhere. Consider using non-static fields instead.</p>\n\n<blockquote>\n<pre><code>/*\n * Takes care of the setup aspects of the game like\n * Generating a new random number and finding how\n * Many attemps the player will have\n */\nprivate static void gameInit()\n</code></pre>\n</blockquote>\n\n<p>Such initialization logic is usually expressed in a constructor, because that enforces that state is initialized before use (you can forget calling an init method, but the compiler will yell at you if your forget to call a constructor).</p>\n\n<p>Your javadoc comment restates the implementation in its entirety. Not only is this redundant, it also violates information hiding: Javadoc is intended to inform the callers of this method about its proper use. A caller doesn't need to know which private fields are being set, and how. All a caller needs to know is when he needs to invoke this method. Since this is already being conveyed by the method name, a comment is superfluous.</p>\n\n<blockquote>\n<pre><code> setRandomNumber();\n setAttemptsAndRange();\n</code></pre>\n</blockquote>\n\n<p>As a matter of style, prefer expressing yourself in the programming language instead of through clever names (names are only understood by humans, and can not be checked by your compiler, and refactored by your refactoring tools). </p>\n\n<p>That is, I'd have written:</p>\n\n<pre><code>randomNumber = randomInteger(100)\nguessRange = rangeOf(randomNumber)\nattempts = maximumAttemptsFor(randomNumber)\n</code></pre>\n\n<p>Passing <code>randomNumber</code> allows both the compiler and future maintainers to see and check that <code>randomNumber</code> is initialized before use. </p>\n\n<blockquote>\n<pre><code>/* Displays the number of attempts the user has left */\nprivate static void getAttempts()\n</code></pre>\n</blockquote>\n\n<p>The Javadoc contradicts the method name: Do we \"get\" or \"display\" the number of attempts?</p>\n\n<blockquote>\n<pre><code>/* Gets input from the user */\nprivate static void getInput()\n</code></pre>\n</blockquote>\n\n<p>Actually, it also validates the input. A caller might want to know that he doesn't have to check the range. </p>\n\n<p>Perhaps rename the method to <code>readGuess()</code>? That makes it clear that only guesses are returned.</p>\n\n<blockquote>\n<pre><code>* Checks to see if the guess is correct\n* If it is not correct it will decrement the attempts value\n*/\nprivate static void checkGuess()\n</code></pre>\n</blockquote>\n\n<p>The method implementation also displays feedback about the guess. A caller might want to know that.</p>\n\n<blockquote>\n<pre><code>/* Tells the user their win/loss status and asks them to play again */\nprivate static void playAgain()\n</code></pre>\n</blockquote>\n\n<p>The Javadoc and method name seem at odds. What does \"playing again\" have to do with a win/loss status?</p>\n\n<blockquote>\n<pre><code>/* Main game loop */\npublic static void playGame()\n{\n while (gameRunning)\n {\n gameInit();\n while (attempts &gt; 0 &amp;&amp; userGuess != randomNumber)\n {\n getInput();\n checkGuess();\n }\n playAgain();\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Well done! By structuring your program into steps, each in their own named method, the main method gives a very good overview of your program, and makes it very easy and quick to drill down to a particular part of the code.</p>\n\n<p>However, why is this excellent summary at the <em>end</em> of your source file? Wouldn't it do more good if it were the <em>first</em> thing the reader of this class sees? </p>\n\n<p>And a last nitpick: your summary reads a variable (<code>gameRunning</code>), but doesn't express when that variable is set. This could be seen a mixing layers of abstraction.</p>\n\n<p>All that said, here is a sketch how I'd write it:</p>\n\n<pre><code>public class GuessingGame {\n\n public static void main(String... args) {\n do {\n new GuessingGame().play();\n } while (playAgain());\n }\n\n private final int secretNumber;\n private final int guessRange;\n private int remainingAttempts;\n\n public GuessingGame() {\n secretNumber = randomInteger(100);\n guessRange = guessRange(secretNumber);\n remainingAttempts = maximimumAttempts(secretNumber);\n }\n\n public void play() {\n while (remainingAttempts &gt; 0) {\n remainingAttempts--;\n\n int guess = readGuess();\n if (guess == secretNumber) {\n display(\"You won!);\n return;\n }\n display(hint(guess));\n }\n display(\"You lost!\");\n }\n\n // more utility methods go here\n}\n</code></pre>\n\n<p>PS: This review held your code to professional standards. For a beginner, you did very well! Should you want to learn more about writing maintainable code, I can recommend <a href=\"https://rads.stackoverflow.com/amzn/click/com/0132350882\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">\"Clean Code\" by Robert C. Martin</a> - he may be a bit dogmatic at times, but his arguments are well worth considering.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T10:58:58.583", "Id": "428690", "Score": "0", "body": "Good review. However... your GuessingGame implementation is a disposable object but it still allows re-entry to play() method, which results in surprising behaviour. I would place the game parameters (range and number of tries) into GuessingGame class and the game state (number of guesses remaining) into another class that is instantiated in the play() method." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T20:26:52.117", "Id": "221502", "ParentId": "221467", "Score": "21" } }, { "body": "<p>All the other answers are very good and detailed but they fail to touch upon the reasoning behind the fatal flaw in your code: static variables are generally bad and to be avoided. This answer should help you understand some of the basics of static variables so you can understand the other answers better. To explain that we need to touch on some OOP basics and what a static variable is in a class.</p>\n\n<p>The principle of OOP is that you can create objects containing their own methods and variables so that all of the code relating to a certain task is in an \"object\". In java an \"object\" is created in the form of a class.</p>\n\n<p>The main benefits of OOP are twofold, it simplifies the code, and more importantly allows effective code reuse and duplication. Static variables and methods are, generally speaking, against code reuse and duplication. A class is meant to be initialized before using, essentially making an instance of the class before you use it. In java this initialization would look like this:</p>\n\n<pre><code>GameFunctions game = new GameFunctions();\n</code></pre>\n\n<p>And then all methods after that would be called like</p>\n\n<pre><code>game.getInput();\n</code></pre>\n\n<p>This is very useful because it allows multiple instances of a class to be created simultaneously so if you wanted to have two games running you could do something like:</p>\n\n<pre><code>GameFunctions game1 = new GameFunctions();\nGameFunctions game2 = new GameFunctions();\n</code></pre>\n\n<p>Static variables, instead of being owned by each object as you create them are owned by the class itself, in other words there will only really be one GameFunctions object. This object may work just fine, but it's far better to do things in terms of non static variables. Although static variables do have their place, that place is very rare and this class shouldn't have a single static variable.</p>\n\n<p>That being said, this is a common mistake everyone makes when they first start, your code seems pretty well thought out and I'm sure you're on track to learn much more in the way of coding!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T23:22:10.857", "Id": "428475", "Score": "1", "body": "Thank you for the detailed explanation of static variables. I was actually following a udemy tutorial on java and for whatever reason the course has touched on classes without really explaining minor details like this. Udemy is really hit or miss I've come to realize after a couple courses." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:22:36.643", "Id": "221556", "ParentId": "221467", "Score": "6" } } ]
{ "AcceptedAnswerId": "221502", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T08:03:16.347", "Id": "221467", "Score": "9", "Tags": [ "java", "beginner", "number-guessing-game" ], "Title": "Java guess the number" }
221467
<p>I have table which contains different permissions. Currently i am render all those permsion columns into check boxes manually. Like this</p> <pre><code>global $con; $sql = "SELECT * FROM `permissionsinpage` where `ETPK` = $id"; //chk allow project name $result = mysql_query($sql,$con) or die(mysql_error()); $no_result = mysql_num_rows($result); // total rows echo "ID,Name,Switch,MembersList, Self Category List, Allow Projects,Verify Proj,WhiteBoard,Chk Emp Proj Days, Chk Proj Days,Permissions,Main Menu,WhiteBoard_EmpDetail,Entry_WhiteBoard,Proj_StatusEdit,Ger_StatusReport, Switch_request, Get Switch Request, Project QuestionAnswer, Allow All Task Finished Request Received, AllowDeadLineInternalView, AllowDeadLineExternalView, AllowITComplainsNotInStockPanel, AllowITComplainsPendingOrInprogressPanel, AllowAllITComplainsEdit, AllowEditViewOwnITComplains"; while($row = mysql_fetch_assoc($result)) { echo "----//------"; echo $row['ETPK'];echo","; $name = GetEmpName($row['ETPK']); echo $name;echo","; echo '&lt;input type="checkbox" id="switch"'; if ($row['switch'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="MemberNames"'; if ($row['MemberNames'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="selfCategoryList"'; if( $row['selfCategoryList'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="AllowProjects"'; if ($row['AllowProjects'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="VerifyAllowProjects"'; if ($row['VerifyAllowProjects'] ==1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="WhiteBoard"'; if($row['WhiteBoard'] ==1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="ChkEmpProjDays"'; if( $row['ChkEmpProjDays'] ==1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="ChkProjDays"'; if($row['ChkProjDays'] ==1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="permissionPage"'; if( $row['permissionPage'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="MainMenuTop"'; if( $row['MainMenuTop'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="WhiteBoard_EmpDetail"'; if( $row['WhiteBoard_EmpDetail'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="Entry_WhiteBoard"'; if( $row['Entry_WhiteBoard'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="Proj_StatusEdit"'; if( $row['Proj_StatusEdit'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="Ger_StatusReport"'; if( $row['Ger_StatusReport'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="RequestForSwitchEmployee"'; if( $row['SwitchRequest'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="GetSwitchRequest"'; if( $row['GetSwitchRequest'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="ProjectQuestionAnswer"'; if( $row['ProjectQuestionAnswer'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="AllowAllTaskFinishedRequest"'; if( $row['AllowAllTaskFinishedRequest'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="AllowDeadLineInternalView"'; if( $row['AllowDeadLineInternalView'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="AllowDeadLineExternalView"'; if( $row['AllowDeadLineExternalView'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="AllowITComplainsNotInStockPanel"'; if( $row['AllowITComplainsNotInStockPanel'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="AllowITComplainsPendingOrInprogressPanel"'; if( $row['AllowITComplainsPendingOrInprogressPanel'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="AllowAllITComplainsEdit"'; if( $row['AllowAllITComplainsEdit'] == 1) echo "checked"; echo"&gt;,"; echo '&lt;input type="checkbox" id="AllowEditViewOwnITComplains"'; if( $row['AllowEditViewOwnITComplains'] == 1) echo "checked"; echo"&gt;"; </code></pre> <p>As you can see that i am manully adding even checkbox. Is there anyway to short this code and generate the diesred checked checkbox dynamically.</p>
[]
[ { "body": "<ol>\n<li>You should not be using <code>mysql_</code> functions anymore as they are deprecated.</li>\n<li>Whether you upgrade to <code>mysqli_</code> or <code>PDO</code> is up to you, but you should be using a prepared statement.</li>\n<li>By declaring a lookup / translation array which stores database table column names as keys and output labels as values, you can control all of the variable bits of text from a single source. This will make managing your script much easier and avoid many points where typos/inconsistencies may be difficult to locate.</li>\n<li>If <code>GetEmpName()</code> is executing another query, then you should be using a JOIN in your posted query to avoid performing separate/iterated queries.</li>\n</ol>\n\n<p>My suggestion with some basic debugging check to make your transition to mysqli smoother:</p>\n\n<p><strong>The lookup array:</strong></p>\n\n<pre><code>$columnsLabels = [\n 'ETPK' =&gt; 'ID',\n 'switch' =&gt; 'Switch',\n 'MemberNames' =&gt; 'MembersList',\n 'selfCategoryList' =&gt; 'Self Category List',\n 'AllowProjects' =&gt; 'Allow Projects',\n 'VerifyAllowProjects' =&gt; 'Verify Proj',\n 'WhiteBoard' =&gt; 'WhiteBoard',\n 'ChkEmpProjDays' =&gt; 'Chk Emp Proj Days',\n 'ChkProjDays' =&gt; 'Chk Proj Days',\n 'permissionPage' =&gt; 'Permissions',\n 'MainMenuTop' =&gt; 'Main Menu',\n 'WhiteBoard_EmpDetail' =&gt; 'WhiteBoard_EmpDetail',\n 'Entry_WhiteBoard' =&gt; 'Entry_WhiteBoard',\n 'Proj_StatusEdit' =&gt; 'Proj_StatusEdit',\n 'Ger_StatusReport' =&gt; 'Get_StatusReport',\n 'RequestForSwitchEmployee' =&gt; 'Switch_request',\n 'GetSwitchRequest' =&gt; 'Get Switch Request',\n 'ProjectQuestionAnswer' =&gt; 'Project QuestionAnswer',\n 'AllowAllTaskFinishedRequest' =&gt; 'Allow All Task Finished Request Received',\n 'AllowDeadLineInternalView' =&gt; 'AllowDeadLineInternalView',\n 'AllowDeadLineExternalView' =&gt; 'AllowDeadLineExternalView',\n 'AllowITComplainsNotInStockPanel' =&gt; 'AllowITComplainsNotInStockPanel',\n 'AllowITComplainsPendingOrInprogressPanel' =&gt; 'AllowITComplainsPendingOrInprogressPanel',\n 'AllowAllITComplainsEdit' =&gt; 'AllowAllITComplainsEdit',\n 'AllowEditViewOwnITComplains' =&gt; 'AllowEditViewOwnITComplains'\n];\n</code></pre>\n\n<p><strong>Processing:</strong></p>\n\n<pre><code>$sql = \"SELECT \" . implode(',', array_keys($columnsLabels)) . \" FROM permissionsinpage WHERE ETPK = ?\";\n\nif (!$stmt = $con-&gt;prepare($sql)) {\n echo \"Prepare Syntax Error\";\n} elseif (!$stmt-&gt;bind_param(\"i\", $id) || !$stmt-&gt;execute() || !$result = $stmt-&gt;get_result()) {\n echo \"Statement Error\";\n} elseif (!$row = $result-&gt;fetch_assoc()) {\n echo \"No data found for Id: {$id}\";\n} else {\n echo implode(',', $columnLabels) , \"&lt;br&gt;\";\n foreach ($row as $column =&gt; $value) {\n if ($column == 'ETPK') {\n $rowOutput[] = \"----//------{$value}\";\n $rowOutput[] = GetEmpName($value);\n } else {\n $rowOutput[] = \"&lt;input type=\\\"checkbox\\\" id=\\\"{$column}\\\"\" . ($value == 1 ? ' checked' : '') . '&gt;';\n }\n }\n echo implode(',', $rowOutput);\n}\n</code></pre>\n\n<ul>\n<li>I am assuming that <code>ETPK</code> is the table's primary key and is unique -- ergo there will either be zero or one row produced by the query.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T13:12:37.807", "Id": "221484", "ParentId": "221472", "Score": "3" } }, { "body": "<p>Firstly, you need to consider using <strong>prepared statement</strong> and not using <code>mysql_</code> since it has been deprecated.</p>\n\n<p>Second thing, you may wanna use <code>SHOW COLUMNS</code> instead of creating any bulk arrays or typing the name of each column.\nA clean code for that:</p>\n\n<pre><code>$columns = mysqli_query($con, 'SHOW COLUMNS FROM `permissionsinpage`');\nwhile($column = mysqli_fetch_array($columns)) $fields[] = $row['Field'];\n</code></pre>\n\n<p><strong>So your code will look like:</strong></p>\n\n<pre><code>$columns = mysqli_query($con, 'SHOW COLUMNS FROM `permissionsinpage`');\nwhile($column = mysqli_fetch_array($columns)) $fields[] = $row['Field'];\n\n$stmt = $con-&gt;prepare('SELECT * FROM `permissionsinpage` where `ETPK` = ?');\n$stmt-&gt;bind_param('s', $id);\n$stmt-&gt;execute();\n\n$result = $stmt-&gt;get_result();\nif($result-&gt;num_rows === 0) exit('No rows');\n\necho implode(', ', $fields);\n\nwhile($row = $result-&gt;fetch_assoc()) {\n echo '----//------'.$row['ETPK'].','.GetEmpName($row['ETPK']).',';\n foreach($fields as $field){\n echo '&lt;input type=\"checkbox\" id=\"'.$field.'\"'.($row[$field] == 1 ? ' checked':'').'&gt;,';\n }\n}\n$stmt-&gt;close();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T10:14:03.100", "Id": "222073", "ParentId": "221472", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T09:03:03.607", "Id": "221472", "Score": "1", "Tags": [ "php" ], "Title": "Dynamically create table colmun into checkboxes" }
221472
<p>I am trying to build object identity in PHP so that when I have a collection of objects, each one can have a string as identifier and all of these identifiers are afterwards combined to form an unique md5 to represent the "identity of a collection".</p> <p>Why? So that I can choose to skip re-execution of code when it's not needed:</p> <pre><code>interface SomeTestInterface { public function testFunction(); } abstract class Identifiable { public function __toString() { $identity_shards = array_merge( get_object_vars( $this ), class_implements( $this ) ); $identity_string = ''; foreach( $identity_shards as $identity_shard_key =&gt; $identity_shard_value ) { $identity_string .= (string) $identity_shard_key . (string) json_encode( $identity_shard_value ); } return md5( get_class( $this ) . $identity_string ); } } class SomeBaseClass extends Identifiable implements SomeTestInterface { public function __construct( $number ) { $this-&gt;number = $number; $this-&gt;thing = 'a'; $this-&gt;other_thing = ['a','b','c',1,2,3,]; } public function testFunction() { return 'a'; } } </code></pre> <p>This is testable with:</p> <pre><code>for( $i = 1; $i &lt; 10000; $i++ ) { $class = new SomeBaseClass( $i ); (string) $class; } </code></pre> <p>For me, PHP 7.3 and WordPress, this takes ~100ms to execute.</p> <p>My micro-decisions:</p> <ol> <li>I need <code>json_encode</code> on <code>$identity_shard_value</code> because you can't cast an array to string, for example. <code>json_encode</code> is both fast in my experience and knows how to deal with it all.</li> <li>I chose to make this an <code>abstract class</code> because <code>json_encode</code> doesn't have access to scoped classes, as such, it cannot encode what it can't find, so I must be able to access <code>$this</code> though it's weird because even in the abstract class, I still can't encode it, but I should be able to.</li> </ol> <p>My main concerns with this is if I really need all these items to build my object identity or if there's another, faster way. 10000 objects in 0.1ms, although very good on its own, doesn't necessarily scale.</p> <p>In essence, every single object that implements <code>Identifiable</code> in a collection that a module of my framework has will have an identity that I will then combine into a final "collection identity" to later do a check such as:</p> <pre><code>$collection_identity = getCollectionIdentity( $collection ); //MD5 computed from the identity of all these objects if( $collection_identity != getCollectionIdentityByName( 'some_collection' ) { setCollectionIdentity( 'some_collection', $collection_identity ); //re-execute code } else { retrieveDataFromStorage(); } </code></pre> <p>As you can see, it checks if there was a change to the objects / collection and if so, it re-executes all the other code, but if not, it just retrieves what that "other code" generated in the past and as such, this is a way to use persistent storage to skip execution of heavy code.</p>
[]
[ { "body": "<p>I think this code is fine, and can't be sped up very much. But ....</p>\n\n<p>The MD5 hash is most likely unique, it's got 16^32 (3.4e38) values after all, but once in a blue moon two different objects will have the same identity, especially if you use this a lot. This might cause very rare, random, bugs in your software. Bugs that are virtually impossible to track down.</p>\n\n<p>I don't think the <code>__toString()</code> magic Method was intended for the purpose you're now using it for. I have learned that; <em>\"You should always use something for the purpose it was intended for.\"</em>. The purpose of <code>__toString()</code> is to give you a readable representation of the object. By appropriating it now for identifying objects, you're loosing the capability to use it for its intended purpose later.</p>\n\n<p>You're also relying on an undocumented property of <code>get_object_vars()</code>, namely that it will always return the variables in the same order. Will it? I don't know. It probably will, but doesn't have to. This could also change with changing versions of PHP, leaving you with a very big headache if it happens. You could use <code>ksort()</code> to make sure the order is always the same, but that will slow things down a lot.</p>\n\n<p>I've also read in various places, and in the comments in the manual, that <code>get_object_vars()</code> doesn't return static variables. That makes sense since all objects of a class share the same values for these variables, but it is something to keep in mind.</p>\n\n<p>The storing and checking of the identity hashes, in some collection of hashes, will probably be the slowest part of this whole idea.</p>\n\n<p>Then <strong>my final problem</strong> wilt this code: </p>\n\n<p>Properly written code would know the identity of its objects, or at least have a 100% reliable method to check this. Your code should be written in such a way that it already minimizes object duplication. This code seems the result of not being able to write good and efficient code (sorry, I'm trying to make a point here). </p>\n\n<p>For instance, many objects could already have a simply ID integer that identifies them. For instance a model class, based on a database row, would most likely have such an ID. Most other classes could, if needed, have a similar way to identify themselves. Once you combine such an ID with the class name you should have a 100% reliable identifier.</p>\n\n<p>If you really need a way to identify various objects you could simply add an <code>identity()</code> method to them. Something like this:</p>\n\n<pre><code>&lt;?php\n\nclass MyClass \n{\n public function __construct($id)\n {\n $this-&gt;id = $id;\n } \n\n public function identity() {\n return get_class() . \":\" . $this-&gt;id;\n }\n}\n\n$myObject = new MyClass(999);\n\necho $myObject-&gt;identity();\n\n?&gt;\n</code></pre>\n\n<p>This would return:</p>\n\n<blockquote>\n <p>MyClass:999</p>\n</blockquote>\n\n<p>I agree that this is a very basic example, but it should be possible to do something similar for any class.</p>\n\n<p>By writing such a specific identifier method for each class you can optimize it, which means it will be faster, and you can make it a 100% reliable under any circumstances. It is also a lot easier to debug, because you can see and read what is going on. No hiding behind mysterious hashes here.</p>\n\n<p><strong>Conclusion:</strong> Despite my objections I think your code looks fine. I do however wonder whether this approach will, in the end, cause more trouble than it is worth.</p>\n\n<p><strong>Note:</strong> There is more discussion in the comments. In the end coolpasta wrote <a href=\"https://codereview.stackexchange.com/a/221558/53331\">a response to this question</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T00:04:13.033", "Id": "428321", "Score": "0", "body": "100% I agree, each object should be identifiable by an id. If it was after me, each object should have some kind of unique identifier for its identity. Unfortunately we only have a randomly assigned id that changes roughly on each request. Here was my thought process: When somebody is using my framework, do I want them to implement both the function and the property for that id? No! It's way easier to just extend an `abstract` and be done with it. This is the only hack I have within the framework and knowing that, should I still dwell more on this code? PHP really has no answer for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T00:06:19.623", "Id": "428322", "Score": "0", "body": "Also, because it's an abstract, if the class extending it decides that now it needs a `__toString` of its own, it can just override, in which case, my original `Identifiable` logic fails, but again, there's no escape, `json_encode` doesn't have access to scoped objects, `identity()` requires too much setup code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T10:03:20.440", "Id": "428349", "Score": "0", "body": "Ah, your framework will be used by others? I didn't know that. I can understand you don't want to burden other people with creating an `identity()` method for each class. I still don't get why you need to appropriate `__toString()`. Are you saying your code wouldn't work if the same method was called `createIdentityHash()`? The problem I have is that I don't understand your explanation about `json_encode`, abstract classes, and scoping. Then again, I haven't actually ran your code, so there might be something I missed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T19:56:28.393", "Id": "428436", "Score": "0", "body": "When you run `json_encode` on a scoped class, it doesn't know about its existence, so if it's not in the global scope, it won't be able to find it. The idea for `__toString` came because I do `(string) $class` which instantly calls it. I think the better idea is to make my `ObjectsInMyCollectionInterface` to `extend Identifiable` and so, people are only forced to spit out an identifier, not write `use Identifiable` and then also `implements ObjectsInMy... , Identifiable`, they'll simply do `implements Identifiable` and implement the function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:19:19.607", "Id": "428438", "Score": "0", "body": "Yes, so the user of your framework has implement a fast indentifier function after all? I can imagine `json_encode` has its limits looking inside classes, but I've never heard of a 'scoped class'. I can only guess what it could be. I do however have a suggestion: You could check whether the `$identity_shard_value` is an object with an identifier function, if it is you could invoke it to fully indentify the object. That would solve any scoping problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:23:14.503", "Id": "428440", "Score": "0", "body": "Exactly what I just did. I was just hoping I'd save the developer from having to setup this function. But there's a key takeaway. If I am generating a class from a factory from a base, then it also needs to be provided an unique string by the developer himself. If I just create my collection with identifiables from all new classes, this is fine to use as identifier: `return __NAMESPACE__ . 'ClassName'` since no two classes can exist in the same namespace with the same name, but if I generate them from just a `BaseClass`, then I can't use the class name since it won't be unique." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:23:49.693", "Id": "428442", "Score": "0", "body": "As such, I think that I will also need, when dealing with factories of base classes, to check whether or not the ID is taken and reject the generation of a class from that base if the id is already taken." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T22:19:47.233", "Id": "428460", "Score": "0", "body": "I'd appreciate it if you linked to my answer since it's the actual implementation as per your theory and \"object identity php\" on Google will serve exactly this link so others can see." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T23:05:23.427", "Id": "221512", "ParentId": "221473", "Score": "4" } }, { "body": "<p>My initial issues were: speed &amp; readability and as it turned out, issues with working with <code>__toString</code>.</p>\n\n<p>First, a problem with my initial approach:</p>\n\n<p>If my <code>SomeBaseClass</code> at some point needed to re-write the <code>__toString</code> function it inherited from <code>Identifiable</code>, then the initial functionality of me going through a collection of same <code>SomeBaseClass</code> would fall through, basically it won't be an <code>Identifiable</code> anymore because the functionality was re-written.</p>\n\n<p>What I did, based on @KIKO's suggestion and it yielded me no bugs so far is create an interface that inherits <code>IdentifiableInterface</code>, like such:</p>\n\n<pre><code>/**\n * Interfaces that contains a single method in regards to an object's unique &amp; persistent identity.\n *\n * @internal Mostly used by objects that are inside containers (as such, they're of the same intent, but differ) where comparison between these objects is needed.\n */\ninterface IdentifiableInterface\n{\n /**\n * Retrieves the object's identifier.\n *\n * @internal Do note that this is the object identifier which is meant for identification in the broader scope. You might have a, say, \"suggestion identifier\" which is specific to the Suggestions Module.\n *\n * @return string\n */\n public function getUniqueObjectIdentifier();\n}\n</code></pre>\n\n<p>then, in my scoped (sub-module) functionality, I'm working with <code>SuggestionInterface</code> that represents each object that will be in my collection:</p>\n\n<pre><code>use Sprout\\SproutIdentity\\Interfaces\\IdentifiableInterface;\n\ninterface SuggestionInterface extends IdentifiableInterface\n{\n}\n</code></pre>\n\n<p>Which basically makes any <code>SuggestionInterface</code> object also implement <code>getUniqueObjectIdentifier</code> and by nature, telling the users that this object and the likes of it are meant to be in a collection and that this state of being a member of a collection is important.</p>\n\n<p>Although I pat myself on the back here, I think it's an elegant way to, through comments and inheritance (with which I kind of agree when it comes to interfaces) you can tell so much about your system.</p>\n\n<p>In the end, here is how I compute a collection of <code>SuggestionInterface</code>s identity from a helper function:</p>\n\n<pre><code>public static function computeArrayIndetity( $array )\n{\n $identity = '';\n\n foreach( $array as $array_item ) {\n $identity .= $array_item-&gt;getUniqueObjectIdentifier();\n }\n\n return md5( $identity );\n}\n</code></pre>\n\n<p>The result?</p>\n\n<pre><code>10000 iterations:\nnew approach - 0.0005820830663045\nold approach - 0.0020218133926392\n\n100000 iterations:\nnew approach - 0.005621083577474 \nold approach - 0.019490500291189\n</code></pre>\n\n<p>Of course, it's like comparing apples to pears when you see what one does and what the other does, it's like \"duh\", but I just wanted to showcase how I went from a complicated, slower method that was well intended to a more elegant, simpler and way faster result.</p>\n\n<p>Although the speed is clearly better, the byproduct the new approach creates is non-existent and there will be no bugs due to <code>__toString</code>.</p>\n\n<p>It does require the developer to setup that function and therefore it defeats the purpose of automation but I'll make a helper function that they can use to instantly generate names without having to think about it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T23:54:55.813", "Id": "428478", "Score": "1", "body": "I linked your answer at the end of mine and upvoted yours." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:47:19.597", "Id": "221558", "ParentId": "221473", "Score": "4" } } ]
{ "AcceptedAnswerId": "221512", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T09:08:12.167", "Id": "221473", "Score": "4", "Tags": [ "performance", "php" ], "Title": "Building object identity in PHP" }
221473
<p><strong>The task</strong></p> <p>is taken from <a href="https://leetcode.com/problems/jewels-and-stones/" rel="nofollow noreferrer">leetcode</a></p> <blockquote> <p>You're given strings J representing the types of stones that are jewels, and S representing the stones you have. Each character in S is a type of stone you have. You want to know how many of the stones you have are also jewels.</p> <p>The letters in J are guaranteed distinct, and all characters in J and S are letters. Letters are case sensitive, so "a" is considered a different type of stone from "A".</p> <p><strong>Example 1:</strong></p> <p>Input: J = "aA", S = "aAAbbbb"</p> <p>Output: 3</p> <p><strong>Example 2:</strong></p> <p>Input: J = "z", S = "ZZ"</p> <p>Output: 0</p> <p>Note:</p> <p>S and J will consist of letters and have length at most 50. The characters in J are distinct.</p> </blockquote> <p><strong>My functional solution</strong></p> <pre><code>/** * @param {string} J * @param {string} S * @return {number} */ var numJewelsInStones = function(J, S) { const set = new Set(J); return [...S].reduce((ac, s) =&gt; set.has(s) + ac, 0); }; </code></pre> <p><strong>My imperative solution:</strong></p> <pre><code>/** * @param {string} J * @param {string} S * @return {number} */ var numJewelsInStones = function(J, S) { let num = 0; const set = {}; for (let j = 0; j &lt; J.length; j++) { set[J[j]] = 1; } for (let s = 0; s &lt; S.length; s++) { num += set[S[s]] || 0; } return num; }; </code></pre>
[]
[ { "body": "<p>here is my proposal: there are fewer cycles, and uses a regex more \"simple\" for interpreters javascript (I think that the use of the Set consumes more resources)</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function numJewelsInStones(J, S)\n{\n return [...J].reduce((ac, j) =&gt; ac + (S.match(RegExp(j)) || []).length, 0)\n}\n\nconsole.log( \"'aA', 'aAAbbbb' ==&gt;\", numJewelsInStones('aA', 'aAAbbbb') )\nconsole.log( \"'z', 'ZZ' ==&gt;\", numJewelsInStones('z', 'ZZ') )</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T13:44:18.090", "Id": "221486", "ParentId": "221475", "Score": "0" } }, { "body": "<p>Your code is concise and readable... I didn't have any feedback... it really shows how the functional solution is nicer.</p>\n\n<p>I was curious if it could be done with regular expressions and no iteration, so I played around and got:</p>\n\n<pre><code>const numJewelsInStones = (j,s) =&gt; { \n const m = s.match(new RegExp(`[${j}]`,'g'))\n return m ? m.length : 0 \n}\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>numJewelsInStones = (j,s) =&gt; s.replace(new RegExp(`[^${j}]`,'g'),'').length\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T18:51:27.663", "Id": "428295", "Score": "0", "body": "Very clever indeed" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T17:12:34.973", "Id": "221498", "ParentId": "221475", "Score": "2" } }, { "body": "<p>Instead of populating a <code>Set</code> and using <code>.has()</code>, you can use <a href=\"https://www.w3schools.com/jsref/jsref_includes.asp\" rel=\"nofollow noreferrer\">String includes()</a> directly. After that, it's just a matter of filtering the array and taking its length. I'd avoid using regexes unless they actually simplify things.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const countJewels = (J, S) =&gt; [...S].filter(n =&gt; J.includes(n)).length\n\nconsole.log(countJewels(\"aA\", \"aAaabb\"))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Your functions should be <code>const</code> unless you intend to change them. I wouldn't use parameter names like <code>J</code> and <code>S</code>, but I guess those were given by leetcode.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T10:52:50.210", "Id": "428688", "Score": "0", "body": "Includes is slower I think" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T10:55:41.580", "Id": "428689", "Score": "0", "body": "For length 50 it might actually not be. Anyway, the inputs are so short you don't need to care." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T10:48:10.773", "Id": "221639", "ParentId": "221475", "Score": "1" } } ]
{ "AcceptedAnswerId": "221498", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T09:14:28.667", "Id": "221475", "Score": "2", "Tags": [ "javascript", "algorithm", "programming-challenge", "ecmascript-6" ], "Title": "Jewels and Stones" }
221475
<p>I wrote some JavaScript to generate some graphics on a canvas, on a regular HTML page.</p> <p>I now want the same code to run in a component that is part of a React app. I've done this:</p> <pre><code> componentDidMount() { const canvas = this.refs.firstCanvas const ctx = canvas.getContext('2d') const bgCanvas = this.refs.firstbgCanvas const bgCtx = bgCanvas.getContext('2d') function generateStarfield() { bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height) for (let i = 0; i &lt; 2000; i++) { bgCtx.beginPath() const x = Math.random()*bgCanvas.width const y = Math.random()*bgCanvas.height bgCtx.arc(x, y, 0.35, 0, 2*Math.PI, 'anticlockwise') bgCtx.closePath() bgCtx.fillStyle = 'white' bgCtx.fill() } } generateStarfield() const origin_x = 1000 const origin_y = 1000 const scale = 1000 class planet { constructor(orbital_velocity, offset_theta, orbital_radius, radius, colour) { this.orbital_velocity = orbital_velocity this.orbital_radius = orbital_radius this.colour = colour this.radius = radius this.offset_theta = offset_theta this.draw() } draw() { const theta = this.offset_theta + (t*this.orbital_velocity) const x = origin_x + (this.orbital_radius*Math.cos(theta)) const y = origin_y + (this.orbital_radius*Math.sin(theta)) ctx.beginPath() ctx.arc(x, y, this.radius, 0, 2*Math.PI, 'anticlockwise') ctx.closePath() ctx.fillStyle = this.colour ctx.fill() } } let t = 0 const a = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.1, 10, 'white') const b = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.2, 16, 'white') const c = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.3, 18, 'white') const d = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.4, 14, 'white') const e = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.5, 12, 'white') const f = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.6, 28, 'white') const g = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.7, 22, 'white') const h = new planet((0.2+0.4*Math.random())*Math.PI, 2*Math.random()*Math.PI, scale*0.8, 20, 'white') setInterval(function() { ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.beginPath() a.draw() b.draw() c.draw() d.draw() e.draw() f.draw() g.draw() h.draw() t += 0.05 }, 40) } </code></pre> <p>Now, this works (!), but I've just lifted it directly from the original JavaScript, and modified the <code>document.getElementByID</code> calls to use <code>ref</code>s. Is it bad practice to stick all of this stuff into <code>componentDidMount</code>?</p> <p>Note - I'm aware that the code itself could be tidied up, I'm mainly asking about putting all of this (especially the definitions for <code>planet</code> and <code>generateStarField</code>) into <code>componentDidMount</code>.</p>
[]
[ { "body": "<p>You <em>can</em> do this, if it works... but it's not really using the React architecture or patterns.</p>\n\n<ul>\n<li><p>Most of this code that is drawing should be in the <code>render</code> method.</p></li>\n<li><p>You'll want to move some of the state (<code>canvas</code>, <code>ctx</code>, <code>bgCanvas</code>, <code>bgCtx</code>) into the class's state, or just as instance variables.</p></li>\n<li><p>You can probably do most of the creation in the constructor, although doing it in <code>componentDidMount</code> will work.</p></li>\n<li><p>You can integrate the animation with React, \n<code>setInterval(() =&gt; this.forceUpdate(() =&gt; this.t += 0.05))</code>. This makes sense in componentDidMount. You'll also want to turn this off in the unmount method.</p></li>\n</ul>\n\n<h2>EDIT/ADDED LATER</h2>\n\n<p>...maybe you just want to leave it the way it is, although it's quite non-React... it's working fine, though, and there aren't really problems... </p>\n\n<p>To make it \"React\" you're probably going to have to re-write it completely-- because just moving pieces around like I suggested may make you end up fighting the framework more than leveraging. Looking more, you'd probably make separate components for the different canvases and perhaps pass in <code>t</code> as a property, so there's a container component that functions as the \"clock\". Doing something like that would allow the regular React rendering mechanisms work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T17:10:18.963", "Id": "428283", "Score": "0", "body": "I'm a bit confused about the order of this - the canvas, ctx, bgCanvas, and bgCtx can't be defined until after render has completed (as render creates the <canvas /> elements), so how can any drawing be done until the componentDidMount?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T21:04:15.483", "Id": "428306", "Score": "0", "body": "Yeah, there's a bit of a start-up ordering issue, but I think having `React.createRef()` in the constructor and then you can just check in the `render` if it's set will work..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T03:47:59.363", "Id": "428326", "Score": "0", "body": "No you should not render animated content via `setInterval` and worse as canvas context is completely independent of the DOM you should never animate its content via reacts `forceUpdate`. Should use `requestAnimationFrame` in `componentDidMount` and stop it in `componentWillUnmount()`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:32:14.557", "Id": "221496", "ParentId": "221489", "Score": "1" } } ]
{ "AcceptedAnswerId": "221496", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T15:03:25.060", "Id": "221489", "Score": "2", "Tags": [ "javascript", "animation", "react.js", "canvas" ], "Title": "React component to animate planets on a canvas" }
221489
<p>I have solved this exercise, but it looks really redundant. Is there a built-in function in Java or a cleaner way to caluclate mod of a value + deviation without multiple OR statements? If I had to calculate this for a deviation of 5, this would then require a lot of repetition.</p> <blockquote> <p>Given a non-negative number "num", return true if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2.</p> </blockquote> <pre class="lang-java prettyprint-override"><code> public boolean nearTen(int num) { return isMod10(num) || isMod10(num - 1) || isMod10(num + 1) || isMod10(num - 2) || isMod10(num + 2); } private boolean isMod10(int num) { return num % 10 == 0; } </code></pre>
[]
[ { "body": "<p>You should read about congruent integers and <a href=\"https://en.wikipedia.org/wiki/Congruence_relation\" rel=\"noreferrer\">modular arithmic</a>. The distance of a number to a <em>base</em> is the minimum distance of its <em>congruent</em> value and its <em>inverted congruent</em> value.</p>\n\n<pre><code> public boolean nearBase(int num, int base, int deviation) {\n\n // ..TODO check guards, normalize input or throw exceptions \n // - base and deviation are expected strict positive integers\n // - deviation is expected smaller than base\n // - num is expected a positive integer\n\n var congruent = num % base;\n var inverted = base - congruent;\n var distance = Math.min(congruent, inverted);\n return distance &lt;= deviation;\n }\n\n // your method rewritten -&gt;\n public boolean nearTen(int num) {\n return nearBase(num, 10, 2);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T15:54:29.733", "Id": "428269", "Score": "0", "body": "Okay, thanks! I had this topic in introductory algebra but did not think about it at all." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T15:30:33.187", "Id": "221492", "ParentId": "221490", "Score": "5" } }, { "body": "<p>Let's consider the results of numbers around 10 as an example : </p>\n\n<blockquote>\n<pre><code>7 % 10 = 7\n8 % 10 = 8\n9 % 10 = 9\n10 % 10 = 0\n11 % 10 = 1\n12 % 10 = 2\n13 % 10 = 3\n</code></pre>\n</blockquote>\n\n<p>We know that 8 to 12 should be included.</p>\n\n<p>For 10 to 12 it's easy, we just need to check if their modulo is smaller than 2.</p>\n\n<pre><code>public boolean nearTen(int num) {\n int modulo = num % 10;\n return modulo &lt;= 2;\n}\n</code></pre>\n\n<p>For 8 and 9, if we look at the above results, we can see that the difference between their modulo and the original number will give us a number under 2. So we'll add that to the algorithm:</p>\n\n<pre><code>public boolean nearTen(int num) {\n int modulo = num % 10;\n return modulo &lt;= 2 || num - modulo &lt;= 2;\n}\n</code></pre>\n\n<p>With that, we covered all cases. When facing a problem like this one, don't be afraid to write down the results and try to find a match.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T15:38:15.630", "Id": "221494", "ParentId": "221490", "Score": "3" } }, { "body": "<p>Thanks to @<a href=\"https://codereview.stackexchange.com/users/202056/roastedpotatoe\">RoastedPotatoe</a>'s answer above; I now understand that we want to consider only those numbers which are in the range <span class=\"math-container\">\\$((10-2)\\%10)\\$</span> to <span class=\"math-container\">\\$((10+2)\\%10)\\$</span>. For example <span class=\"math-container\">\\$(8\\%10)\\$</span> to <span class=\"math-container\">\\$(12\\%10)\\$</span>.</p>\n<p>This means our use cases to be passed are:</p>\n<ul>\n<li><span class=\"math-container\">\\$(8\\%10=8)\\$</span>,</li>\n<li><span class=\"math-container\">\\$(9\\%10=9)\\$</span>,</li>\n<li><span class=\"math-container\">\\$(10\\%10=0)\\$</span>,</li>\n<li><span class=\"math-container\">\\$(11\\%10=1)\\$</span>, and</li>\n<li><span class=\"math-container\">\\$(12\\%10=2)\\$</span>.</li>\n</ul>\n<p>From here I know I can just say:</p>\n<ul>\n<li>if the remainder comes out to be 8 or 9 return true. Otherwise,</li>\n<li>if the remainder to be between 0 and 2 return true. Otherwise,</li>\n<li>return false.</li>\n</ul>\n\n<pre><code>public boolean nearTen(int num){\n if((num%10==8 || num%10==9) || (num%10 &gt;= 0 &amp;&amp; num%10 &lt;= 2)) return true;\n else return false;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-12T08:50:44.213", "Id": "249262", "ParentId": "221490", "Score": "-1" } }, { "body": "<p>Instead of your individual checks of the deviations in the range <code>-2 .. 2</code>, you could check the range as such. With a lower bound check and an upper bound check. Although <code>-2 .. 2</code> doesn't play well because <code>% 10</code> splits it into <code>8 .. 9</code> and <code>0 .. 2</code>. Shifting by 2 gives you the simpler range <code>0 .. 4</code>, which <code>% 10</code> leaves intact, and where we get the lower bound for free and only have to check the upper bound:</p>\n<pre><code> public boolean nearTen(int num) {\n return (num + 2) % 10 &lt;= 4;\n }\n</code></pre>\n<p>Btw, about yours you say <em>&quot;If I had to calculate this for a deviation of 5, this would then require a lot of repetition&quot;</em>, which isn't true. <em>Every</em> integer is within 5 of a multiple of 10, so you wouldn't need <em>any</em> checks for that. Anyway, for a generalization, you could do this:</p>\n<pre><code> public boolean nearTen(int num, maxDeviation) {\n return (num + maxDeviation) % 10 &lt;= 2 * maxDeviation;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-12T09:44:23.853", "Id": "249265", "ParentId": "221490", "Score": "2" } } ]
{ "AcceptedAnswerId": "221492", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T15:06:30.733", "Id": "221490", "Score": "3", "Tags": [ "java", "integer" ], "Title": "Test if a number is within 2 of a multiple of 10" }
221490
<p>I want to showcase with as minimal code as possible the basic Object-oriented programming (OOP) principles of Polymorphism, Inheritance, and Encapsulation. I know there are many more principles than just these 3 and even different types of the 3 I've mentioned there. I attempted to implement them all below. I think using Pokémon as an example is a good way to show this, so I've used <a href="https://bulbapedia.bulbagarden.net/wiki/Castform_(Pok%C3%A9mon)" rel="noreferrer">Castform</a> as my buddy of choice for these examples.</p> <p>If you believe showcasing more than just Polymorphism, Inheritance, and Encapsulation to evaluate a developers understanding of OOP, please provide comments around this and which additional key principles I should add to my Pokémon example.</p> <p><strong>Main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;time.h&gt; class Pokemon { protected: int m_dex_num; float m_catch_rate; std::string m_type; public: Pokemon(int dex_num, int catch_rate, std::string type) : m_dex_num(dex_num), m_catch_rate(catch_rate), m_type(type) {} int dex_num() const { return m_dex_num; } float catch_rate() const { return m_catch_rate; } std::string type() const { return m_type; } virtual bool attempt_catch() = 0; }; class Castform : public Pokemon { private: std::string m_forms[3] = { "sunny", "rainy", "snowy" }; public: Castform() : Pokemon(351, 11.9, "normal") {} bool attempt_catch() { srand(time(NULL)); return (rand() % 100) &lt; m_catch_rate; } }; int main() { auto wild_castform = Castform(); std::cout &lt;&lt; "Wild Castform appeared!\n"; std::cout &lt;&lt; "Dex number " &lt;&lt; wild_castform.dex_num() &lt;&lt; '\n'; std::cout &lt;&lt; "It's a " &lt;&lt; wild_castform.type() &lt;&lt; " type\n"; for(int i=0; i &lt; 5; ++i) { std::cout &lt;&lt; "Catch attempt resulted in " &lt;&lt; wild_castform.attempt_catch() &lt;&lt; '\n'; } return 0; } </code></pre> <p><a href="https://i.stack.imgur.com/Hu1fL.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Hu1fL.png" alt="c++"></a></p>
[]
[ { "body": "<ul>\n<li><p>It looks like all the <code>Pokemon</code> member variables should be private, not public.</p></li>\n<li><p>The <code>Pokemon</code> constructor takes <code>catch_rate</code> as an <code>int</code>, where it should be a float.</p></li>\n<li><p>The <code>Pokemon</code> constructor could <code>std::move</code> the string argument into <code>m_type</code>.</p></li>\n<li><p><code>Pokemon::type()</code> could return by <code>const&amp;</code> to avoid an unnecessary copy.</p></li>\n<li><p><code>Castform::m_forms</code> is not used anywhere, but should probably also be <code>static</code> and <code>const</code>.</p></li>\n<li><p>When overriding a virtual function, we should always use the <code>override</code> keyword (and arguably also the <code>virtual</code> keyword):</p>\n\n<pre><code>virtual bool attempt_catch() override { ... }\n</code></pre></li>\n<li><p>Use the C++11 <code>&lt;random&gt;</code> functionality, not <code>rand()</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>Run-time polymorphism with virtual functions in C++ is driven by a need to treat objects of different types with the same interface. Unfortunately, this example lacks the motivation for it:</p>\n\n<ul>\n<li><p>Currently the <code>attempt_catch()</code> function could be implemented in the <code>Pokemon</code> base-class with no problem.</p></li>\n<li><p>There is no example of differing behavior (i.e. there should be a second pokemon type implementing a different <code>attempt_catch()</code> function). Maybe an attack function would work better?</p></li>\n<li><p>There is no demonstration of using the different types through the same interface. In C++ this usually boils down to storing different types in the same container (e.g. iterating a <code>std::vector&lt;std::unique_ptr&lt;Pokemon&gt;&gt;</code> and calling the virtual function). However, it might be simpler to pass two different pokemon types to a function taking a <code>Pokemon</code> reference:</p>\n\n<pre><code>void throw_pokeball(Pokemon const&amp; target) { target.attempt_catch() } // or something\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>Depending on what this is actually for, I'd suggest approaching things in a \"problem <code>-&gt;</code> solution\" way, both in terms of what the code does (see above), but also in terms of language development and why these features exist. i.e.</p>\n\n<ul>\n<li><p>\"Here's what programmers used to have to do without this language feature [...]. It sucks because [...]\"</p></li>\n<li><p>\"This language feature allows us to do [...] safely and easily because [...]\".</p></li>\n</ul>\n\n<hr>\n\n<p>Note that there are many different types of both static and dynamic polymorphism in C++ (e.g. function overloading, implicit conversions, function objects, template parameters (traits, tags, etc.)), not just inheritance and virtual functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T18:37:44.813", "Id": "428574", "Score": "0", "body": "Using `std::move` on the string argument into `m_type` in the Pokemon ctor would avoid another unnecessary string copy correct?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T19:29:20.677", "Id": "221500", "ParentId": "221497", "Score": "7" } } ]
{ "AcceptedAnswerId": "221500", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T16:42:18.117", "Id": "221497", "Score": "6", "Tags": [ "c++", "object-oriented", "random", "c++17", "pokemon" ], "Title": "OOP demonstration in C++17 using a Pokémon" }
221497
<p>So I've been working on a simple little hashing algorithm for Python that I like to call PRBHA-10 for short, or Pseudo-Random-Based Hash Algorithm. This is a hash algorithm in Python that is meant to be simplistic and secure. As you could see from the title, the algorithm implements a system with seeding the pseudo-random number generator to be able to produce the correct integer values when provided the correct password, therefore enabling the decryption of an encrypted byte sequence or string.</p> <p>Here's the advantages of my method:</p> <ul> <li><p>The functions are tiny and simple, unlike some hashing methods out there.</p></li> <li><p>Despite the simplicity of the algorithm, it is secure due to the generation of large random numbers that scale with the password size.</p></li> <li><p>There is no chance of revealing even part of the encrypted string without the full password due to the huge numbers created by the seeded PRNG and multiplication that completely messes up the string if the wrong password is entered.</p></li> <li><p>It is fast. I have not done <code>timeit</code>s yet, but the functions run in a trivial amount of time to generate their results.</p></li> </ul> <p>The disadvantages:</p> <ul> <li><p>A somewhat large password is required to ensure security - usually anything over seven characters is completely cryptographically secure.</p></li> <li><p>It is vulnerable to the same brute-force attacks that any cryptographic encryption method is vulnerable to.</p></li> <li><p>With larger passwords comes greater security, but also a larger hash. The hash size slightly increases with each character added onto the password.</p></li> </ul> <p>Here's the whole module program, <code>prhba.py</code>:</p> <pre><code>"""Pseudo-Random Based Hash Algorithm (PRHBA-10) is a simple Python cipher that uses the integer representation of a string, along with taking advantage of the built-in pseudo-random number generator to be able to securely encrypt strings and bytearrays. The algorithm uses the integer representation of byte sequences, seeding the random number generator using the password to create a predictable random number for later use, and a special encoded form to turn any byte sequence into an ASCII string using only the letters 'aceilnorst'. This is secure due to the extremely large random number generated ensuring the security of the result. The result can be later decrypted using a special algorithm to decipher the text into a large integer number. Then, the password is used as a seed to once again get the random number used earlier in the process. That integer is used to modify the large integer to be able to get the integer form of the original string, which can then be converted to a string. This cipher currently only works in Python due to the specific random number generation implementation in the `random` module. """ import math import random __all__ = ["encrypt", "decrypt"] LETTERS = "aceilnorst" def to_num(s): return int.from_bytes(s.encode(), 'little') def from_num(n): return n.to_bytes(math.ceil(n.bit_length() / 8), 'little') def encrypt(data, password): assert len(password) &gt; 1, "Password length cannot be less than two" random.seed(to_num(password)) unique_id = to_num(data) * random.getrandbits(len(password)) chunk = [] for digit in str(unique_id): chunk.append(LETTERS[int(digit)]) return "".join(chunk) def decrypt(encrypted_data, password): random.seed(to_num(password)) partnum_digits = [] for char in encrypted_data: partnum_digits.append(str(LETTERS.index(char))) partnum = int("".join(partnum_digits)) return from_num(partnum // random.getrandbits(len(password))) </code></pre> <p>Here's the questions I have:</p> <ul> <li><p>Is it PEP-8 compliant?</p></li> <li><p>Are the variable names confusing?</p></li> <li><p>Is there any parts that could be improved or further reduced?</p></li> <li><p>Do you have any other suggestions?</p></li> </ul> <p>Thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-08T02:18:19.523", "Id": "429309", "Score": "0", "body": "If you want to understand how this stuff works, try reading about how real hash functions work. Most hashes use what's called the Merkle-Damgard construction, and understanding how that works and how the blocks that make up real hashes will probably help you understand the problem better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-08T02:21:13.080", "Id": "429310", "Score": "0", "body": "Also this isn't a hash function at all, it's an encryption algorithm. And if you don't understand the difference you definitely shouldn't be writing either." } ]
[ { "body": "<p>Don’t roll your own encryption. It takes a team of experts to develop new secure encryption methods, and even they can get it wrong from time to time.</p>\n\n<p>Huge hole in your DIY encryption:</p>\n\n<p>If I use a 2-character password, I might naïvely expect I’d have <span class=\"math-container\">\\$62^2\\$</span> possible passwords that I can encrypt the data with. I’d be really shocked when it turns out there are only 4.</p>\n\n<pre><code>random.getrandbits(len(password))\n</code></pre>\n\n<p>generates 2 random bits, for <span class=\"math-container\">\\$2^2\\$</span> possible values to multiply <code>to_num(data)</code> by. Only 4 possibilities is a lot easier to attack than <span class=\"math-container\">\\$62^2\\$</span> different possibilities!</p>\n\n<p>And one of those possibilities ... all bits zero ... destroys all the data you want to encode. So we’re down to actually only 3 possible numbers to test to reverse the encryption.</p>\n\n<hr>\n\n<p>Any encryption mechanism worth its salt uses a salt (initial random data) to prevent the same message with the same password from being encrypted as the same text.</p>\n\n<hr>\n\n<p>Code improvements: use generator expressions. Eg)</p>\n\n<pre><code>chunk = []\nfor digit in str(unique_id):\n chunk.append(LETTERS[int(digit)])\nreturn \"\".join(chunk)\n</code></pre>\n\n<p>would be more efficient rewritten as:</p>\n\n<pre><code>return \"\".join(LETTERS[int(digit)] for digit in str(unique_id))\n</code></pre>\n\n<p>The <code>chunk</code> list is never created in memory; instead, the <code>join</code> method pulls items one at a time from the generator expression.</p>\n\n<hr>\n\n<p>Finally, don’t roll your own encryption.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T21:05:29.823", "Id": "428307", "Score": "0", "body": "Thanks for the suggestion. I agree, it is lacking in the department of small passwords. That's why I said it needs sufficiently large passwords in the post. This was just something I was playing with - I don't actually expect it to compete with any standard cryptographic methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T22:28:12.560", "Id": "428316", "Score": "0", "body": "You missed the point. A two character pass phrase creates a *two bit* encryption key; an 10 character pass phrase creates a *10 bit* encryption key!!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T22:29:35.023", "Id": "428317", "Score": "0", "body": "No, yes, I understand that. It's a limitation I've been trying to get past." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T20:42:32.203", "Id": "221504", "ParentId": "221499", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T18:51:50.457", "Id": "221499", "Score": "4", "Tags": [ "python", "python-3.x", "random", "cryptography" ], "Title": "PRBHA-10: A hashing algorithm in Python" }
221499
<p><strong>The problem</strong></p> <blockquote> <p>For any given array, find a corresponding zig-zag array such the each element (a,b,c,d,e...) follows the rule:</p> <pre><code>a &lt; b &gt; c &lt; d &gt; e &lt; f </code></pre> </blockquote> <p>In other words, every other element is greater than both of its neighbouring elements and the remaining elements are smaller than their neighbours.</p> <p>For example, for the list:</p> <pre><code>[4, 3, 7, 8, 6, 2, 1] </code></pre> <p>the output is:</p> <pre><code>[1 8 2 7 3 6 4] </code></pre> <p><strong>My solution</strong></p> <pre><code>array = [4, 3, 7, 8, 6, 2, 1] array.sort() while len(array) &gt; 1: print(array[0], array[-1], sep = " ", end= " ") array.pop(0) if array: array.pop(-1) print(array[0]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T20:44:28.080", "Id": "428301", "Score": "0", "body": "(Hint: There is a cleaner solution utilizing [`zip`](https://docs.python.org/3.5/library/functions.html#zip))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T20:45:11.197", "Id": "428302", "Score": "0", "body": "I'm not sure if you sure my update as I just changed it..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T20:50:56.730", "Id": "428303", "Score": "0", "body": "Actually on second thoughts, I'm wrong, but you're not supposed to update code. Updated code is supposed to be a new question as per the FAQ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T20:53:23.173", "Id": "428304", "Score": "0", "body": "Sorry. As no one had replied I thought it'd be ok. I think you replied as I updated it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T22:05:54.520", "Id": "428313", "Score": "0", "body": "@Dair You can edit code before answers have been posted. There are some edge cases, but I don't think they're relevant here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T10:11:58.297", "Id": "428352", "Score": "0", "body": "What output do you expect for `[1, 1, 1, 1]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T10:12:46.073", "Id": "428353", "Score": "0", "body": "What output do you expect for `[1, 1, 2, 2, 2]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T10:21:13.483", "Id": "428355", "Score": "0", "body": "I'm not sure, sorry. I got this task from GeeksForGeeks and they didn't cover that case." } ]
[ { "body": "<p>You can just use Python's slice notation. It allows you to pass steps, which allows you to do this with ease.</p>\n\n<p>I also think it's fairly easy to understand.</p>\n\n<pre><code>def zigzag(values):\n half = len(values) // 2\n new = [None] * len(values)\n\n new[0::2] = values[:-half]\n new[1::2] = values[-half:][::-1]\n return new\n</code></pre>\n\n<pre><code>&gt;&gt;&gt; zigzag([1, 2, 3, 4])\n[1, 4, 2, 3]\n&gt;&gt;&gt; zigzag([1, 2, 3, 4, 5])\n[1, 5, 2, 4, 3]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T21:41:54.140", "Id": "428309", "Score": "0", "body": "How come you have written [:-half]? What is with the minus sign? Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T21:51:55.380", "Id": "428310", "Score": "1", "body": "I worked it out. I can see if I don't put the minus sign the sliced list is too short for lists of odd length if there is no minus sign" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T21:56:51.490", "Id": "428311", "Score": "1", "body": "@EML It's short hand for `values[:len(values) - half]`. `values[-half:]` takes the last `half` amount of items. `values[:-half]` takes the first `len(values) - half` items - which is 2 in the first example and 3 in the second." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T21:26:08.763", "Id": "221507", "ParentId": "221503", "Score": "1" } } ]
{ "AcceptedAnswerId": "221507", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-01T20:37:35.020", "Id": "221503", "Score": "1", "Tags": [ "python", "array" ], "Title": "Zig-zag array - solution" }
221503
<p>I have this log file (example below) and I'm trying to find the number of times a particular route is called. </p> <p>Example log file:</p> <blockquote> <pre><code>2019-05-29 11:00:00 192.168.1.1 POST /route1 200 100000 2019-05-29 11:00:01 10.1.1.2 POST /route1 200 100000 2019-05-29 11:00:01 192.168.1.2 GET /route2 404 200000 2019-05-29 11:00:02 192.168.1.3 GET /route3 200 100000 2019-05-29 11:00:03 10.1.1.3 GET /route4 200 200000 2019-05-29 11:00:04 192.168.1.1 POST /route1 200 100000 </code></pre> </blockquote> <p>Here is the code I've written:</p> <pre><code>route_count = Hash.new(0) File.open('test.log').each do |line| temp_array = line.split(" ") route = temp_array[4] if route_count.has_key?(route) route_count[route] = route_count[route] + 1 else route_count[route] = 1 end end puts( route_count.map{ |k,v| "#{k},#{v}" }) </code></pre> <p>and it gives the output:</p> <pre><code>/route1,3 /route2,1 /route3,1 /route4,1 </code></pre> <p>I wanted to know if there is a better way to do this.</p>
[]
[ { "body": "<p>The <code>Enumerable.group_by</code> method is perfect for situations like this. The method takes the items in the enumerable, evaluates a block on them to yield a key, and inserts them into a hash under that key. Using this the code is very short:</p>\n\n<pre><code>puts(File.open('test.log').entries\n .group_by { |line| line.split(\" \")[4] }\n .map { |k, v| \"#{k},#{v.count}\" })\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T04:25:05.553", "Id": "428327", "Score": "0", "body": "Thank you!! A much shorter and cleaner way." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T02:28:39.600", "Id": "221518", "ParentId": "221515", "Score": "4" } } ]
{ "AcceptedAnswerId": "221518", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T01:59:14.367", "Id": "221515", "Score": "1", "Tags": [ "ruby", "parsing" ], "Title": "Getting the count of how many times a route has been hit" }
221515
<p>So,I was looking for the non-recursive version of Trie data structures deletion in the internet. I couldn't find one. The best I could manage to find was a recursive implementation of trie in <a href="https://www.geeksforgeeks.org/trie-delete/" rel="nofollow noreferrer">this</a> website. Looking at the code for sometime, I thought that I could make the recursive version of the deletion to non-recursive one. Here is my take on it. Remember, I am worried whether I have done effective memory cleanup. Any insight on the overall code structure will also be helpful. Thanks.</p> <pre><code>#include&lt;iostream&gt; using namespace std; struct node{ bool isWord=false; node* previous; node* children[27]; }; void insert(node*&amp; root, string key){ node *temp = root; temp-&gt;previous = NULL; int keyLen = key.length(); for(int i=0; i&lt;keyLen; ++i){ int index = key[i]-'a'; //If i is the last element if(i==keyLen-1){ //then take notice of it //and change isWord to true temp-&gt;isWord=true; temp-&gt;children[index] = NULL; } //If there is no node at a given index if(!temp-&gt;children[index]){ //Form a new node temp-&gt;children[index] = new node; //Take notice of the node that it is coming from (temp-&gt;children[index])-&gt;previous = temp; } //Traverse along the children node temp = temp-&gt;children[index]; } } bool search(node*&amp;root, string key){ node*temp = root; int keyLen = key.length(); for(int i=0; i&lt;keyLen; ++i){ int index = key[i] -'a'; //If i is at string length //and the end the end it finds //itself to be true if(i==keyLen-1 &amp;&amp; temp-&gt;isWord==true) { return true; } //If a character does not exist //in the traversal if(!temp-&gt;children[index]){ return false; } temp = temp-&gt;children[index]; } //If the string is longer then expected return false; } bool hasNoChildren(node* root){ for(int i=0; i&lt;27; ++i){ //If the root has at least one child //then return false if(root-&gt;children[i])return false; } //else return true return true; } void remove(node*&amp; root, string key){ if(!search(root,key)) return ; node*temp = root; int keyLen = key.length(); for(int i=0; i&lt;keyLen; ++i){ int index = key[i]-'a'; /*If i reaches the length of the string temp is turned to false is turned to false Which means if day word 'foo' is part of longer word 'football', 'foo' does not exist as a seperate word. And if only 'foo' exist in the dictionary, it also signals for it get removed in the next for loop.*/ if(i==keyLen-1){ temp-&gt;isWord = false; } temp = temp-&gt;children[index]; } /*The pointer temp in the above for loop manages to reach to the end of the string Since, the previous pointer is being tracked it is easy to retract , if it is so required.*/ for(int i=keyLen-1; i&gt;=0; --i){ /*If the temp isWord variable is false and it happens to have not children then it is being removed. Not this removal happens in the bottom up fashion, which allows effective memory deletion.*/ if(temp-&gt;isWord == false &amp;&amp; hasNoChildren(temp)){ node*p = temp; temp = temp-&gt;previous; delete p; } else temp= temp-&gt;previous; } } int main(){ node* a = new node; string keys[] = { "the", "a", "there", "answer", "any", "by", "bye", "their", "hero", "heroplane" }; for (int i = 0; i &lt; 10; i++) insert(a, keys[i]); search(a, "the") ? cout &lt;&lt; "Yes\n" : cout &lt;&lt; "No\n"; search(a, "these") ? cout &lt;&lt; "Yes\n" : cout &lt;&lt; "No\n"; remove(a,"heroplane"); search(a, "hero") ? cout &lt;&lt; "Yes\n" : cout &lt;&lt; "No\n"; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T06:14:17.823", "Id": "428334", "Score": "1", "body": "How much of this code was actually written by you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T06:41:45.437", "Id": "428336", "Score": "3", "body": "I wrote the deletion portion, and I modified the search as well as insert function." } ]
[ { "body": "<ol>\n<li><p>Your code is not consistently formatted:</p>\n\n<ul>\n<li>Sometimes you have two empty lines before a function, sometimes none. Best to Always have exactly one.</li>\n<li>I suggest also leaving an empty line after the includes, as well as before any class-/struct-/union-definition.</li>\n<li>Sometimes you leave out the space between type and identifier.</li>\n<li>Sometimes you surround a binary operator with spaces, sometimes you don't for the same one.<br>\nI suggest one space on both sides for all but comma (<code>,</code>, leave a space after it) and member-access (<code>.</code> and <code>-&gt;</code>).</li>\n<li>I'm not sure why you sometimes put single statements into their own blocks for a control-structure, and sometimes don't.</li>\n<li>Space before a semicolon is very odd.</li>\n<li>Your indentation also deserves some more TLC.</li>\n</ul></li>\n<li><p>As the namespace <code>std</code> is not designed for being included wholesale, <code>using namespace std;</code> is a bug waiting to manifest. Read \"<a href=\"https://stackoverflow.com/q/1452721\">Why is “using namespace std” considered bad practice?</a>\" for the details.</p></li>\n<li><p>You use <code>std::string</code>, but you don't #include it. While any standard library header is allowed to include any others it likes, very few secondary includes are mandatory.</p></li>\n<li><p>Using a <code>std::string_view</code> wherever you currently use a <code>std::string</code> would remove many useless short-term allocations.</p></li>\n<li><p>Consider encapsulating your datastructure in its own class. That's what they are for!</p></li>\n<li><p>You are assuming keys only contain lowercase latin characters (or the one directly following, which is <code>{</code> for ASCII). I assume the 27<sup>th</sup> Slot is wrong. Also, consider throwing a <a href=\"https://en.cppreference.com/w/cpp/error/domain_error\" rel=\"nofollow noreferrer\"><code>std::domain_error</code></a> if you are wrong, and encapsulating the mapping in its own function.</p></li>\n<li><p>You are using a single in-class-initializer, specifically for <code>isWord</code>. That leaves all the rest un-initialized, resulting in UB.<br>\nPersonally, I would remove it and value-initialize the whole node.</p></li>\n<li><p>Three of four functions accept a <code>node*</code> by reference, assign it to a non-reference and forget it. I hope you see that's just wrong?</p></li>\n<li><p>You only use <code>node::previous</code> for <code>remove()</code>. It's pretty trivial to remove that need by saving the last node which must be retained.</p></li>\n<li><p>If you save the number of times a node is needed (children + endpoint), you can speed up testing for obsolescence considerably.</p></li>\n<li><p>You don't notify the caller if a key already is (<code>insert()</code>) respectively is not (<code>remove()</code>) in the trie.</p></li>\n<li><p><code>search()</code> should be able to deal with a constant Version of the trie.</p></li>\n<li><p>Consider adding <code>noexcept</code> and <code>constexpr</code> where appropriate.</p></li>\n<li><p>Your comments rephrase the code, adding nothing useful. Explain the why, not the what, the latter being far better represented by the code.</p></li>\n<li><p>While you should generally free all the resources you allocated, skipping it might be harmless at the end of the program for many of them. Anyway, think about how to free the whole datastructure.</p></li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code>.</p></li>\n</ol>\n\n<p>Modified code (<a href=\"http://coliru.stacked-crooked.com/a/116ac74115de98b6\" rel=\"nofollow noreferrer\">See live on coliru</a>):</p>\n\n<pre><code>#include &lt;stdexcept&gt;\n#include &lt;string_view&gt;\n#include &lt;utility&gt;\n\nstruct node {\n bool terminal;\n unsigned char count;\n node* children[26];\n};\n\nconstexpr static inline auto&amp; child(const node* p, char c) {\n if (c &lt; 'a' || c &gt; 'z')\n throw std::domain_error(\"Must be a lowercase latin letter\");\n return p-&gt;children[c - 'a'];\n}\nconstexpr static inline auto&amp; child(node* p, char c) {\n return const_cast&lt;node*&amp;&gt;(child(const_cast&lt;const node*&gt;(p), c));\n}\n\nbool insert(node*&amp; root, std::string_view key) {\n if (!root)\n root = new node();\n auto* p = root;\n for (auto c : key) {\n auto&amp; x = child(p, c);\n if (!x) {\n x = new node();\n ++p-&gt;count;\n }\n p = x;\n }\n if (p-&gt;terminal)\n return false;\n p-&gt;terminal = true;\n ++p-&gt;count;\n return true;\n}\n\nbool search(const node* root, std::string_view key) noexcept\ntry {\n for (auto c : key) {\n if (!root)\n break;\n root = child(root, c);\n }\n return root &amp;&amp; root-&gt;terminal;\n} catch(std::domain_error&amp;) {\n return false;\n}\n\nbool remove(node* root, std::string_view key) noexcept\ntry {\n auto p = root;\n if (!p)\n return false;\n for (std::size_t i = 0; i &lt; key.size(); ++i) {\n p = child(p, key[i]);\n if (!p)\n return false;\n if (p-&gt;count &gt; 1) {\n root = p;\n key = key.substr(i + 1);\n i = -1;\n }\n }\n if (!p-&gt;terminal)\n return false;\n --root-&gt;count;\n if (root == p) {\n root-&gt;terminal = false;\n return true;\n }\n p = std::exchange(child(root, key[0]), nullptr);\n key = key.substr(1);\n for (auto c : key)\n delete std::exchange(p, child(p, c));\n delete p;\n return true;\n} catch(std::domain_error&amp;) {\n return false;\n}\n\nvoid destroy(node* root) noexcept {\n if (!root)\n return;\n node* trees = nullptr;\n node* reserve = nullptr;\n root-&gt;count -= root-&gt;terminal;\n root-&gt;terminal = false;\n for (auto p = root, np = root; !reserve; p = np) {\n if (!root-&gt;count) {\n delete trees;\n delete root;\n return;\n }\n np = root;\n for (auto&amp; x : p-&gt;children) {\n if (x &amp;&amp; x-&gt;count == x-&gt;terminal) {\n --p-&gt;count;\n (!trees ? trees : reserve) = std::exchange(x, {});\n if (reserve)\n break;\n } else if (x) {\n np = x;\n }\n }\n }\n\n auto trees_free = std::size(trees-&gt;children);\n trees-&gt;children[--trees_free] = nullptr;\n trees-&gt;children[--trees_free] = root;\n while ((root = trees-&gt;children[trees_free++])) {\n if (trees_free == std::size(root-&gt;children)) {\n delete std::exchange(reserve, trees);\n trees = root;\n } else\n for (auto x : root-&gt;children)\n if (x &amp;&amp; x-&gt;count == x-&gt;terminal) {\n delete std::exchange(reserve, x);\n } else if (x) {\n if (!trees_free) {\n trees_free = std::size(trees-&gt;children);\n reserve-&gt;children[--trees_free] = trees;\n trees = std::exchange(reserve, {});\n }\n trees-&gt;children[--trees_free] = x;\n }\n }\n delete trees;\n delete reserve;\n}\n\n#include &lt;iostream&gt;\n\nint main() {\n node* a = nullptr;\n std::string_view keys[] = { \"the\", \"a\", \"there\", \"answer\", \"any\", \"by\",\n \"bye\", \"their\", \"hero\", \"heroplane\" };\n for (int i = 0; i &lt; 10; i++)\n insert(a, keys[i]);\n std::cout &lt;&lt; (search(a, \"the\") ? \"Yes\\n\" : \"No\\n\");\n std::cout &lt;&lt; (search(a, \"these\") ? \"Yes\\n\" : \"No\\n\");\n remove(a,\"heroplane\");\n std::cout &lt;&lt; (search(a, \"hero\") ? \"Yes\\n\" : \"No\\n\");\n std::cout &lt;&lt; (search(a, \"heroplane\") ? \"Yes\\n\" : \"No\\n\");\n destroy(a);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T00:10:06.090", "Id": "428480", "Score": "0", "body": "`You use std::string, but you don't #include it. While any standard library header is allowed to include any others it likes, very few secondary includes are mandatory.` For whatever reason, I was working on code recently, and in visual studio it let me use std::string while including <iostream>. So, it may not be technically be needed. However, I agree that it would be much clearer, and is not good to assume <iostream> includes string (even if it does)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T23:22:52.003", "Id": "221564", "ParentId": "221520", "Score": "3" } } ]
{ "AcceptedAnswerId": "221564", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T04:18:32.500", "Id": "221520", "Score": "4", "Tags": [ "c++", "trie" ], "Title": "Non-recursive version of Trie deletion" }
221520
<p>I believe this code prints both the DFS and BFS of a directed graph. As with some of my previous posts, this is mainly to share my code with other people working on a similar issue but I would also appreciate any feedback. </p> <p>In the code I have written, DFS and BFS use a pre-order technique, as follows:</p> <ul> <li><p>DFS (Depth first search) starts with a given node and explores the first unexplored node it comes across before returning to itself again and exploring its remaining nodes (e.g: if the parent node <code>1</code> has 2 children <code>2, 3</code> the DFS method will explore <code>2</code> and its children nodes before exploring <code>3</code>. It will print <code>self</code> before exploring its children (so <code>1-&gt;(2,3)</code> will print <code>1,2,3</code>))</p></li> <li><p>BFS (Breadth first search) works down a tree in a top-to-bottom manner (e.g: a graph with parent <code>1</code> and children <code>2, 3</code> will print level 1 first (<code>1</code>) then level 2 (<code>2, 3</code>) and then level 3 (<code>the children of nodes 2 and 3</code>). The level of a given node is determined by the highest level it could appear on (e.g: if <code>2</code> is a child of an item on <code>level 1</code> and <code>level 4</code>, it would be printed as if it were a <code>level 2</code> item)</p></li> </ul> <pre><code>from collections import defaultdict class Graph(): def __init__(self): self.value = defaultdict(list) def addConnection(self, parent, child): self.value[parent].append(child) def DFS(self, start): visited = [start] stack = [start] print(start, end = " ") while stack: s = stack[-1] if any([item for item in self.value[s] if item not in visited]): for item in [item for item in self.value[s] if item not in visited]: stack.append(item) visited.append(item) print(item, end= " ") break else: stack.pop() def BFS(self, start): visited = [start] queue = [start] while queue: x = queue.pop(0) print(x, end= " ") for item in self.value[x]: if item not in visited: queue.append(item) visited.append(item) #Build the graph g=Graph() g.addConnection(1,4) g.addConnection(1,2) g.addConnection(2,3) g.addConnection(2,6) g.addConnection(4,5) g.addConnection(4,7) g.addConnection(7,96) #Explore the graph g.DFS(1) print("\n") g.BFS(1) </code></pre> <p>Output is</p> <pre><code>DFS: 1 4 5 7 96 2 3 6 BFS: 1 4 2 5 7 3 6 96 </code></pre> <p>Adding a (2,4) node gives</p> <pre><code>DFS: 1 4 5 7 96 2 3 6 BFS: 1 4 2 5 7 3 6 96 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T12:11:44.543", "Id": "428367", "Score": "2", "body": "Could you include the output of your DFS and BFS algorithms using your example (parent 1, child 2, child 3) ? And perhaps also with child 2 having its own child 4." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T12:34:04.053", "Id": "428368", "Score": "0", "body": "Thanks for the update in the question. Both your algorithms are in Pre-Order." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T12:46:07.653", "Id": "428370", "Score": "0", "body": "Is this written for Python 2 or 3?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T13:02:03.100", "Id": "428372", "Score": "0", "body": "Python 3. sorry" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T04:39:35.597", "Id": "428487", "Score": "1", "body": "You talk about graphs and trees seemingly interchangeably. If your code works on graphs in general, then I'd rephrase the question to say that you are traversing graphs." } ]
[ { "body": "<h2>Clarification (OK)</h2>\n<p>After update of your question, it has gotten clear that:</p>\n<ul>\n<li>you work on a DAG, which includes a Tree</li>\n<li>both your strategies DFS and BFS are in Pre-Order</li>\n</ul>\n<hr />\n<p>=&gt; original answer requesting clarification from the OP</p>\n<h2>Review Definitions</h2>\n<p>Before being able to review your code, I would like to review your definitions. Perhaps you should clarify your algorithm with examples.</p>\n<blockquote>\n<p>I believe this code prints both the DFS and BFS of a directed graph.</p>\n</blockquote>\n<p>How do you decide the breadth level of a node when it has multiple parents? Or would you only work with <em>Tree</em> instead of <em>DAG</em>?</p>\n<blockquote>\n<p>As a reminder of the difference:</p>\n<p>DFS (Depth first search) starts with a given node and explores the\nfirst unexplored node it comes across before returning to itself again\nand exploring its remaining nodes (e.g: if the parent node 1 has 2\nchildren 2, 3 the DFS method will explore 2 and its children nodes\nbefore exploring 3</p>\n</blockquote>\n<p>Because you say to explore remaining nodes before returning to self, you are not very clear whether the order is A or B.</p>\n<ul>\n<li>(A) 1 -&gt; 2 -&gt; 3</li>\n<li>(B) 2 -&gt; 3 -&gt; 1</li>\n</ul>\n<blockquote>\n<p>BFS (Breadth first search) works down a tree in a top-to-bottom manner\n(e.g: a graph with parent 1 and children 2, 3 will print level 1 first\n(1) then level 2 (2, 3) and then level 3 (the children of nodes 2 and\n3)</p>\n</blockquote>\n<p>The <em>order</em> is independant of search <em>strategy</em> (DFS/BFS). BFS can be both top-to-bottom or bottom-to-top.</p>\n<hr />\n<h2>Terminology</h2>\n<ul>\n<li><strong>DFS</strong>: process each child completely before processing the next child</li>\n<li><strong>BFS</strong>: process each level across childs before processing the next level</li>\n<li><strong>Pre-Order</strong>: process self before rest of tree</li>\n<li><strong>Post-Order</strong>: process rest of tree before self</li>\n</ul>\n<p>In your example of parent 1 having child 2 and child 3:</p>\n<ul>\n<li>DFS Pre-Order: 1 -&gt; 2 -&gt; 3</li>\n<li>DFS Post-Order: 2 -&gt; 3 -&gt; 1</li>\n<li>BFS Pre-Order: 1 -&gt; 2 -&gt; 3</li>\n<li>BFS Post-Order: 2 -&gt; 3 -&gt; 1</li>\n</ul>\n<p>Suppose 2 would have its own child 4:</p>\n<ul>\n<li>DFS Pre-Order: 1 -&gt; 2 -&gt; 4 -&gt; 3</li>\n<li>DFS Post-Order: 4 -&gt; 2 -&gt; 3 -&gt; 1</li>\n<li>BFS Pre-Order: 1 -&gt; 2 -&gt; 3 -&gt; 4</li>\n<li>BFS Post-Order: 4 -&gt; 2 -&gt; 3 -&gt; 1</li>\n</ul>\n<p>You could even add a third dimension <em>direction</em> in which case we distinguish left-to-right and right-to-left.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T12:10:57.863", "Id": "221536", "ParentId": "221534", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T11:53:54.317", "Id": "221534", "Score": "3", "Tags": [ "python", "tree" ], "Title": "A BFS and DFS implementation" }
221534
<p>Exercise 7.2 from Python for Informatics:</p> <blockquote> <p>Write a program to prompt for a file name, and then read through the file and look for lines of the form:</p> <p><code>X-DSPAM-Confidence: 0.8475</code></p> <p>When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence.</p> <pre class="lang-none prettyprint-override"><code>Enter the file name: mbox.txt Average spam confidence: 0.894128046745 Enter the file name: mbox-short.txt Average spam confidence: 0.750718518519 </code></pre> <p>Test your file on the mbox.txt and mbox-short.txt files.</p> </blockquote> <p>My code works. It's a bit more forgiving with the amount of decimals on both input and output, but that's as intended.</p> <p>What I'm not happy about are the <code>ask_file_name</code> and <code>retrieve_values</code> functions. The first uses a hacky method of input validation (the Path module seems appropriate here, but that would be overkill), the second uses iteration while it shouldn't. Perhaps a <code>reduce</code> would be more appropriate, or something different altogether.</p> <p>This is written in modern Python. Which means it's written in Python 3 (3.5.2 to be exact, Python 3.7.x is incoming) and has plenty of docstrings. It should be up to standards, but I'd like to have that verified.</p> <h3>AverageSpamConfidence.py</h3> <pre class="lang-py prettyprint-override"><code>#! /usr/bin/env python3 # coding: utf-8 # Sample data from http://www.py4inf.com/code/ import re def ask_file_name(): """ Ask user for file name. Check for FileNotFound &amp; IsADirectory errors. Keyword arguments: - """ while True: try: user_input = input("Enter the file name: ") # Is the file there and can we open it? with open(user_input, "r") as test_input: pass except FileNotFoundError: print("Input empty or file does not exist.") continue except IsADirectoryError: print("That's not a directory, not a file.") continue else: return user_input def find_occurences_in_file(file_name): """ Find all occurences in target file. Keyword arguments: file_name -- name of (and path to) target file (example: mbox.txt) """ with open(file_name, "r") as input_file: return re.findall( 'X-DSPAM-Confidence: 0.[0-9]+', str(input_file.readlines()) ) def retrieve_values(input_list): """ Return relevant values from list. Keyword arguments: input_list -- list to results to retrieve values from """ return_list = [] for line in input_list: return_list.append(float(line.split()[-1])) return return_list def average(input_list): """ Calculate average of list provided. Keyword arguments: input_list -- list of numerical values """ return sum(input_list) / len(input_list) def main(): """ Exercise 7.2 (Python for Informatics, Charles Severance) Write a program to prompt for a file name, and then read through the file and look for lines of the form: X-DSPAM-Confidence: 0.8475 When you encounter a line that starts with “X-DSPAM-Confidence:” pull apart the line to extract the floating-point number on the line. Count these lines and then compute the total of the spam confidence values from these lines. When you reach the end of the file, print out the average spam confidence. """ file_name = ask_file_name() occurences = find_occurences_in_file(file_name) values = retrieve_values(occurences) print(average(values)) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T13:49:21.020", "Id": "428391", "Score": "1", "body": "I just noticed there's a stupid mistake in the print statement under `except IsADirectoryError:`. It's a directory, not a file. Not neither." } ]
[ { "body": "<ul>\n<li><p>I think <code>ask_file_name</code> looks fine without using <code>pathlib</code>. The difference between the two comes down to LBYL vs EAFP.</p>\n\n<p>For the most part the difference between the two is style. Do you prefer using <code>except FileNotFoundError</code> or an <code>if path.exists()</code>.</p></li>\n<li><p>What I do find strange is <code>ask_file_name</code> follows a LBYL approach, but the code inside it follows an EAFP approach.</p>\n\n<p>To make it fully EAFP return the file object you create in the <code>try</code>.</p></li>\n<li><p>I'd move the <code>input</code> call outside the <code>try</code>. Whilst it's unlikely to raise either error, it's a good habit to get into.</p></li>\n<li>There's no need to <code>continue</code> in the <code>except</code>, this is as there are no statements after the <code>try</code>.</li>\n<li><p>I don't understand why you've used <code>str(input_file.readlines())</code>.</p>\n\n<p>This converts from a list to a string adding additional noise. You can also read the entire file with <code>input_file.read()</code>.</p></li>\n<li><p><code>retrieve_values</code> can be changed to a list comprehension.</p></li>\n<li>Don't mix string delimiters, pick either <code>\"</code> or <code>'</code>.</li>\n<li>I'm not a fan of your names. I have changed them to what I would use, but you may dislike my naming style.</li>\n</ul>\n\n<p><sub>Docstrings removed for brevity</sub></p>\n\n<pre><code>#! /usr/bin/env python3\n# coding: utf-8\n\n# Sample data from http://www.py4inf.com/code/\n\nimport re\n\n\ndef get_file():\n while True:\n path = input('Enter the file name: ')\n try:\n return open(path, 'r')\n except FileNotFoundError:\n print('Input empty or file does not exist.')\n except IsADirectoryError:\n print(\"That's not a directory, not a file.\")\n\n\ndef find_confidences(file):\n return re.findall(\n 'X-DSPAM-Confidence: 0.[0-9]+',\n file.read()\n )\n\n\ndef retrieve_confidences(confidences):\n return [\n float(confidence.split()[-1])\n for confidence in confidences\n ]\n\n\ndef average(values):\n return sum(values) / len(values)\n\n\ndef main():\n with get_file() as file:\n occurences = find_confidences(file)\n confidences = retrieve_confidences(occurences)\n print(average(confidences))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T13:48:04.153", "Id": "428390", "Score": "0", "body": "As to why I used `str(input_file.readlines()`, that section comes from an old piece of code I'd written years ago. I modified it without updating it to follow the rest of the program's style. I'll see if I can modify my PEP8 validator to check for things like that as well. Thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T13:50:54.750", "Id": "428392", "Score": "0", "body": "Why I went with LBYL inside the EAFP `ask_file_name`? To maintain the wrapper. Your approach breaks it, right? The file now stays opened." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T13:55:15.567", "Id": "428394", "Score": "0", "body": "@Mast Yes if you only call `get_file` then it will stay open. However, in `find_confidences` I use the same file object in a with statement forcing the file to close when it exits that `with` statement. This isn't immediately apparent, and so I'll update the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T14:01:34.777", "Id": "428397", "Score": "0", "body": "Heh, that's legal? I didn't know that. That's going to solve a couple of problems I've had in other projects as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T14:14:50.177", "Id": "428404", "Score": "2", "body": "@Mast Yes. Since the [`__exit__` runs no matter what](https://www.python.org/dev/peps/pep-0343/#specification-the-with-statement) when you leave the `with` block then it doesn't matter if you defined the value in the with statement or before it. It should be noted that `__enter__` can return a different object, and so `cm = CM(); with cm as obj` can mean that `cm != obj`. With `open` AFAIK `cm == obj`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T22:38:31.647", "Id": "428464", "Score": "0", "body": "Should it be \"That's a directory, not a file\" instead of \"That's not a directory, not a file\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T22:40:54.037", "Id": "428466", "Score": "1", "body": "@alexyorke https://codereview.stackexchange.com/questions/221535/average-spam-confidence/221539?noredirect=1#comment428391_221535" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T13:08:26.947", "Id": "221539", "ParentId": "221535", "Score": "12" } }, { "body": "<p>Not duplicating any of @Peilonrayz's code review points ...</p>\n\n<hr>\n\n<p>Stop reading entire files into memory when you can process the file line by line in one pass, and stop creating huge lists in memory which are then iterated over exactly once. Both of these things creates a huge unnecessary memory pressure which can be avoided by looping and/or using generator expressions.</p>\n\n<p>Using a simple loop over all lines in the file:</p>\n\n<pre><code>def average_spam_confidence(filename):\n with open(filename) as file:\n count = 0\n total = 0\n for line in file:\n if line.startswith(\"X-DSPAM-Confidence: \"):\n try:\n total += float(line[20:])\n count += 1\n except:\n pass # Line ended with garbage\n return total / count\n</code></pre>\n\n<p>No regex. No reading entire file in memory. No creating a list of individual confidence values to sum up afterwards.</p>\n\n<p>Plus, we've fixed a bug! If \"<code>X-DSPAM-Confidence:</code>\" appears in the middle of a line, instead of at the start as required by the problem text, we don't try to process it.</p>\n\n<p>But perhaps you wanted a more functional way of programming, where you:</p>\n\n<ol>\n<li>find all the confidence lines,</li>\n<li>extract the confidence values, and</li>\n<li>compute the average</li>\n</ol>\n\n<p>... all as separate steps which you can compose together, and reuse to solve other problems. Fear not! We can do that too! Enter generator expressions:</p>\n\n<p>First, let's open the file, and read all the matching lines into a list, using list comprehension:</p>\n\n<pre><code>with open(filename) as file:\n lines = [line for line in file if line.startswith(\"X-DSPAM-Confidence: \")]\n</code></pre>\n\n<p>That second statement loops through each line in the file, checks if the line begins with the desired text, and if so, includes it in the list that is being constructed. We can later iterator over <code>lines</code> to further process each line individually.</p>\n\n<p>That is almost what we want to do. Well, that is exactly what we want to do, but we don't want to do it all at once. If we change the <code>[...]</code> to <code>(...)</code>, we move from list comprehension to a generator expression.</p>\n\n<pre><code>with open(filename) as file:\n lines = (line for line in file if line.startswith(\"X-DSPAM-Confidence: \"))\n</code></pre>\n\n<p>Now, the second statement has done ... nothing. We haven't read the first character of the file yet. What we have returned is a generator expression, which when we ask for the first value will start reading lines until it finds one that matches, and then it will pause its execution and return that value.</p>\n\n<p>Ok. Let's extract just the confidence values:</p>\n\n<pre><code> values = [ line[20:] for line in lines ]\n</code></pre>\n\n<p>Whoops! That's list comprehension. It will loop over all the lines that the <code>lines</code> generator can produce, skip over the prefix and return the rest. Again, change those <code>[...]</code> to <code>(...)</code>:</p>\n\n<pre><code> values = ( line[20:] for line in lines )\n</code></pre>\n\n<p>Better! Now those are still strings, so we'll need to convert them into float point values. Too easy. Just <code>map</code> them:</p>\n\n<pre><code> confidences = map(float, values)\n</code></pre>\n\n<p><code>confidences</code> is a generator. If you said <code>list(confidences)</code>, you'd create that in-memory list of float values for all the \"<code>X-DSPAM-Confidence:</code>\" values in the file. And you could then <code>sum(...)</code> and <code>len(...)</code> the list of values to compute the average. But we don't want to realize the list in memory, so ...</p>\n\n<pre><code>def average(data):\n total = 0\n count = 0\n for value in data:\n total += value\n count += 1\n return total / count\n\naverage_confidence = average(confidences)\n</code></pre>\n\n<p>... we ask for values from the <code>confidences</code> generator, add them up one at a time, counting as we go. When the generator is exhausted, the <code>for</code> loop ends, and we return the average.</p>\n\n<p>Putting it all together:</p>\n\n<pre><code>def average(data):\n total = 0\n count = 0\n for value in data:\n total += value\n count += 1\n return total / count\n\ndef average_spam_confidence(filename):\n with open(filename) as file:\n lines = (line for line in file if line.startswith(\"X-DSPAM-Confidence: \"))\n values = ( line[20:] for line in lines )\n confidences = map(float, values)\n return average(confidences)\n</code></pre>\n\n<p>Or more simply:</p>\n\n<pre><code>import statistics\n\ndef average_spam_confidence(filename):\n with open(filename) as file:\n values = (line[20:] for line in file\n if line.startswith(\"X-DSPAM-Confidence: \"))\n return statistics.mean(map(float, values))\n</code></pre>\n\n<p>Note: the non-generator solution was more robust converting the confidence value strings into floats, via a <code>try...except</code> block. The generator expression solution shown above omits that. The robustness may be improved by using a more precise matching when searching for the \"<code>X-DSPAM</code>\" lines (regex). Alternately, a generator function could be used, which discards the non-float values.</p>\n\n<pre><code>def map_to_float(data):\n for value in data:\n try:\n yield float(value)\n except:\n pass\n\nconfidences = map_to_float(values)\n</code></pre>\n\n<hr>\n\n<p><strong>Note</strong> (from @Roland Illig's comment): Because generator expressions delay the execution of their operation, any resources they use must remain available until their processing has been finished. They cannot be used to compute the average spam confidence if the file they are reading from is closed before the average has been computed. In the above examples, the generator expressions are fully consumed within the body of the <code>with open(...) as file:</code> block, so the file was kept open.</p>\n\n<p>This does not mean the generator expressions must all occur within the <code>with</code> statement. They can be spread out across many functions, but their execution must be constrained to the interval when the file is open:</p>\n\n<pre><code>def find_occurrences_in_file(input_file):\n \"\"\"Return a generator for occurrences of X-DSPAM lines\"\"\"\n return (line for line in input_file if line.startswith(\"X-DSPAM-Confidence: \"))\n\ndef retrieve_values(input_list):\n \"\"\"Return a generator for float values from a list\"\"\"\n return map(float, (line.split()[-1] for line in input_list))\n\ndef average(input_list):\n \"\"\"Compute average of a list/sequence/iterable/generator of values...\"\"\"\n return statistics.mean(input_list)\n\ndef average_spam_confidence(file_name):\n with open(file_name) as file:\n # File is open for this entire with statement.\n occurrences = find_occurrences_in_file(file)\n values = retrieve_values(occurrences)\n print(average(values))\n # File is closed here - but \"average(...)\" has exhaustively read\n # from all of the generators already.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T18:55:08.440", "Id": "428434", "Score": "3", "body": "Finally! Some mentions `statistics.mean` ... huzzah!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T21:13:44.533", "Id": "428450", "Score": "2", "body": "`return total / count` needs division-by-zero checking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T21:16:24.383", "Id": "428451", "Score": "3", "body": "@OhMyGoodness That is not a new issue; the OP’s code has that defect as well. Feel free to add your own answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T16:45:57.357", "Id": "221545", "ParentId": "221535", "Score": "15" } } ]
{ "AcceptedAnswerId": "221545", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T12:04:20.913", "Id": "221535", "Score": "13", "Tags": [ "python", "python-3.x", "programming-challenge", "regex", "file" ], "Title": "Average spam confidence" }
221535
<p>I would like to know the best way to setup my PHP Blog classes.</p> <p>I have created a Post class which creates a blog post.</p> <pre><code>class Post { private $title; private $body; private $createdDate; private $publishedDate = null; private $published = false; public function __construct(string $title, string $body) { $this-&gt;setTitle($title); $this-&gt;setBody($body); $this-&gt;createdDate = date('d/M/Y/'); } public function publish() { $this-&gt;published = true; $this-&gt;publishedDate = date('d/M/Y/'); } public function unpublish() { $this-&gt;published = false; $this-&gt;publishedDate = null; } public function setTitle(string $title) { $this-&gt;title = $title; } public function getTitle(): string { return $this-&gt;title; } public function setBody(string $body) { $this-&gt;body = $body; } public function getBody(): string { return $this-&gt;body; } } </code></pre> <p>I also have a simple Database class</p> <pre><code>class Database { private $db; public function __construct($host, $name, $username, $password) { $dsn = "mysql:host=$host;dbname=$name"; try { $this-&gt;db = new PDO($dsn, $username, $password); } catch (PDOException $e) { die('Error: ' . $e-&gt;getMessage()); } } } </code></pre> <p>My question is where should the database class be extended from? I could use it in my Post class, but it wouldn't really make sense to make Post queries related to just this specific blog post. It also wouldn't make sense to perform a query to get all posts just from this object. The SOLID principle states a class should just have one single responsibility. Therefore I'm concerned that creating a post object and running multiple queries within the class is causing the class to have lots of responsibilities. </p> <p>I have read about static methods where these could be of use, as I could run a query on a Post object, which wouldn't need to be instantiated. However, I have read that static methods should be avoided due to a variety of reasons, such as breaking encapsulation. </p> <p>I have searched for examples online, but they don't seem to be implementing OOP completely. Any Pure OOP examples you know would be great to hear about.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T15:39:04.393", "Id": "428414", "Score": "2", "body": "It's a pity, but this question will be closed as off topic, because only a working code is accepted, and this code does literally nothing. To briefly answer your questions: get rid of the database class, it does nothing useful at the moments. Use vanilla PDO instead. Pass a PDO instance as a Post's constructor. parameter. Having an entity class is an accepted trade-off, called ActiveRecord. It is frowned upon nevertheless, and a better implementation would be of a Data Mapper. Shortly, a class that has methods to load from the database your Post objects and persist them back." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T18:51:50.593", "Id": "428432", "Score": "0", "body": "Thanks for taking the time to help out here. I just want to make sure I am doing things the correct way. I will get some working code up so that I can get additional info." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T18:54:43.110", "Id": "428433", "Score": "0", "body": "Yes, it would be the best. Just write any working prototype you can think of, and then we will gladly review it" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T14:56:09.490", "Id": "221542", "Score": "1", "Tags": [ "php", "object-oriented" ], "Title": "correctly implement PHP OOP in blog Post Class" }
221542
<p><strong>This task</strong> is taken from <a href="https://leetcode.com/problems/trapping-rain-water/" rel="noreferrer">Leetcode</a> -</p> <blockquote> <p>Given <em>n</em> non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.</p> <p><a href="https://i.stack.imgur.com/2GykT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2GykT.png" alt="enter image description here"></a></p> <p>The above elevation map is represented by array <code>[0,1,0,2,1,0,1,3,2,1,2,1]</code>. In this case, 6 units of rain water (blue section) are being trapped. <strong>Thanks Marcos</strong> for contributing this image!</p> <p><strong>Example:</strong></p> <pre><code>Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 </code></pre> </blockquote> <p><strong>My solution</strong></p> <pre><code>/** * @param {number[]} height * @return {number} */ function trap(height) { let res = 0; const LEN = height.length; for (let i = 1; i &lt; LEN - 1; i++) { let maxLeft = 0, maxRight = 0; for (let j = i; j &gt;= 0; j--) { maxLeft = Math.max(maxLeft, height[j]); } for (let j = i; j &lt; LEN; j++) { maxRight = Math.max(maxRight, height[j]); } res += Math.min(maxLeft, maxRight) - height[i]; } return res; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T16:45:49.097", "Id": "428416", "Score": "2", "body": "Umm... who's Marcos?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T16:50:22.680", "Id": "428417", "Score": "16", "body": "The person who contributed that image to leetcode. (I just copied the description from leetcode) @Justin" } ]
[ { "body": "<p>You wrote very clear and readable code:</p>\n\n<ul>\n<li>the variable names express the purpose</li>\n<li>you use <code>const</code> and <code>let</code> instead of the old <code>var</code></li>\n<li>you encapsulated all the interesting code in a function, which makes it easy to copy and reuse the code</li>\n</ul>\n\n<p>You chose to use as few temporary memory as possible (4 local variables, no arrays or other objects), at the cost of needing more execution time, <span class=\"math-container\">\\$\\mathcal O\\left(\\text{len}(\\textit{height})^2\\right)\\$</span>. If you later need it, you could reduce the execution time to <span class=\"math-container\">\\$\\mathcal O\\left(\\text{len}(\\textit{height})\\right)\\$</span> by calculating <code>maxRight</code> once for all <code>i</code> and storing it in an array.</p>\n\n<p>You can optimize the inner <code>for</code> loop from the calculation of <code>maxLeft</code>, since it can be calculated by looking only at the previous <code>maxLeft</code> and the current <code>height[i]</code>:</p>\n\n<pre><code>function trap(height) {\n const len = height.length;\n let result = 0;\n\n if (len === 0)\n return 0;\n let maxLeft = height[0];\n\n for (let i = 1; i &lt; len - 1; i++) {\n maxLeft = Math.max(maxLeft, height[i]);\n ...\n }\n ...\n}\n</code></pre>\n\n<p>You only need to recalculate <code>maxRight</code> if <code>height[i - 1]</code> is equal to it. Because if it isn't, the maximum height cannot have changed.</p>\n\n<p>These two optimizations destroy the nice-looking symmetry of your current code. Therefore you may or may not want to apply them. In any case, you should know that they exist.</p>\n\n<p>In my above code I named the variable <code>len</code> instead of <code>LEN</code> since it feels more like a normal variable than like a constant. A constant is something whose value is the same over time. This <code>len</code> variable depends on the <code>height</code> parameter, therefore it may differ between multiple calls of the <code>trap</code> function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T17:13:35.483", "Id": "428420", "Score": "0", "body": "Thanks. I know it's not optimal, because the code iterates over the same values mutliple times. I'll improve it later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T01:54:01.277", "Id": "428482", "Score": "0", "body": "Why would `maxRight` need to be stored in an array? Isn't it just a single (scalar) value?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T06:01:08.070", "Id": "428489", "Score": "2", "body": "@Solomon that's in case you want to speed up the algorithm. As a first step, you could recalculate `maxRight` once at the beginning and later only after `height[i] == maxRight`. And if that is still not fast enough, you could iterate once over `height` and remember all indices where `maxRight` actually changes. This needs time O(n) and space O(n)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T06:02:47.237", "Id": "428490", "Score": "0", "body": "@Solomon the crucial point is that `maxRight` cannot be calculated by iterating the array in the normal order, the iteration needs to go backwards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T10:42:47.480", "Id": "428518", "Score": "0", "body": "@RolandIllig I'm slightly confused by your explanation, but I think I understand what you're saying: new elements get added to `maxLeft` and `maxRight` from opposite directions, so only one of them (in this case `maxLeft`) can go in the same direction as the main loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T21:58:51.150", "Id": "428779", "Score": "0", "body": "I suspect a one-pass algorithm with no lookahead may be possible. When you see a new local maximum (\"peak\"), you calculate the \"basin\" to the left that it holds in. e.g. if you start by assuming you'll see something to the right as tall as your current maxLeft, you can subtract the rectangle above that. This might actually require a whole array indexed by heights, though, to keep track of everything. Still, if your problem is much wider than it is tall, that could be a win." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T17:05:31.557", "Id": "221547", "ParentId": "221543", "Score": "22" } }, { "body": "<ul>\n<li><p>This is purely stylistic, but I'd add some spacing around the loops.</p></li>\n<li><p>I'm also not a fan of multiple declarations on the same line, so I'd separate out the <code>maxLeft</code> and <code>maxRight</code> declarations.</p></li>\n<li><p>Lastly, the parameter should arguably be called <code>heights</code>. <code>height</code> suggests that it's a single number representing a height, whereas it's actually multiple height values.</p></li>\n</ul>\n\n<hr>\n\n<pre><code>function trap(heights) {\n let res = 0;\n const LEN = heights.length;\n\n for (let i = 1; i &lt; LEN - 1; i++) {\n let maxLeft = 0\n let maxRight = 0;\n\n for (let j = i; j &gt;= 0; j--) {\n maxLeft = Math.max(maxLeft, heights[j]);\n }\n\n for (let j = i; j &lt; LEN; j++) {\n maxRight = Math.max(maxRight, heights[j]);\n }\n\n res += Math.min(maxLeft, maxRight) - heights[i];\n }\n\n return res;\n};\n</code></pre>\n\n<p>The spacing bulks the code up a bit, but I've always found code to be easier to read when it isn't all compacted together.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T18:25:40.040", "Id": "428426", "Score": "0", "body": "That image I linked to is massive though (30,000x20,000 pixels; ~75mb), so Drive won't be able to preview it properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T09:42:15.467", "Id": "428846", "Score": "0", "body": "Mod note: Comments are strictly for clarification and discussion of the post they are attached to. You're very welcome to socialize in [chat] :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T17:41:42.433", "Id": "221549", "ParentId": "221543", "Score": "21" } }, { "body": "<p>Here's a more functional approach you might like:</p>\n\n<pre><code>function trappedWater(heights) {\n const maxSoFar = arr =&gt; arr.reduce((m, x) =&gt; m.concat(Math.max(...m, x)), [])\n const leftWall = arr =&gt; [0, ...maxSoFar(arr).slice(0, -1)]\n const l = leftWall(heights)\n const r = leftWall(heights.reverse()).reverse()\n return heights.reduce((m, h, i) =&gt; m + Math.max(0, Math.min(l[i], r[i]) - h), 0)\n}\n</code></pre>\n\n<p><a href=\"https://tio.run/##fVCxTsQwDN3zFR5jkYtamGFkY2K4oeoQtb5rUJpUbno6CfHtxe1BKyRgiGP5@b28lzd3cWPDfsiHmFqa59MUm@xThMxuGKg9ukysO/LnLo8I7wqgSXHM0Lvra3p2DI/gWOrTclmmdmpI697AFZdhb2W9cVm/uNxZIWlr7YqigarGTS/QKR9dCLteVRhYlr8e0jJGOwYv@oIcSqx3srC@BTazG8q/oOL0QjySRtxbYTDliSPsW1uezoC/RYI72NKIk1vvow6Vrw2wVIQDdBKwQPWhlI/DlMWDBCpNYe7XWpqHtZNTK7UYTYFsSGf94@dXLuLfC/KH/6HFAs/zJw\" rel=\"nofollow noreferrer\" title=\"JavaScript (Node.js) – Try It Online\">Try it online!</a></p>\n\n<p>The main difference is that we first calculate the left \"wall\" height and the right \"wall\" height for every index, using the same <code>leftWall</code> function, which itself uses a \"scan sum\" utility function, and noticing that the <code>rightWall</code> values can be calculated using the <code>leftWall</code> function, by applying <code>reverse</code> to both the input and the output.</p>\n\n<p>The amount of water at any index is then the minimum of the left and right wall heights minus the height at the point, or zero if that quantity is negative. Then we just sum all of those. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T04:26:57.020", "Id": "221569", "ParentId": "221543", "Score": "9" } }, { "body": "<p>Going even more functional, splitting out mapping functions, spicing with a bit of <a href=\"https://en.wikipedia.org/wiki/Currying\" rel=\"nofollow noreferrer\">curry</a>.</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>// Curried initialization of the current max value\nconst maxSoFar = max =&gt; n =&gt; max = Math.max(max, n)\n// The max previous value; like max current but shifted to the right with a zero first\nconst maxPrevious = arr =&gt; [0, ...(arr.map(maxSoFar(0)))].slice(0, -1)\n// Note the [...arr] - .reverse() changes the original. Not very functional\nconst maxFollowing = arr =&gt; maxPrevious([...arr].reverse()).reverse()\n// Function to get mapping function subtracting two arrays\nconst subtract = otherArr =&gt; (n, index) =&gt; n - otherArr[index]\n// Like above, but taking the minimum value\n// Non-currying to make the main function more readable\nconst min = (arr, other) =&gt; arr.map((n, index) =&gt; Math.min(n, other[index]))\n\nconst trappedWater = heights =&gt; min(maxPrevious(heights), maxFollowing(heights))\n .map(subtract(heights))\n .filter(n =&gt; n &gt; 0) // Positive only\n .reduce((a,b) =&gt; a + b, 0) // Sum the array\n\nconsole.log(trappedWater([0,1,0,2,1,0,1,3,2,1,2,1]))\nconsole.log(trappedWater([0,1,1,0]))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Edit a couple years later. Happened on this and saw it could be a lot simpler, though losing some efficiency</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 maxBefore = (a, i) =&gt; Math.max(...a.slice(0,i+1))\nconst maxAfter = (a, i) =&gt; Math.max(...a.slice(i))\n\nconst trappedWater = heights =&gt; heights\n .map((n, i) =&gt; Math.min(maxBefore(heights, i), maxAfter(heights, i)) - n)\n .reduce((a,b) =&gt; a + b, 0) // Sum the array\n\nconsole.log(trappedWater([0,1,1,0]))\nconsole.log(trappedWater([0,1,0,2,1,0,1,3,2,1,2,1]))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>or inlining the maxes\n<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 trappedWater = heights =&gt; heights\n .map((n, i) =&gt; Math.min(Math.max(...heights.slice(0,i+1)), Math.max(...heights.slice(i))) - n)\n .reduce((a,b) =&gt; a + b, 0) // Sum the array\n\nconsole.log(trappedWater([0,1,1,0]))\nconsole.log(trappedWater([0,1,0,2,1,0,1,3,2,1,2,1]))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>or just using the fact that the max can include the current height to improve the original\n<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 maxSoFar = max =&gt; n =&gt; max = Math.max(max, n)\n\nconst trappedWater = heights =&gt; {\n const before = heights.map(maxSoFar(0))\n const after = heights.reverse().map(maxSoFar(0)).reverse()\n return heights\n .map((n, i) =&gt; Math.min(before[i], after[i]) - n)\n .reduce((a,b) =&gt; a + b, 0) // Sum the array\n}\nconsole.log(trappedWater([0,1,1,0]))\nconsole.log(trappedWater([0,1,0,2,1,0,1,3,2,1,2,1]))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T15:10:52.110", "Id": "428554", "Score": "1", "body": "yes! functionalism!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T20:17:51.463", "Id": "428765", "Score": "0", "body": "I have to start practicing FP and currying. As of now, that code is too packed for me" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T21:27:10.843", "Id": "428776", "Score": "0", "body": "I'm familar with FP, but this is hard to follow. Also, it's slower, which would be acceptable as long as you can write it more concise and readable. But this is not the case here. Also, you forgot to intialize the accumulator in `reduce`. And some comments are redundant, e.g. the last two." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:16:56.230", "Id": "428819", "Score": "0", "body": "@thadeuszlay Comments are overdone on purpose. Some of the functions could also be inline. The accumulator doesn't need to be initialized; [\"If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.\"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:32:29.083", "Id": "428820", "Score": "1", "body": "What happens if the reduce function is called on an empty array( and without an initial value)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:39:17.250", "Id": "428821", "Score": "0", "body": "@thadeuszlay Tested it, \"TypeError: Reduce of empty array with no initial value\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:42:30.670", "Id": "428823", "Score": "1", "body": "Yes. I think it's best to always provide an initial value" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:58:18.420", "Id": "428828", "Score": "0", "body": "@thadeuszlay At least in this use case, you're absolutely right. Edited the code and added a test case that failed before." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T11:49:13.373", "Id": "221585", "ParentId": "221543", "Score": "7" } }, { "body": "<h1>Reviewing complexity</h1>\n\n<p>So far only one answer has addressed the complexity issue, and is a considerable improvement over your solution. As the existing answers have addressed code style I will stick to the complexity as there is a less complex solution.</p>\n\n<h2>Looking both ways!?</h2>\n\n<p>Your solution is looking in both direction to find the next peak and thus calculate the volume trapped. You do this for each elevation and thus get a complexity of <span class=\"math-container\">\\$O(n^2)\\$</span> and <span class=\"math-container\">\\$O(1)\\$</span> storage.</p>\n\n<p>One answer's suggestion is to store the max values for quick reference which means you will need to increase the storage to <span class=\"math-container\">\\$O(n)\\$</span> in order to get <span class=\"math-container\">\\$O(n)\\$</span> complexity which is a much better approach.</p>\n\n<p>However the extra storage can be avoided.</p>\n\n<h2>Look behind.</h2>\n\n<p>To solved in <span class=\"math-container\">\\$O(1)\\$</span> storage and <span class=\"math-container\">\\$O(n)\\$</span> complexity use a two pass method that tracks the peak elevation you have already passed over (look behind rather than look both ways)</p>\n\n<p>One that passes from left to right checking all elevations and a second from right to left checking only to the highest peak found in the first pass. </p>\n\n<p>At most you will pass over each elevation twice, and best case is if the right most elevation is the highest you need only pass over each elevation once.</p>\n\n<p>This avoids the memory overhead and improves performance <sup><sup><sub><strong>[1]</strong></sub></sup></sup>, over the best solution so far suggested, by reducing the iterations to an average of <span class=\"math-container\">\\$n * 1.5\\$</span> rather than <span class=\"math-container\">\\$n * 2\\$</span></p>\n\n<p><sup><sup> <strong>[1]</strong> <em>Note performance does not mean complexity</em></sup></sup></p>\n\n<h2>Example</h2>\n\n<ul>\n<li><span class=\"math-container\">\\$O(1)\\$</span> storage, <span class=\"math-container\">\\$O(n)\\$</span> complexity solution</li>\n</ul>\n\n<p>I checked its correctness against your function, (farmed to get a good volume of tests, thus far at half a billion tests on random data the two functions agree)</p>\n\n<pre><code>function floodVolume(elevations) {\n var peakIdx, i = 0, peak = 0, volume = 0, total = 0;\n const depth = (i, elevation = elevations[i]) =&gt; {\n if (elevation &gt;= peak) {\n peak = elevation;\n peakIdx = i;\n total += volume;\n volume = 0;\n } else { volume += peak - elevation }\n }\n while (i &lt; elevations.length) { depth(i++) }\n const MAX_IDX = peakIdx;\n volume = peak = 0;\n while (i-- &gt;= MAX_IDX) { depth(i) } \n return total;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T09:43:09.993", "Id": "428847", "Score": "0", "body": "Mod note: Comments are strictly for clarification and discussion of the post they are attached to. You're very welcome to socialize in [chat] :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T13:08:11.477", "Id": "221588", "ParentId": "221543", "Score": "14" } }, { "body": "<p>I stumbled upon your question by accident (I normally only visit StackOverflow) and finally decided to make an account.</p>\n<h1>The Idea</h1>\n<p>After I saw @Blindman67's answer (which I cannot comment on since I do not have enough reputation), I was wondering if we could reduce the iterations from <span class=\"math-container\">\\$n* 1.5\\$</span> to just <span class=\"math-container\">\\$n\\$</span>. Thus, I propose this idea. Instead of evaluating all the way to the right and then coming back, create 2 different pointers.</p>\n<p>Pointer <code>i</code> would go from left to right, and pointer <code>j</code> would go from right to left. The idea is to get the first and last block, and figure out which one is higher. Then, use the lowest one for our walls. If <code>maxL &lt; maxR</code>, we move up, and compare <code>height[i]</code> to <code>maxL</code>, since we know for sure that there is a wall somewhere to the right side which will retain the water. On the other side, if <code>maxR &lt; maxL</code>, we do the opposite. By moving <code>i</code> up every time we compare it to <code>maxL</code> and <code>j</code> down every time we compare it to <code>maxR</code>, when <code>i=j</code> it means we evaluated every single point from our array.</p>\n<h1>Example Code</h1>\n<p>I believe the solution is still <span class=\"math-container\">\\$O(n)\\$</span> complexity and <span class=\"math-container\">\\$O(i)\\$</span> storage, but I have little knowledge in this field, so if anyone could confirm I would appreciate it.</p>\n<pre><code>var trap = function(height) {\n const len = height.length;\n let rainWater = 0;\n let maxL = height[0];\n let maxR = height[len - 1];\n let i = 1;\n let j = len - 2;\n \n while ( i &lt;= j ) { \n if ( maxL &lt; maxR ) {\n maxL = height[i] &gt; maxL ? height[i] : maxL; \n rainWater += maxL - height[i];\n i++; \n } else {\n maxR = height[j] &gt; maxR ? height[j] : maxR; \n rainWater += maxR - height[j];\n j--; \n }\n }\n return rainWater;\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T04:42:02.547", "Id": "428799", "Score": "1", "body": "I like the idea" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:02:20.827", "Id": "428860", "Score": "1", "body": "Welcome to CR... +1 Yes you have the complexity and storage correct and performance is an average 33% quicker. May I suggest that `moveUp` can be removed and the statement be `if (maxL < maxR) {` also `i++`, `j--` can be put into height eg `height[j--]`, and style with spaces `while (i <= j) {`, `if () {` and `} else {` (on same line as closing `}`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T20:59:57.063", "Id": "428951", "Score": "0", "body": "@Blindman67 I like your suggestions. I added moveup before, I was calculating it at the end of the loop, but then I realised it made more sense at the beggining and forgot to simplify it. As for `height[j--]`, I can't test it right now, but isn't `rainWater += maxL - height[i++]` change the expression, or is `i++` gonna be applied after it computes `maxL - height[i]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T00:44:02.147", "Id": "428962", "Score": "0", "body": "@Gabrield'Agosto post increment `i++` and decrement `i--` is performed after the expression is evaluated. eg if `j = 1` then `maxR - height[j--]` will get `height` at index 1. However its a minor change and you are best to stick with what you fell comfortable with." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T00:39:38.447", "Id": "221688", "ParentId": "221543", "Score": "4" } }, { "body": "<p>I liked the idea of doing this in a way which is analogous to the way the image is drawn, that is to say, creating a data structure which is somewhat similar to the image you have above, and then using that to count which spaces would hold water.</p>\n\n<p>This isn't so much of a code review, as a presentation of an alternative way of doing the same thing (as are many of the answers here). I don't know that I'd say it's better, but it was interesting to me at least.</p>\n\n<p>The code maps the size array to a grid of ones and zeroes, trims any initial zeroes, and then counts how many are left in each row. I'm fairly sure this will always give a correct result, but then, I may well have missed something.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const data = [1,0,2,1,0,1,3,2,1,2,1];\n\nconst sizesToRows = sizeArray =&gt; [...Array(Math.max(...sizeArray))]\n .map((_, i) =&gt; sizeArray.map(s =&gt; s &gt; i ? 1 : 0))\n\nconst trimArray = condition =&gt; array =&gt; array.slice(\n array.findIndex(condition),\n array.length - array\n .reduce((ary, ele) =&gt; {ary.unshift(ele); return ary}, [])\n .findIndex(condition)\n);\n\nconst removeLeadingAndTrailingZeroes = trimArray(x =&gt; x !== 0);\n\nconst countConditionMatches = condition =&gt; array =&gt; array\n .reduce((p, c) =&gt; condition(c) ? p + 1 : p, 0);\n \nconst countZeroes = countConditionMatches(x =&gt; x === 0);\n\nconst sum = (p, c) =&gt; p + c\n\nconst result = sizesToRows(data)\n .map(removeLeadingAndTrailingZeroes)\n .map(countZeroes)\n .reduce(sum, 0);\n \nconsole.dir(result)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:15:56.193", "Id": "428862", "Score": "1", "body": "There is a bug, `Array.reduce` second optional argument is not optional if the array is empty. eg `[0].reduce(sum)` works while `[].reduce(sum)` will throw an error, you need to provide the init value for empty arrays." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:45:29.723", "Id": "428868", "Score": "0", "body": "@Blindman67 Thanks, good spot, I've updated that now" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T10:14:54.183", "Id": "221713", "ParentId": "221543", "Score": "2" } } ]
{ "AcceptedAnswerId": "221547", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T16:32:53.340", "Id": "221543", "Score": "27", "Tags": [ "javascript", "algorithm", "programming-challenge" ], "Title": "Trapping Rain Water" }
221543
<p>I have no idea if this kind of lock is called time lock, but I need something for the following scenario: I'm making a lot of concurrent requests with <code>aiohttp</code>, and it's possible that the server at some point returns <code>429 Too Many Requests</code>. In that instance, I have to pause all my subsequent requests for some time.</p> <p>I came up with the following solution:</p> <pre class="lang-py prettyprint-override"><code>import asyncio class TimeLock: def __init__(self, *, loop=None): self._locked = False self._locked_at = None self._time_lock = None self._unlock_task = None self._num_waiters = 0 if loop is not None: self._loop = loop else: self._loop = asyncio.get_event_loop() def __repr__(self): state = f'locked at {self.locked_at}' if self._locked else 'unlocked' return f'[{state}] {self._num_waiters} waiters' @property def locked(self): return self._locked @property def locked_at(self): return self._locked_at async def __aenter__(self): await self.acquire() return self async def __aexit__(self, exc_type, exc, tb): # in this time lock there is nothing to do when it's released return async def acquire(self): if not self._locked: return True try: print('waiting for lock to be released') self._num_waiters += 1 await self._time_lock self._num_waiters -= 1 print('done, returning now') except asyncio.CancelledError: if self._locked: raise return True def lock_for(self, delay, lock_more=False): print(f'locking for {delay}') if self._locked: if not lock_more: # if we don't want to increase the lock time, we just exit when # the lock is already in a locked state print('already locked, nothing to do') return print('already locked, but canceling old unlock task') self._unlock_task.cancel() self._locked = True self._locked_at = time.time() self._time_lock = self._loop.create_future() self._unlock_task = self._loop.create_task(self.unlock_in(delay)) print('locked') async def unlock_in(self, delay): print('unlocking started') await asyncio.sleep(delay) self._locked = False self._locked_at = None self._unlock_task = None self._time_lock.set_result(True) print('unlocked') </code></pre> <p>I am testing the lock with this code:</p> <pre class="lang-py prettyprint-override"><code>import asyncio from ares.http import TimeLock async def run(lock, i): async with lock: print(lock) print(i) if i in (3, 6, 9): lock.lock_for(2) if __name__ == '__main__': lock = TimeLock() tasks = [] loop = asyncio.get_event_loop() for i in range(10): tasks.append(run(lock, i)) loop.run_until_complete(asyncio.gather(*tasks)) print(lock) </code></pre> <p>The code produces the following output, which seems to be consistent with what I want from the above scenario:</p> <pre><code>[unlocked] 0 waiters 0 [unlocked] 0 waiters 1 [unlocked] 0 waiters 2 [unlocked] 0 waiters 3 locking for 2 locked waiting for lock to be released waiting for lock to be released waiting for lock to be released waiting for lock to be released waiting for lock to be released waiting for lock to be released unlocking started unlocked done, returning now [unlocked] 5 waiters 4 done, returning now [unlocked] 4 waiters 5 done, returning now [unlocked] 3 waiters 6 locking for 2 locked done, returning now [locked at 1559496296.7109463] 2 waiters 7 done, returning now [locked at 1559496296.7109463] 1 waiters 8 done, returning now [locked at 1559496296.7109463] 0 waiters 9 locking for 2 already locked, nothing to do unlocking started [locked at 1559496296.7109463] 0 waiters </code></pre> <p>Is the implementation correct, or can it be improved somehow?</p> <p><em>EDIT</em>: After doing a few experiments I think that the implementation works well. I am not sure about the thread-safety of this code though. I don't have too much experience with threads and asyncio code.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T17:13:08.900", "Id": "221548", "Score": "4", "Tags": [ "python", "asynchronous", "locking" ], "Title": "Implementation of a time lock with Python's asyncio" }
221548
<p>This is an update of the code for my <a href="https://codereview.stackexchange.com/questions/221513/generate-new-array-of-length-n-where-n2-0-from-2-arrays">previous post</a> (which has now been removed as this code is more efficient and accurate) for the <a href="https://www.geeksforgeeks.org/generate-all-possible-sorted-arrays-from-alternate-elements-of-two-given-arrays/" rel="noreferrer">GeeksForGeeks</a> task.</p> <p><strong>Task outline</strong></p> <p>Given two arrays, print all new arrays of <em>even</em> length where each subsequent element in the new array comes alternately from A then B <strong>and</strong> each element is larger than the previous element</p> <p><em>Example</em>:</p> <ul> <li>Array 1 = [1, 2, 3]</li> <li>Array 2 = [2, 4, 6]</li> </ul> <p>Possible new array lengths = [2, 4, 6]</p> <p>The output for arrays of length 2 is: <code>[1,2], [1,4], [1,6], [2,4], [2,6], [3,4] [3,6]</code></p> <p>The full solution for the above includes the following two additional arrays: <code>[1 2 3 4], [1 2 3 6]</code></p> <p>This solution uses the <code>itertools</code> library </p> <pre><code>import itertools A=[10, 20, 30,40] B=[11,21,31,41] list_solutions = [] for x in range (1,min(len(A),len(B))+1): newA = list(itertools.combinations(A,x)) newB = list(itertools.combinations(B,x)) for itemA in newA: for itemB in newB: to_print = True for index in range (min(len(itemA),len(itemB))): if itemA[index] &gt;= itemB[index]: to_print = False break if to_print == True: list_solutions.append([itemA, itemB]) #Print only valid solutions: for item in list_solutions: print_valid = True for index in range (len(item[0])): if item[0][index] &gt;= item[1][index]: print_valid = False break if index &gt;= 1: if item[0][index] &lt;= item[1][index-1]: print_valid = False break if print_valid == True: for index in range (len(item[0])): print (item[0][index], item[1][index], sep = " ", end = " ") print ("") if print_valid == False: continue </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T18:03:39.837", "Id": "428572", "Score": "0", "body": "Have you figure out the `selector ^ 1` moment? I have added explanation to the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T18:18:09.100", "Id": "428573", "Score": "0", "body": "Yes thanks. I ran a few examples myself and worked it out. THanks for the update" } ]
[ { "body": "<p>It's unclear to me why you didn't chose to use a tree. From your example you know:</p>\n\n<ul>\n<li><code>A[0]</code> has the children <code>B[0:]</code>.</li>\n<li><code>A[1]</code> has the children <code>B[1:]</code>.</li>\n<li><p><code>A[2]</code> has the children <code>B[1:]</code>.</p></li>\n<li><p><code>B[0]</code> has the children <code>A[2:]</code>.</p></li>\n<li><code>B[1]</code> has no children.</li>\n<li><code>B[2]</code> has no children.</li>\n</ul>\n\n<p>From this you should be able to see that you'll just have to walk the tree to get the values.</p>\n\n<p>To get all the values you walk the tree with the roots being all the values in <code>A</code>. And you filter odd results.</p>\n\n<pre><code>class Node:\n def __init__(self, value):\n self.value = value\n self.children = []\n\n def walk(self, path=None):\n path = (path or ()) + (self.value,)\n yield path\n for child in self.children:\n yield from child.walk(path)\n\n\ndef solution(A, B):\n A = [Node(a) for a in A]\n B = [Node(b) for b in B]\n\n for parents, children in ((A, B), (B, A)):\n for parent in parents:\n parent.children = [\n child\n for child in children\n if child.value &gt; parent.value\n ]\n\n for start in A:\n for values in start.walk():\n if len(values) % 2 == 0:\n print(values)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:23:47.270", "Id": "428441", "Score": "0", "body": "I actually never considered that as a possibility. But it makes so much sense!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:28:37.063", "Id": "428443", "Score": "0", "body": "On second thoughts....A tree as above wouldn't work if the inputs were A = [10,15,20] and B was [1,4,15,20]. The example I gave perhaps was too simple. But it is possible for elements in B to be smaller than those in A at the equivalent position" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:30:05.897", "Id": "428444", "Score": "1", "body": "@EML I have tested the above code. It works with that input. Notice how I didn't discriminate by index in the selection of the children." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T23:13:43.540", "Id": "428472", "Score": "0", "body": "I tried to break down your ```for parents, children...``` loop into two separate loops \n```for parent in A:\n parent.children = [child for child in B if child.value > parent.value]``` and \n ```for parent in B:\n parent.children = [child for child in B if child.value > parent.value]``` \nbut this didn't work. Do you know why? Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T23:17:50.900", "Id": "428473", "Score": "1", "body": "@EML Second loop, comprehension and outer loop both loop over `B`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T23:19:37.473", "Id": "428474", "Score": "0", "body": "Oh yes. So it does. Sorry. Thanks for pointing out out!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:22:09.980", "Id": "221555", "ParentId": "221552", "Score": "5" } }, { "body": "<h3>Reference</h3>\n\n<p>When solving puzzles from websites, I always include the link and the task description.\nIn case of Project Euler questions, this already helped me figure out that their tasks change over time.\nIn your case, such a reference could look like</p>\n\n<pre><code># https://www.geeksforgeeks.org/generate-all-possible-sorted-arrays-from-alternate-elements-of-two-given-arrays/\n# Given two sorted arrays A and B, generate all possible arrays such that first element is taken from A then from B then from A and so on in increasing order till the arrays exhausted. The generated arrays should end with an element from B.\n</code></pre>\n\n<h3>Redundant comparisons</h3>\n\n<p>In your code I see <code>if xxx == True:</code> which can be shortened to <code>if xxx:</code>. I wrote the same code as a beginner, so I guess it's absolutely normal.</p>\n\n<p>Similarly, <code>if xxx == False:</code> would be written as <code>if not xxx:</code>.</p>\n\n<p>An IDE like PyCharm will give you hints for such issues and even help you replace it by an equivalent.</p>\n\n<h3>Unnecessary continue statement</h3>\n\n<pre><code>if print_valid == False:\n continue \n</code></pre>\n\n<p>This part is unnecessary, since it's the last statement of the loop, so the loop would continue anyway.</p>\n\n<h3>Separate output from logic</h3>\n\n<p>Do the calculations on their own, then do all the printing. E.g. define a function which prints the lists as you like to:</p>\n\n<pre><code>def print_all(results: List) -&gt; None:\n for result in results:\n for item in result:\n print(item, sep=\" \", end=\" \")\n print()\n</code></pre>\n\n<h3>Type safety</h3>\n\n<p>You can <code>from typing import *</code>and use type hints to make clear what types are used. This is especially useful when using functions (see next section).</p>\n\n<h3>Use testable functions</h3>\n\n<p>Right now, you have some input which gives some output, but you don't have a test whether your code works for the given input. The website already indicates that there is a defined set of solutions for the given input <code>A = {10, 15, 25}</code>and <code>B = {1, 5, 20, 30}</code>.</p>\n\n<p>You could implement it like this:</p>\n\n<pre><code>def get_potential_solutions() -&gt; List:\n list_solutions = []\n ...\n return list_solutions = []\n\ndef filter_solutions(list_solutions: List) -&gt; List:\n # Print only valid solutions:\n valid_results = []\n current_result = []\n for item in list_solutions:\n ...\n return valid_results\n\nlist_solutions = get_potential_solutions(A, B)\nlist_solutions = filter_solutions(list_solutions)\nprint_all(list_solutions)\n</code></pre>\n\n<p>You can then implement an assertion which will warn you whenever you broke your code.</p>\n\n<pre><code>givensolution = [[10, 20], [10, 30], [15, 20], [15, 30], [25, 30], [10, 20, 25, 30], [15, 20, 25, 30]]\nsolution = filter_solutions(get_potential_solutions([10, 15, 25], [1, 5, 20, 30]))\nassert (solution == givensolution)\n</code></pre>\n\n<p>If you do this many times, read about unit tests.</p>\n\n<h3>Naming</h3>\n\n<p>I still didn't understand the algorithm you implemented. It may have to do with the terms <code>x</code>, <code>item</code>, <code>index</code>, <code>newA</code> and <code>newB</code>, <code>itemA</code> and <code>itemB</code>, which tell me nothing.</p>\n\n<ul>\n<li><code>x</code> is used in <code>itertools.combinations()</code>, so it must be the length</li>\n<li><code>newA</code> and <code>newB</code> are combinations, so I renamed them to <code>combinationsA</code> and <code>combinationsB</code></li>\n<li><code>itemA</code> and <code>itemB</code> are a specific combination, so I renamed them to <code>combinationA</code> and <code>combinationB</code></li>\n</ul>\n\n<p>You may say that this is not an improvement. I'd say I moved from a nonsense name to a honest name, which is at least one step better, but still on <a href=\"https://twitter.com/llewellynfalco/status/634014935706636288\" rel=\"nofollow noreferrer\">level 2 of the 6 stages of naming</a></p>\n\n<h3>Doubled condition</h3>\n\n<p>IMHO, the condition in <code>get_potential_solutions()</code></p>\n\n<pre><code>if combinationA[position] &gt;= combinationB[position]:\n valid = False\n break\n</code></pre>\n\n<p>is identical to the condition in <code>filter_solutions()</code></p>\n\n<pre><code>if item[0][index] &gt;= item[1][index]:\n valid = False\n break\n</code></pre>\n\n<p>Since it is about filtering, I'd prefer to remove it in the potentials method.</p>\n\n<h3>Make smaller methods</h3>\n\n<p>The check whether a potential solution is valid or not can be moved into its own method.</p>\n\n<pre><code>def is_valid_solution(potential):\n for index in range(len(potential[0])):\n if potential[0][index] &gt;= potential[1][index]:\n return False\n if index &gt;= 1:\n if potential[0][index] &lt;= potential[1][index - 1]:\n return False\n return True\n</code></pre>\n\n<p>The next loop seems to just clean up the results in order to remove the tupels. This can be done in a method as well:</p>\n\n<pre><code>def flatten(potential):\n current_result = []\n for index in range(len(potential[0])):\n current_result.append(potential[0][index])\n current_result.append(potential[1][index])\n return current_result\n</code></pre>\n\n<h3>Single responsibility</h3>\n\n<p>The <code>filter_solutions()</code> method now does 2 things: filtering and flattening. One could argue that this should be separated. And it's simple to do now.</p>\n\n<h3>Final result</h3>\n\n<pre><code>import itertools\nfrom typing import *\n\nA = [10, 20, 30, 40]\nB = [11, 21, 31, 41]\n\n\ndef get_potential_solutions(a: List, b: List) -&gt; List:\n potentials = []\n for length in range(min(len(a), len(b))):\n combinationsA = list(itertools.combinations(a, length + 1))\n combinationsB = list(itertools.combinations(b, length + 1))\n for combinationA in combinationsA:\n for combinationB in combinationsB:\n potentials.append([combinationA, combinationB])\n return potentials\n\n\ndef filter_solutions(potentials: List) -&gt; List:\n valid_results = []\n for potential in potentials:\n if is_valid_solution(potential):\n valid_results.append(potential)\n return valid_results\n\n\ndef is_valid_solution(potential):\n for index in range(len(potential[0])):\n if potential[0][index] &gt;= potential[1][index]:\n return False\n if index &gt;= 1:\n if potential[0][index] &lt;= potential[1][index - 1]:\n return False\n return True\n\n\ndef flatten_list(solutions: List) -&gt; List:\n result = []\n for solution in solutions:\n result.append(flatten(solution))\n return result\n\n\ndef flatten(potential):\n current_result = []\n for index in range(len(potential[0])):\n current_result.append(potential[0][index])\n current_result.append(potential[1][index])\n return current_result\n\n\ndef print_all(results: List) -&gt; None:\n for result in results:\n for item in result:\n print(item, sep=\" \", end=\" \")\n print()\n\n\ngivensolution = [[10, 20], [10, 30], [15, 20], [15, 30], [25, 30], [10, 20, 25, 30], [15, 20, 25, 30]]\nsolution = flatten_list(filter_solutions(get_potential_solutions([10, 15, 25], [1, 5, 20, 30])))\nassert (solution == givensolution)\n\nlist_solutions = get_potential_solutions(A, B)\nlist_solutions = filter_solutions(list_solutions)\nprint_all(flatten_list(list_solutions))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T21:08:27.617", "Id": "428449", "Score": "2", "body": "Thanks for this detailed feedback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T21:03:22.730", "Id": "221561", "ParentId": "221552", "Score": "4" } }, { "body": "<p>Just another approach. It is recursive solution, so it can't process big lists. I get \"maximum recursion depth exceeded\" with more than 1000 items lists. Also, I think it is slow, because it walks through both lists from the beginning every time to greater number search. But it is easy and short, so as an example.</p>\n\n<pre><code>def possible_arrays(lis, num, selector, buf):\n for val in lis[selector]: \n\n if val &gt; num:\n\n if selector:\n print(*buf, val)\n\n possible_arrays(lis, val, selector ^ 1, buf + [val])\n</code></pre>\n\n<p><strong>Explanation:</strong></p>\n\n<p><code>selector ^ 1</code> - is an <a href=\"https://stackoverflow.com/q/14526584/2913477\">exclusive or</a> logical operation. I use it for fast switching <code>selector</code> from <code>1</code> to <code>0</code> or from <code>0</code> to <code>1</code>. It is needed, because the <code>lis</code> variable is a list comprising two lists: <code>l_a</code> and <code>l_b</code> and I want to select one or another alternately. <code>lis[0]</code> points to <code>l_a</code>, <code>lis[1]</code> points to <code>l_b</code>.</p>\n\n<p><strong>For example:</strong> in the first <code>possible_arrays</code> function call the <code>selector</code> equals to <code>0</code>, so we work with the first list (<code>l_a</code>). When the necessary number is found, we should change the working list to the second one (<code>l_b</code>). We achieve this by doing <code>selector ^ 1</code> -> <code>0 ^ 1</code> -> <code>1</code> and passing the <code>1</code> to the next <code>possible_arrays</code> call. In the next call, when we should switch back to the first list, we do <code>selector ^ 1</code> -> <code>1 ^ 1</code> -> <code>0</code> again. And so on. This way we alternate used lists from one to another as the task was supposing.</p>\n\n<p><strong>Test 1:</strong></p>\n\n<pre><code>l_a = [10, 15, 25]\nl_b = [1, 5, 20, 30]\n\nl_main = [l_a, l_b]\npossible_arrays(l_main, 0, 0, [])\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>10 20\n10 20 25 30\n10 30\n15 20\n15 20 25 30\n15 30\n25 30\n</code></pre>\n\n<p><strong>Test 2:</strong></p>\n\n<pre><code>l_a = [1, 2, 3]\nl_b = [2, 4, 6]\n\nl_main = [l_a, l_b]\npossible_arrays(l_main, 0, 0, [])\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<pre><code>1 2\n1 2 3 4\n1 2 3 6\n1 4\n1 6\n2 4\n2 6\n3 4\n3 6\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T17:01:39.570", "Id": "221595", "ParentId": "221552", "Score": "2" } } ]
{ "AcceptedAnswerId": "221561", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T18:17:53.413", "Id": "221552", "Score": "6", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Version 2 - print new even-length arrays from two arrays" }
221552
<p>Given a matrix you shall stripe the matrix, such that every number that has equal distance to the matrix border will be filled into an array.</p> <p>For examples see code comments.</p> <pre><code>typedef int matrixOptimizationValue; /* Striping a matrix by packing numbers who have the same distance from matrix border. Note that the packing is anti-clockwise. E.g: Example 1: ___ ___ . 1 1 1 1 . Field: . 2 2 2 2 . [1,2,3,3,3,3,2,1,1,1] . 3 3 3 3 . --&gt; [2,2] ___ ___ Example 2: ___ ___ Field: . 1 1 1 4 1 . [1,2,3,1,2,4,5,6,3,2,1,4,1,1,1] . 2 2 2 3 2 . [2,3,3,3,2,3,2,3,2,2] . 3 3 3 2 3 . --&gt; . 1 2 4 5 6 . ___ ___ returns: return_value - Field of Arrays; unpacked Matrix arr_lengths - Since fields arrays have a variable size, "*array_lengths" contains the following information. {Amount of arrays in the field, sizes_of_array01, sizes_of_array03 ... } Therefore "*array_lengths" size must be *array_lengths[0]+1. in: const int* matrix - Matrix to be unpacked int rows - rows of the matrix int columns - columns of the matrix Possible Errors: 1. Matrix has no measurments. */ matrixOptimizationValue** strip(const matrixOptimizationValue* matrix, const int rows, const int columns, int** arr_lengths){ //Checking if Matrix has measurments. int* lengths = *arr_lengths; if(rows == 0 || columns == 0){ printf("\nMatrix has no measurments. Error. \n"); exit(0); } //Calculating maximal distance of an element to borders. const int max_dis = (columns &gt; rows) ? round((double)(rows)/2) : round((double)(columns)/2); //Creating future return_value matrixOptimizationValue** unstriped_matrix = malloc(max_dis*sizeof(int*)); (lengths) = malloc((max_dis+1) * sizeof(matrixOptimizationValue)); (lengths)[0] = max_dis; //Packing... int x_minborder = 0; //Borders int y_minborder = 0; int x_maxborder = columns; int y_maxborder = rows; for(int i = 0; i &lt; max_dis; i++){ int elements_size=0; //Unfortunately, making "const" causes really bad syntax... if(x_maxborder-x_minborder &lt;= 1 || y_maxborder-y_minborder &lt;=1){ if(x_maxborder-x_minborder &lt;= 1 &amp;&amp; y_maxborder-y_minborder &lt;=1){ elements_size = 1; } else { elements_size = (x_maxborder-x_minborder == 1) ? y_maxborder-y_minborder : x_maxborder-x_minborder; } } else { elements_size = 2*(x_maxborder-x_minborder + y_maxborder-y_minborder)-4; } matrixOptimizationValue* array = malloc(elements_size * sizeof(int)); (lengths)[i+1]=elements_size; //Initializing coordinates int x = i; //It is certain, that this coordinates will always belong to fields array_i; int y = i; int dir_x = 0; //Direction int dir_y = 1; for(int j = 0; j &lt; elements_size; j++){ array[j] = matrix[y*columns + x]; if(x+dir_x &gt;= x_maxborder || x+dir_x &lt; x_minborder || y+dir_y &gt;= y_maxborder || y+dir_y &lt; y_minborder){ /*Rotate Direction-vector using Algebra x y 0 1 y -1 0 -x */ const int clone = dir_x; dir_x = dir_y; dir_y = -clone; } x += dir_x; y += dir_y; } x_minborder++; y_minborder++; x_maxborder--; y_maxborder--; unstriped_matrix[i]=array; } return unstriped_matrix; } </code></pre> <ol> <li>How would you improve the syntax?</li> <li>Assume high-performance needs, how would you improve the code?</li> </ol>
[]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Fix the bug</h2>\n\n<p>The code allocates memory for the passed <code>arr_lengths</code> but never returns a pointer to the newly allocated memory to the caller. The code currently has this:</p>\n\n<pre><code>int* lengths = *arr_lengths;\n// more code\n(lengths) = malloc((max_dis+1) * sizeof(matrixOptimizationValue));\n</code></pre>\n\n<p>Instead it should be this:</p>\n\n<pre><code>// more code\n*arr_lengths = malloc((max_dis+1) * sizeof(matrixOptimizationValue));\nint* lengths = *arr_lengths;\n</code></pre>\n\n<h2>Provide complete code to reviewers</h2>\n\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. The code comments are good, but a sample program would be better. </p>\n\n<h2>Use the required <code>#include</code>s</h2>\n\n<p>The code uses <code>printf</code> which means that it should <code>#include &lt;stdio.h&gt;</code>. It was not difficult to infer, but it helps reviewers if the code is complete. I had to add these three lines:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;math.h&gt;\n#include &lt;stdlib.h&gt;\n</code></pre>\n\n<h2>Avoid the use of floating point math</h2>\n\n<p>On many computers, floating point mathematics is slower than integer math. For this reason, it's often better to avoid if you can. In this case, it's easily done. We can replace this:</p>\n\n<pre><code>const int max_dis = (columns &gt; rows) ? round((double)(rows)/2) : round((double)(columns)/2);\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code>const int max_dis = (rows &lt; cols ? rows+1 : cols+1) / 2;\n</code></pre>\n\n<p>I also changed the variable <code>columns</code> to <code>cols</code> but that's a personal preference. The longer name is arguably more descriptive.</p>\n\n<h2>Check return values for errors</h2>\n\n<p>The calls to <code>malloc</code> can fail. You must check the return values to make sure they haven't or your program may crash (or worse) when given malformed input or due to low system resources. Rigorous error handling is the difference between mostly working versus bug-free software. You should strive for the latter.</p>\n\n<h2>Choose descriptive names</h2>\n\n<p>Most of the variables and function are well-named and clear in their usage and intent, but I found <code>matrixOptimizationValue</code> both somewhat misleading (it's not a value, but rather a <em>type</em>) and also overly long. I renamed it <code>DataType</code> which is also not a brilliant name, but is, at least, shorter. </p>\n\n<h2>Minimize system calls</h2>\n\n<p>If you're looking for performance, it's often a good idea to avoid system calls, such as for <code>malloc</code>. In this case, I'd suggest changing the code to do only one single allocation. This has the benefits of speed, simplification of error checking and handling, and simplification of cleanup after the call (only one call to <code>free</code> is required).</p>\n\n<h2>Consider separating I/O from the algorithm</h2>\n\n<p>The <code>strip</code> function uses <code>printf</code> to print to the console and then exits via <code>exit</code> if the input is malformed. Consider changing that to return <code>NULL</code> on error and letting the caller figure out what to do.</p>\n\n<h2>Simplify the algorithm</h2>\n\n<p>I found the length of the code and many variables something of an impediment to my understanding of the algorithm. It can be simplified considerably by remembering that the passed variables may also be used directly. In the rewrite I created, pointers are used extensively to simplify the code. It also uses the fact that we can calculate in advance when to change direction.</p>\n\n<h2>Results</h2>\n\n<p>Following all of these suggestions, I created the following rewrite:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stddef.h&gt;\n\ntypedef unsigned short DataType;\n#define DataTypeStr \"u\"\n\nDataType* strip(const DataType* matrix, int rows, int cols, int** arr_lengths){\n if (rows == 0 || cols == 0) {\n return NULL;\n }\n const int max_dis = (rows &lt; cols ? rows+1 : cols+1) / 2;\n // return value is a single vector of the same size as \n // the input, followed by an int value n, which is the \n // count of arrays represented, followed by n ints which\n // represent the lengths of those sub-arrays.\n DataType *retval = malloc(rows * cols * sizeof(DataType*) \n + (1 + max_dis) * sizeof(int));\n if (retval == NULL) { // bail out on allocation error\n return NULL;\n }\n *arr_lengths = (int *)(&amp;retval[rows*cols]);\n DataType *out = retval;\n int *len = *arr_lengths;\n *len++ = max_dis;\n // precalculate down, right, up, left \n enum compass { DOWN, RIGHT, UP, LEFT, DIRCOUNT };\n const int dirs[DIRCOUNT] = { cols, +1, -cols, -1 };\n // because we move and then fetch a value, \n // move one row above matrix\n matrix += dirs[UP];\n\n for (int matnum=0; matnum &lt; max_dis; ++matnum) {\n if (rows &gt; 1 &amp;&amp; cols &gt; 1) {\n *len++ = 2 * (rows + cols - 2);\n } else {\n *len++ = rows + cols - 1; \n }\n // start by moving down\n int dir = DOWN;\n while (rows &amp;&amp; cols &amp;&amp; dir &lt; DIRCOUNT) {\n // down and up\n for (int i = rows; i; --i) {\n matrix += dirs[dir];\n *out++ = *matrix;\n }\n --rows;\n --cols;\n ++dir;\n // right and left\n for (int i = cols; i; --i) {\n matrix += dirs[dir];\n *out++ = *matrix;\n }\n ++dir;\n }\n }\n return retval;\n}\n\nint main(int argc, char *argv[]) {\n if (argc != 3) {\n puts(\"Usage: matstripe rows cols\\n\");\n }\n int rows = atoi(argv[1]);\n int columns = atoi(argv[2]);\n printf(\"Input is a %d x %d matrix\\n\", rows, columns);\n DataType *input = malloc(rows * columns * sizeof(DataType));\n if (input == NULL) {\n puts(\"Out of memory error, quitting program.\");\n return 1;\n }\n int colcounter = columns;\n for (int i = 0; i &lt; rows*columns; ++i) {\n input[i] = i+1;\n printf(\"%3\" DataTypeStr \" \", input[i]);\n if (--colcounter == 0) {\n printf(\"\\n\");\n colcounter = columns;\n }\n }\n int *arr_lengths;\n DataType* answer = strip(input, rows, columns, &amp;arr_lengths);\n free(input);\n puts(\"Output:\");\n if (answer) {\n DataType* mat = answer;\n for (int matnum = 0; matnum &lt; *arr_lengths; ++matnum) {\n printf(\"[%\" DataTypeStr, *mat++);\n for (int i = arr_lengths[matnum+1] - 1; i; --i) {\n printf(\",%\" DataTypeStr, *mat++);\n }\n puts(\"]\");\n }\n free(answer);\n }\n}\n\n</code></pre>\n\n<p>This takes two command line parameters for the nmber of rows and number of columns and constructs a test input matrix of that size filled with cardinal numbers. Here's an example of output.</p>\n\n<pre><code>Input is a 5 x 4 matrix\n 1 2 3 4 \n 5 6 7 8 \n 9 10 11 12 \n 13 14 15 16 \n 17 18 19 20 \nOutput:\n[1,5,9,13,17,18,19,20,16,12,8,4,3,2]\n[6,10,14,15,11,7]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-03-29T19:37:07.797", "Id": "239626", "ParentId": "221553", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T19:40:01.470", "Id": "221553", "Score": "5", "Tags": [ "performance", "c", "matrix" ], "Title": "Striping a matrix concentrically, anticlockwise" }
221553
<p><strong>Task</strong></p> <p>Old mobile phones had the ability to type characters by pressing a number. The letter <code>a</code> could be typed by pressing <code>2</code> once. The letter <code>b</code> could be typed by pressing <code>2</code> twice. </p> <p>Given a sequence of numbers, give all possible letter combinations.</p> <p>For example: The number <code>23</code> could give an output <code>ad, ae, af, bd, be, bf, cd, ce, cf</code></p> <p><a href="https://i.stack.imgur.com/MOlFo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MOlFo.png" alt="numeric keypad with letter equivalents"></a></p> <p>My recursive solution to this problem is given below. </p> <pre><code>def num_to_char(value): if value == 2: return ["a","b","c"] if value == 3: return ["d","e","f"] if value == 4: return ["g","h","i"] if value == 5: return ["j","k","l"] if value == 6: return ["m","n","o"] if value == 7: return ["p","q","r","s"] if value == 8: return ["t","u","v"] if value == 9: return ["w","x","y","z"] def convert_num(number, current_string = ""): if number == []: print(current_string) return get_list = num_to_char(int(number[0])) for character in get_list: current_string += character convert_num(number[1:], current_string) current_string = current_string[:-1] num_to_covert = list("234") convert_num(num_to_covert) </code></pre>
[]
[ { "body": "<p>You're working way too hard:</p>\n\n<ul>\n<li><a href=\"https://docs.python.org/3/library/itertools.html#itertools.product\" rel=\"noreferrer\"><code>itertools.product()</code></a> produces cartesian products.</li>\n<li>You don't need to convert strings to lists; you can iterate over strings directly.</li>\n<li>Lookups are better done using a dictionary than a chain of <code>if</code> statements.</li>\n</ul>\n\n\n\n<pre><code>from itertools import product\n\nKEYPAD = {\n '2': 'abc', '3': 'def',\n '4': 'ghi', '5': 'jkl', '6': 'mno',\n '7': 'pqrs', '8': 'tuv', '9': 'wxyz',\n}\n\ndef convert_num(number):\n letters = [KEYPAD[c] for c in number]\n return [''.join(combo) for combo in product(*letters)]\n\nprint(convert_num('234'))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:48:54.240", "Id": "428445", "Score": "0", "body": "Brilliant. Sadly I actually had no idea what a cartesian product was so thanks for educating me :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:55:20.387", "Id": "428446", "Score": "9", "body": "In general, any time you want to do some kind of fancy iteration in Python, look at `itertools` first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T04:53:29.823", "Id": "428488", "Score": "5", "body": "@200_success And if you don't find it in `itertools`, [`more_itertools`](https://more-itertools.readthedocs.io/en/stable/) might have it instead (although you need to install it separately)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T07:51:19.183", "Id": "428502", "Score": "0", "body": "Beautiful code :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:40:55.730", "Id": "221557", "ParentId": "221554", "Score": "18" } } ]
{ "AcceptedAnswerId": "221557", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:14:22.830", "Id": "221554", "Score": "12", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Print the string equivalents of a phone number" }
221554
<p><a href="https://leetcode.com/problems/last-stone-weight/" rel="noreferrer">https://leetcode.com/problems/last-stone-weight/</a></p> <blockquote> <p>We have a collection of rocks, each rock has a positive integer weight.</p> <p>Each turn, we choose the two heaviest rocks and smash them together. Suppose the stones have weights x and y with x &lt;= y. The result of this smash is:</p> <p>If x == y, both stones are totally destroyed; If x != y, the stone of weight x is totally destroyed, and the stone of weight y has new weight y-x. At the end, there is at most 1 stone left. Return the weight of this stone (or 0 if there are no stones left.)</p> <p>Example 1:</p> <pre><code>Input: [2,7,4,1,8,1] Output: 1 Explanation: We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of last stone. </code></pre> </blockquote> <p>Please review performance.</p> <pre><code>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Heap { /// &lt;summary&gt; /// https://leetcode.com/problems/last-stone-weight/ /// &lt;/summary&gt; [TestClass] public class LastStoneWeightMaxHeap { [TestMethod] public void MaxHeapTest() { BinaryMaxHeap h = new BinaryMaxHeap(6); h.InsertKey(2); h.InsertKey(7); h.InsertKey(4); h.InsertKey(1); h.InsertKey(8); h.InsertKey(1); Assert.AreEqual(8, h.ExtractMax()); Assert.AreEqual(7, h.ExtractMax()); Assert.AreEqual(4, h.ExtractMax()); Assert.AreEqual(2, h.ExtractMax()); Assert.AreEqual(1, h.ExtractMax()); Assert.AreEqual(1, h.ExtractMax()); } [TestMethod] public void LastStoneWeightTest() { int[] input = {2, 7, 4, 1, 8, 1}; Assert.AreEqual(1, LastStoneWeight(input)); } [TestMethod] public void LastStoneWeightCaseTest() { int[] input = { 2,2}; Assert.AreEqual(0, LastStoneWeight(input)); } public int LastStoneWeight(int[] stones) { BinaryMaxHeap h = new BinaryMaxHeap(stones.Length); foreach (var stone in stones) { h.InsertKey(stone); } while (h.Count &gt; 1) { var stone1 = h.ExtractMax(); var stone2 = h.ExtractMax(); if (stone1 == stone2) { continue; } h.InsertKey(stone1 - stone2); } return h.ExtractMax(); } } public class BinaryMaxHeap { private readonly int[] _heapArr; private readonly int _capacity; public uint _heapSize; public BinaryMaxHeap(int capacity) { _capacity = capacity; _heapSize = 0; _heapArr = new int[capacity]; } public void InsertKey(int key) { if (_heapSize == _capacity) { throw new StackOverflowException("overflow can't insert key"); } //insert the new key at the end _heapSize++; uint i = _heapSize - 1; _heapArr[i] = key; //fix the heap as max heap // Fix the max heap property if it is violated while (i != 0 &amp;&amp; _heapArr[Parent(i)] &lt; _heapArr[i]) //bubble is generic specific { Swap(i, Parent(i)); i = Parent(i); } } public int ExtractMax() { if (_heapSize &lt;= 0) { return 0; } if (_heapSize == 1) { _heapSize--; return _heapArr[0]; } // Store the minimum value, and remove it from heap int root = _heapArr[0]; _heapArr[0] = _heapArr[_heapSize - 1]; _heapSize--; Heapify(0); return root; } private void Heapify(uint i) { uint l = Left(i); uint r = Right(i); uint largest = i; if (l &lt; _heapSize &amp;&amp; _heapArr[i]&lt; _heapArr[l]) { largest = l; } if (r &lt; _heapSize &amp;&amp; _heapArr[largest] &lt; _heapArr[r]) { largest = r; } if (largest != i) { Swap(i, largest); Heapify(largest); } } private void Swap(uint key1, uint key2) { int temp = _heapArr[key2]; _heapArr[key2] = _heapArr[key1]; _heapArr[key1] = temp; } private uint Parent(uint i) { return (i - 1) / 2; } private uint Right(uint i) { return 2 * i + 2; } private uint Left(uint i) { return 2 * i + 1; } public int GetMax() { return _heapArr[0]; } public uint Count { get { return _heapSize; } } } } </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code> [TestMethod]\n public void LastStoneWeightTest()\n {\n int[] input = {2, 7, 4, 1, 8, 1};\n Assert.AreEqual(1, LastStoneWeight(input));\n }\n [TestMethod]\n public void LastStoneWeightCaseTest()\n {\n int[] input = { 2,2};\n Assert.AreEqual(0, LastStoneWeight(input));\n }\n</code></pre>\n</blockquote>\n\n<p>These tests could be combined using <code>DataTestMethod</code> and <code>DataRow</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> BinaryMaxHeap h = new BinaryMaxHeap(stones.Length);\n foreach (var stone in stones)\n {\n h.InsertKey(stone);\n }\n</code></pre>\n</blockquote>\n\n<p>This is inefficient. Inserting like this takes <span class=\"math-container\">\\$O(n \\lg n)\\$</span> time, whereas organising a randomly ordered array so that it satisfies the heap invariant can be done in <span class=\"math-container\">\\$O(n)\\$</span> time.</p>\n\n<p>Note that this operation on the entire array is commonly referred to as <code>heapify</code>, not the restoring of the invariant for a single insertion or deletion. I would rename <code>Heapify</code> to <code>DownHeap</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private readonly int[] _heapArr;\n private readonly int _capacity;\n</code></pre>\n</blockquote>\n\n<p>What is the purpose of <code>_capacity</code>? Would it not be better to eliminate it in favour of <code>_heapArr.Length</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> _heapSize++;\n uint i = _heapSize - 1;\n _heapArr[i] = key;\n</code></pre>\n</blockquote>\n\n<p>This is a matter of opinion, but I think that</p>\n\n<pre><code> _heapArr[_heapSize++] = key;\n</code></pre>\n\n<p>is perfectly readable, and certainly I doubt many people would complain about</p>\n\n<pre><code> _heapArr[_heapSize] = key;\n _heapSize++;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> //fix the heap as max heap\n // Fix the max heap property if it is violated\n while (i != 0 &amp;&amp; _heapArr[Parent(i)] &lt; _heapArr[i]) //bubble is generic specific\n {\n Swap(i, Parent(i));\n i = Parent(i);\n }\n</code></pre>\n</blockquote>\n\n<p>I don't think the double-comment before the loop is necessary. I don't understand the third comment.</p>\n\n<p>Why is moving down the heap pulled out as a method, but not moving up the heap?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public int ExtractMax()\n {\n if (_heapSize &lt;= 0)\n {\n return 0;\n }\n</code></pre>\n</blockquote>\n\n<p>Not an exception?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (_heapSize == 1)\n {\n _heapSize--;\n return _heapArr[0];\n }\n\n // Store the minimum value, and remove it from heap\n int root = _heapArr[0];\n _heapArr[0] = _heapArr[_heapSize - 1];\n _heapSize--;\n Heapify(0);\n return root;\n</code></pre>\n</blockquote>\n\n<p>I would be inclined to combine the two cases:</p>\n\n<pre><code> int root = _heapArr[0];\n _heapSize--;\n if (_heapSize &gt; 0)\n {\n _heapArr[0] = _heapArr[_heapSize];\n Heapify(0);\n }\n return root;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> private void Heapify(uint i)\n {\n ...\n if (largest != i)\n {\n Swap(i, largest);\n Heapify(largest);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>Although .Net does support tail recursion, I believe it's better supported in F# than C#. It might be worth rewriting this to be iterative instead of recursive.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private uint Parent(uint i)\n {\n return (i - 1) / 2;\n }\n</code></pre>\n</blockquote>\n\n<p>As a matter of style here I would prefer to use <code>=&gt;</code>, but this is very subjective.</p>\n\n<hr>\n\n<p>In terms of performance, the only obvious improvement is the way that the heap is initialised, and that's not actually affecting the overall asymptotic performance. There may be a way to do better than <span class=\"math-container\">\\$O(n \\lg n)\\$</span> time overall, but it certainly isn't easy to see. A more complicated heap might give slight improvements to the average running time (e.g. by exploiting the fact that after the initial insertions all insertions will be in descending order, so you can bucket on the most significant bit), but KISS and YAGNI.</p>\n\n<p>I commend you for including the test framework. It would be good to have some more tests: e.g. in my experience it's easy to have subtle bugs in heaps, so I now try to test them by brute force over all permutations of a small number of insertions and removals. For the <code>LastStoneWeight</code> I would consider writing a test case which uses a seeded random number generator to produce a thousand test cases, validating against a trivial but slow implementation such as proposed in Justin's answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T07:47:48.940", "Id": "428501", "Score": "0", "body": "But doesn't Leetcode just have 70 possible test cases (at least for this one)? But honestly, I'm curious. Could you include in your answer or comment on how to get a thousand test cases?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T08:32:39.270", "Id": "428509", "Score": "1", "body": "@Justin, I don't know how many test cases they have, or whether they publish them. My experience in general with this kind of site is that most of the test cases are hidden to prevent people writing solutions specific to the test cases." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T07:37:48.090", "Id": "221577", "ParentId": "221559", "Score": "3" } } ]
{ "AcceptedAnswerId": "221577", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:47:28.130", "Id": "221559", "Score": "7", "Tags": [ "c#", "programming-challenge", "heap" ], "Title": "LeetCode: last stone weight C#" }
221559
<p>I am working on a basic blog application in <strong>Codeigniter 3.1.8</strong> and <strong>Bootstrap 4</strong>.</p> <p>The application allows Registration (as an author), Login, adding Categories and Posts.</p> <p>I have created an installation process for the application: after creating a database and providing its credentials to the <code>application/config/database.php</code> file, you can run the <code>Install</code> controller which will create all the necessary tables:</p> <pre><code>class Install extends CI_Controller { public function __construct() { parent::__construct(); } public function index(){ // Create all the database tables if there are none // by redirecting to the Migrations controller $tables = $this-&gt;db-&gt;list_tables(); if (count($tables) == 0) { redirect('migrate'); } else { redirect('/'); } } } </code></pre> <p>After that, you can register as an <strong>author</strong>. Being the first registered author, you are also an admin, meaning that your author account <em>does not require activation</em> (and the value for the <code>is_admin</code> column has a value of <code>1</code> in the database record for you). </p> <p>All the future authors will need their accounts <em>activated by you</em> in order to publish articles (posts).</p> <p>It is a rather ambitious project, although I did not start it with great plans in mind. I just wanted to learn Codeigniter 3. You can see it on my <strong><a href="https://github.com/Ajax30/lightblog" rel="nofollow noreferrer">GitHub</a></strong> account. </p> <p>There are a few possible issues: </p> <ol> <li>The application does <em>not</em> use HMVC, but "classic" MVC.</li> <li>It does not have a clear separation between its <em>front</em> and its <em>back</em> (admin)</li> <li>I want to add a <strong>theming</strong> feature and I kinda got stuck with it; I don't know what approach to use.</li> <li>My controllers may be a over-coded.</li> </ol> <p>Here is the <code>Posts</code> controller:</p> <pre><code> class Posts extends CI_Controller { public function __construct() { parent::__construct(); } private function _initPagination($path, $totalRows, $query_string_segment = 'page') { //load and configure pagination $this-&gt;load-&gt;library('pagination'); $config['base_url'] = base_url($path); $config['query_string_segment'] = $query_string_segment; $config['enable_query_strings'] =TRUE; $config['reuse_query_string'] =TRUE; $config['total_rows'] = $totalRows; $config['per_page'] = 12; if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] &lt; 1) { $_GET[$config['query_string_segment']] = 1; } $this-&gt;pagination-&gt;initialize($config); $limit = $config['per_page']; $offset = ($this-&gt;input-&gt;get($config['query_string_segment']) - 1) * $limit; return ['limit' =&gt; $limit, 'offset' =&gt; $offset]; } public function index() { //call initialization method $config = $this-&gt;_initPagination("/", $this-&gt;Posts_model-&gt;get_num_rows()); $data = $this-&gt;Static_model-&gt;get_static_data(); $data['pages'] = $this-&gt;Pages_model-&gt;get_pages(); $data['categories'] = $this-&gt;Categories_model-&gt;get_categories(); //use limit and offset returned by _initPaginator method $data['posts'] = $this-&gt;Posts_model-&gt;get_posts($config['limit'], $config['offset']); $this-&gt;load-&gt;view('partials/header', $data); $this-&gt;load-&gt;view('posts'); $this-&gt;load-&gt;view('partials/footer'); } public function search() { // Force validation since the form's method is GET $this-&gt;form_validation-&gt;set_data($this-&gt;input-&gt;get()); $this-&gt;form_validation-&gt;set_rules('search', 'Search term', 'required|trim|min_length[3]',array('min_length' =&gt; 'The Search term must be at least 3 characters long.')); $this-&gt;form_validation-&gt;set_error_delimiters('&lt;p class = "error search-error"&gt;', '&lt;/p&gt; '); // If search fails if ($this-&gt;form_validation-&gt;run() === FALSE) { return $this-&gt;index(); } else { $expression = $this-&gt;input-&gt;get('search'); $posts_count = $this-&gt;Posts_model-&gt;search_count($expression); $query_string_segment = 'page'; $config = $this-&gt;_initPagination("/posts/search", $posts_count, $query_string_segment); $data = $this-&gt;Static_model-&gt;get_static_data(); $data['pages'] = $this-&gt;Pages_model-&gt;get_pages(); $data['categories'] = $this-&gt;Categories_model-&gt;get_categories(); //use limit and offset returned by _initPaginator method $data['posts'] = $this-&gt;Posts_model-&gt;search($expression, $config['limit'], $config['offset']); $data['expression'] = $expression; $data['posts_count'] = $posts_count; $this-&gt;load-&gt;view('partials/header', $data); $this-&gt;load-&gt;view('search'); $this-&gt;load-&gt;view('partials/footer'); } } public function byauthor($authorid){ $data = $this-&gt;Static_model-&gt;get_static_data(); $data['pages'] = $this-&gt;Pages_model-&gt;get_pages(); $data['categories'] = $this-&gt;Categories_model-&gt;get_categories(); $data['posts'] = $this-&gt;Posts_model-&gt;get_posts_by_author($authorid); $data['posts_count'] = $this-&gt;Posts_model-&gt;posts_by_author_count($authorid); $data['posts_author'] = $this-&gt;Posts_model-&gt;posts_author($authorid); $this-&gt;load-&gt;view('partials/header', $data); $this-&gt;load-&gt;view('posts_by_author'); $this-&gt;load-&gt;view('partials/footer'); } public function post($slug) { $data = $this-&gt;Static_model-&gt;get_static_data(); $data['pages'] = $this-&gt;Pages_model-&gt;get_pages(); $data['categories'] = $this-&gt;Categories_model-&gt;get_categories(); $data['posts'] = $this-&gt;Posts_model-&gt;sidebar_posts($limit=5, $offset=0); $data['post'] = $this-&gt;Posts_model-&gt;get_post($slug); if ($data['categories']) { foreach ($data['categories'] as &amp;$category) { $category-&gt;posts_count = $this-&gt;Posts_model-&gt;count_posts_in_category($category-&gt;id); } } if (!empty($data['post'])) { // Overwrite the default tagline with the post title $data['tagline'] = $data['post']-&gt;title; // Get post comments $post_id = $data['post']-&gt;id; $data['comments'] = $this-&gt;Comments_model-&gt;get_comments($post_id); $this-&gt;load-&gt;view('partials/header', $data); $this-&gt;load-&gt;view('post'); } else { $data['tagline'] = "Page not found"; $this-&gt;load-&gt;view('partials/header', $data); $this-&gt;load-&gt;view('404'); } $this-&gt;load-&gt;view('partials/footer'); } public function create() { // Only logged in users can create posts if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } $data = $this-&gt;Static_model-&gt;get_static_data(); $data['pages'] = $this-&gt;Pages_model-&gt;get_pages(); $data['tagline'] = "Add New Post"; $data['categories'] = $this-&gt;Categories_model-&gt;get_categories(); $data['posts'] = $this-&gt;Posts_model-&gt;sidebar_posts($limit=5, $offset=0); if ($data['categories']) { foreach ($data['categories'] as &amp;$category) { $category-&gt;posts_count = $this-&gt;Posts_model-&gt;count_posts_in_category($category-&gt;id); } } $this-&gt;form_validation-&gt;set_rules('title', 'Title', 'required'); $this-&gt;form_validation-&gt;set_rules('desc', 'Short description', 'required'); $this-&gt;form_validation-&gt;set_rules('body', 'Body', 'required'); $this-&gt;form_validation-&gt;set_error_delimiters('&lt;p class="error-message"&gt;', '&lt;/p&gt;'); if($this-&gt;form_validation-&gt;run() === FALSE){ $this-&gt;load-&gt;view('partials/header', $data); $this-&gt;load-&gt;view('create-post'); $this-&gt;load-&gt;view('partials/footer'); } else { // Create slug (from title) $slug = url_title($this-&gt;input-&gt;post('title'), 'dash', TRUE); $slugcount = $this-&gt;Posts_model-&gt;slug_count($slug); if ($slugcount &gt; 0) { $slug = $slug."-".$slugcount; } // Upload image $config['upload_path'] = './assets/img/posts'; $config['allowed_types'] = 'jpg|png'; $config['max_size'] = '2048'; $this-&gt;load-&gt;library('upload', $config); if(!$this-&gt;upload-&gt;do_upload()){ $errors = array('error' =&gt; $this-&gt;upload-&gt;display_errors()); $post_image = 'default.jpg'; } else { $data = array('upload_data' =&gt; $this-&gt;upload-&gt;data()); $post_image = $_FILES['userfile']['name']; } $this-&gt;Posts_model-&gt;create_post($post_image, $slug); $this-&gt;session-&gt;set_flashdata('post_created', 'Your post has been created'); redirect('/'); } } public function edit($id) { // Only logged in users can edit posts if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } $data = $this-&gt;Static_model-&gt;get_static_data(); $data['pages'] = $this-&gt;Pages_model-&gt;get_pages(); $data['categories'] = $this-&gt;Categories_model-&gt;get_categories(); $data['posts'] = $this-&gt;Posts_model-&gt;sidebar_posts($limit=5, $offset=0); $data['post'] = $this-&gt;Posts_model-&gt;get_post($id); if ($this-&gt;session-&gt;userdata('user_id') == $data['post']-&gt;author_id) { $data['tagline'] = 'Edit the post "' . $data['post']-&gt;title . '"'; $this-&gt;load-&gt;view('partials/header', $data); $this-&gt;load-&gt;view('edit-post'); $this-&gt;load-&gt;view('partials/footer'); } else { /* If the current user is not the author of the post do not alow edit */ redirect('/' . $id); } } public function update() { // Form data validation rules $this-&gt;form_validation-&gt;set_rules('title', 'Title', 'required', array('required' =&gt; 'The %s field can not be empty')); $this-&gt;form_validation-&gt;set_rules('desc', 'Short description', 'required', array('required' =&gt; 'The %s field can not be empty')); $this-&gt;form_validation-&gt;set_rules('body', 'Body', 'required', array('required' =&gt; 'The %s field can not be empty')); $this-&gt;form_validation-&gt;set_error_delimiters('&lt;p class="error-message"&gt;', '&lt;/p&gt;'); $id = $this-&gt;input-&gt;post('id'); // Update slug (from title) if (!empty($this-&gt;input-&gt;post('title'))) { $slug = url_title($this-&gt;input-&gt;post('title'), 'dash', TRUE); $slugcount = $this-&gt;Posts_model-&gt;slug_count($slug); if ($slugcount &gt; 0) { $slug = $slug."-".$slugcount; } } else { $slug = $this-&gt;input-&gt;post('slug'); } // Upload image $config['upload_path'] = './assets/img/posts'; $config['allowed_types'] = 'jpg|png'; $config['max_size'] = '2048'; $this-&gt;load-&gt;library('upload', $config); if ( isset($_FILES['userfile']['name']) &amp;&amp; $_FILES['userfile']['name'] != null ) { // Use name field in do_upload method if (!$this-&gt;upload-&gt;do_upload('userfile')) { $errors = array('error' =&gt; $this-&gt;upload-&gt;display_errors()); } else { $data = $this-&gt;upload-&gt;data(); $post_image = $data[ 'raw_name'].$data[ 'file_ext']; } } else { $post_image = $this-&gt;input-&gt;post('postimage'); } if ($this-&gt;form_validation-&gt;run()) { $this-&gt;Posts_model-&gt;update_post($id, $post_image, $slug); $this-&gt;session-&gt;set_flashdata('post_updated', 'Your post has been updated'); redirect('/' . $slug); } else { $this-&gt;form_validation-&gt;run(); $this-&gt;session-&gt;set_flashdata('errors', validation_errors()); redirect('/posts/edit/' . $slug); } } public function delete($slug) { // Only logged in users can delete posts if (!$this-&gt;session-&gt;userdata('is_logged_in')) { redirect('login'); } $data['post'] = $this-&gt;Posts_model-&gt;get_post($slug); if ($this-&gt;session-&gt;userdata('user_id') == $data['post']-&gt;author_id) { $this-&gt;Posts_model-&gt;delete_post($slug); $this-&gt;session-&gt;set_flashdata('post_deleted', 'The post has been deleted'); redirect('/'); } else { /* If the current user is not the author of the post do not alow delete */ redirect('/' . $slug); } } } </code></pre> <p>Please help me with useful feedback and suggestions.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T21:19:49.063", "Id": "428454", "Score": "3", "body": "I'm not sure that there is enough reviewable code posted within your question. You can't just link to github and say: read more there (that content is not static)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T22:47:34.363", "Id": "428469", "Score": "0", "body": "@mickmackusa I have added more code. I can't add *all* the code though. For that there is the *GitHub* repo." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T22:54:58.513", "Id": "428470", "Score": "2", "body": "Of course not. We aren't meant to review an entire repository -- that would be Too Broad." } ]
[ { "body": "<h2>Foreword</h2>\n\n<p>I haven't used CodeIgniter in the past so I am not as well-versed with the idiomatic ways it is used but I have used similar frameworks like Laravel.</p>\n\n<p>I did look at the code in the github repository for references (e.g. the routes) but am mostly planning to review the code embedded directly in the post.</p>\n\n<h2>General Feedback</h2>\n\n<p>I see a fair amount of repeated code. It is wise to abstract out such repeated blocks into methods (make them private if you wish) and call those methods when appropriate. That way if a change needs to happen to each place, it can be done in one spot instead of each occurrence. </p>\n\n<p>In <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">this presentation about cleaning up code</a> Rafael Dohms talks about limiting the indentation level to one per method and avoiding the <code>else</code> keyword. (<a href=\"https://www.slideshare.net/rdohms/bettercode-phpbenelux212alternate/11-OC_1Only_one_indentation_level\" rel=\"nofollow noreferrer\">see the slides here</a>).</p>\n\n<p>It is wise to return early - which your code does in a few places - like in <code>edit()</code> and <code>delete()</code> when the user isn't logged in. But there are other places this could be done. See below for more details on this.</p>\n\n<h2>Specific Feedback</h2>\n\n<h3>Overriding Constructors without side-effects</h3>\n\n<p>I see both <code>Install</code> and <code>Posts</code> classes have a constructor that merely calls the parent method: </p>\n\n<blockquote>\n<pre><code>public function __construct()\n{\n parent::__construct();\n}\n</code></pre>\n</blockquote>\n\n<p>If nothing else happens in that method, there isn't really a point to override it.</p>\n\n<p>The <a href=\"https://www.codeigniter.com/user_guide/general/controllers.html?highlight=controller#class-constructors\" rel=\"nofollow noreferrer\">CodeIgniter Documentation for Controller has a section about _Class Constructors</a> which states:</p>\n\n<blockquote>\n <p>If you intend to use a constructor in any of your Controllers, you MUST place the following line of code in it:</p>\n\n<pre><code>parent::__construct();\n</code></pre>\n</blockquote>\n\n<p>That documentation <em>could</em> be updated to state that it only needs to be overridden if code is added beyond what the parent constructor does. While it may be very unlikely that the signature of the base constructor will never change, it is possible. If that did happen (which would likely lead to a major version release) all code using it would need to be updated. Without overriding it then it wouldn't need to be updated.</p>\n\n<hr>\n\n<h3>Else blocks</h3>\n\n<p>In the <code>search()</code> method there is a conditional block with a <code>return</code> statement, and then an <code>else</code> block:</p>\n\n<blockquote>\n<pre><code>// If search fails\n if ($this-&gt;form_validation-&gt;run() === FALSE) {\n return $this-&gt;index();\n } else {\n</code></pre>\n</blockquote>\n\n<p>There isn't really any need to use the <code>else</code> here.</p>\n\n<p>The same is true in the method <code>Install::index()</code> there is this logic:</p>\n\n<blockquote>\n<pre><code>if (count($tables) == 0) {\n redirect('migrate');\n } else {\n redirect('/');\n }\n</code></pre>\n</blockquote>\n\n<p>Since <code>redirect()</code> terminates the script, it could be treated as an early return (just as <code>Posts</code> methods <code>edit()</code>, <code>create()</code> and <code>delete()</code> also have early returns with <code>redirect()</code>). Thus the <code>else</code> is not needed - the <code>redirect('/')</code> can just be the last statement in the method, after the conditional block.</p>\n\n<p>A ternary operator could also be used to shorten that block to a single line:</p>\n\n<pre><code>redirect( count($tables) == 0 ? 'migrate' : '/' );\n</code></pre>\n\n<hr>\n\n<h3>Repeated Code</h3>\n\n<p>Both the methods <code>post()</code> and <code>create()</code> have the following lines. Those could be abstracted out to a separate method and called in both places.</p>\n\n<blockquote>\n<pre><code>$data = $this-&gt;Static_model-&gt;get_static_data();\n$data['pages'] = $this-&gt;Pages_model-&gt;get_pages();\n\n$data['categories'] = $this-&gt;Categories_model-&gt;get_categories();\n$data['posts'] = $this-&gt;Posts_model-&gt;sidebar_posts($limit=5, $offset=0);\n\nif ($data['categories']) {\n foreach ($data['categories'] as &amp;$category) {\n $category-&gt;posts_count = $this-&gt;Posts_model-&gt;count_posts_in_category($category-&gt;id);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Those could also be abstracted into a separate method to get the data object and called in both places. Actually, I see those first four lines mentioned above are also present in the <code>edit()</code> method so the block to set the counts on each category could be run if categories is set and optionally when a parameter is passed to the method.</p>\n\n<hr>\n\n<h3>Calls to <code>Posts_model::sidebar_posts()</code></h3>\n\n<p>Also on this line in <code>create()</code>, <code>post()</code> and <code>edit()</code>:</p>\n\n<blockquote>\n<pre><code>$data['posts'] = $this-&gt;Posts_model-&gt;sidebar_posts($limit=5, $offset=0);\n</code></pre>\n</blockquote>\n\n<p>it is likely doing more than you think- <code>$limit</code> is assigned the value 5 and <code>$offset</code> is assigned the value 0. There isn't really anything wrong with this but if those methods created a variable with either of those names before this line then it would be over-written. Perhaps you copied the method signature from <a href=\"https://github.com/Ajax30/lightblog/blob/0d199ffa4108f8a00c7a3ecaa9ce181dd7f681e4/application/models/Posts_model.php#L38\" rel=\"nofollow noreferrer\"><code>Posts_model::sidebar_posts()</code></a> and added the assignment; Instead just pass the values without the assignment:</p>\n\n<pre><code>$data['posts'] = $this-&gt;Posts_model-&gt;sidebar_posts(5, 0);\n</code></pre>\n\n<hr>\n\n<h3>updating page parameter in $_GET</h3>\n\n<p>The <code>_initPagination()</code> method has this block:</p>\n\n<blockquote>\n<pre><code>if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] &lt; 1) {\n $_GET[$config['query_string_segment']] = 1;\n}\n</code></pre>\n</blockquote>\n\n<p>And given that </p>\n\n<blockquote>\n<pre><code> $config['query_string_segment'] = $query_string_segment;\n</code></pre>\n</blockquote>\n\n<p>and <code>$query_string_segment</code> isn't changed between there, it may be slightly simpler to read if the block above is changed to:</p>\n\n<pre><code>if (!isset($_GET[$query_string_segment]) || $_GET[$query_string_segment] &lt; 1) {\n $_GET[$query_string_segment] = 1;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T18:53:30.137", "Id": "221876", "ParentId": "221560", "Score": "2" } } ]
{ "AcceptedAnswerId": "221876", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T20:54:05.520", "Id": "221560", "Score": "4", "Tags": [ "php", "mvc", "controller", "codeigniter" ], "Title": "Codeigniter 3 micro-blogging application" }
221560
<p>I have a shared data object with writer threads and reader threads. Number of threads can read from the shared data at the same time (in the code <code>get</code>method), and writing (in my code <code>move</code> method) can be executed only by one thread at a time</p> <p>I also have to make sure that while writing updates, only the single writer thread can access the shared data.</p> <p>I'm new to java and not an expert in multithreading in general and wanted to get some comments and improvment ideas for my implementation:</p> <p>SharedData:</p> <pre><code>public class SharedData { private int x; private int y; public SharedData(int x, int y){ this.x= x; this.y = y; } public SharedData get(){ return (new SharedData(x, y)); } public void move (int dx, int dy){ x = x+dx; y = y+dy; } @Override public String toString() { return x + " " + y; } } </code></pre> <p>SharedDataC (Need to take care of the sync demands in this class): </p> <pre><code>import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class SharedDataC extends SharedData { private final ReentrantLock _lock = new ReentrantLock(); private final Condition _canRead = _lock.newCondition(); private final Condition _canWrite = _lock.newCondition(); private final AtomicInteger _count = new AtomicInteger(0); public SharedDataC(int x, int y) { super(x, y); } @Override public void move(int x, int y) { // Locking _lock.lock(); try { // Waiting for signal that there are no readers if (!_count.compareAndSet(0, 0)) { _canWrite.await(); } super.move(x, y); // Signals readers _canRead.signalAll(); } catch (InterruptedException ex) { ex.printStackTrace(); } finally { // Unlocking _lock.unlock(); } } public SharedData get() { // Waiting while a writer wants to update while (_lock.isLocked()) { try { _canRead.await(); } catch (InterruptedException ex) { ex.printStackTrace(); } } // Atomically incrementing readers count _count.incrementAndGet(); SharedData sd = super.get(); int a = _count.decrementAndGet(); if (a == 0 &amp;&amp; _lock.isLocked()) { _canWrite.signalAll(); } return sd; } } </code></pre> <p>SharedDataC (Need to take care of the sync demands in this class) <strong>Added this alternative implementation after Thomas comment</strong>: </p> <pre><code>import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class SharedDataC extends SharedData { private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private final Lock r = rwl.readLock(); private final Lock w = rwl.writeLock(); public SharedDataC(int x, int y) { super(x, y); } @Override public void move(int x, int y) { w.lock(); try { super.move(x, y); } finally { w.unlock(); } } @Override public SharedData get() { r.lock(); try { return super.get(); } finally { r.unlock(); } } } </code></pre> <p>Reader:</p> <pre><code>public class ReaderThread extends Thread { private final SharedData _shData; public ReaderThread(SharedData shData){ super(); _shData = shData; } @Override public void run() { for (int i = 0; i &lt; 10; i++){ SharedData sd = _shData.get(); System.out.println("Consumer " + getName() + ": " + sd); try { sleep((long)(Math.random() * 2000)); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } </code></pre> <p>Writer:</p> <pre><code>public class WriterThread extends Thread { private SharedData _shData; public WriterThread(SharedData shData){ super(); _shData = shData; } @Override public void run() { for (int i=0; i &lt; 10; i++){ _shData.move((int)(Math.random()*100), (int)(Math.random()*100)); System.out.println("Producer " + getName() + ": " + _shData); try { sleep((long)(Math.random() * 2000)); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } </code></pre> <p>Tester class:</p> <pre><code> public class Tester { public static void main(String[] args){ SharedDataC shDataC = new SharedDataC(0,0); WriterThread thpC1 = new WriterThread(shDataC); WriterThread thpC2 = new WriterThread(shDataC); WriterThread thpC3 = new WriterThread(shDataC); WriterThread thpC4 = new WriterThread(shDataC); ReaderThread thcC1 = new ReaderThread(shDataC); ReaderThread thcC2 = new ReaderThread(shDataC); ReaderThread thcC3 = new ReaderThread(shDataC); ReaderThread thcC4 = new ReaderThread(shDataC); thpC1.start(); thpC2.start(); thpC3.start(); thpC4.start(); thcC1.start(); thcC2.start(); thcC3.start(); thcC4.start(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T22:21:02.080", "Id": "428461", "Score": "1", "body": "Why implement that thing yourself and not use [ReadWriteLock](https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReadWriteLock.html)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T22:39:21.437", "Id": "428465", "Score": "1", "body": "The test does not check the result. Also, the sleeps are quite long for testing. To get data races, I'd test at full speed (100% CPU) with no sleeps and many more loop iterations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T22:41:21.047", "Id": "428467", "Score": "0", "body": "To me it seems that you could have reader starvation in your implementation, since the `_lock` has precedence." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T22:42:08.650", "Id": "428468", "Score": "1", "body": "@ThomasWeller I added an alternative implementation with the class you suggested. Would still appreciate comments on both, for learning purposes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T09:30:08.320", "Id": "428514", "Score": "0", "body": "This is horribly broken on several levels, for one you are not allowed to call await without holding the associated lock. When you do hold it you should call it in a loop. There is a race between reader and writer acquiring the lock." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:32:14.660", "Id": "428580", "Score": "1", "body": "@ratchetfreak I have read this code before. I believe many parts are copied from ArrayBlockingQueue;" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-02T22:17:11.207", "Id": "221563", "Score": "4", "Tags": [ "java", "multithreading", "comparative-review", "reinventing-the-wheel", "producer-consumer" ], "Title": "Java multithreading many readers one writer implementations" }
221563
<p><strong>This is a follow up question of <a href="https://codereview.stackexchange.com/questions/221091/classic-tetris-implementation-for-windows-console">Classic Tetris implementation for Windows console - Initial Version Review</a></strong></p> <p><em>Since the changes this small project of mine suffered after applying all the excellent advice given to me in previous thread were substantial, it seemed to be a sensible idea to open it for review once more and count on the community to decide if I have executed the proposed changes in the best possible way.</em></p> <p>Now, in my first question, I presented the following point as one of the main doubts I had while coding:</p> <ul> <li>Overall code logistics. What would be the best (advised) way of interrelating my class objects? Should I pass references around as member variables (the way I did with my Tetris class, it has pointers to screenBuffer and playingField objects) and make most of the game functionality internal to my objects or make them as independent of one another as possible, bringing all together in my program's main function by accessing each object when needed (essentially pulling some of the programs functionality out of my objects)?</li> </ul> <p>Addressing the given point, I got the following piece of advice:</p> <blockquote> <p>...make them separate. That way, because the objects don't overlap, you have more control at the upper level to do with them what you want. If you want to change how these objects interact, you can change the upper level without messing with the internal representation. If you need a new way for them to interact, you can just make a new method, and then you can keep the old way too, if you want, much easier.</p> </blockquote> <p>So, After pulling all code responsible for interrelating objects out of my classes, I was left with four simple classes with no overlap (each of which in its own separate file) and seven or so helper methods responsible for bringing the objects together into the main execution flow of the program. I bundled all these helper methods into a single utility class (this class has internal references for each relevant object), so to make them available under the same namespace, it seemed to be the most organised thing to do.</p> <p>Finally, my code:</p> <p><strong>Main.cpp:</strong></p> <pre><code>#include &lt;iostream&gt; using namespace std; #include &lt;Windows.h&gt; #include &lt;thread&gt; #include "utils.h" #include "tetris.h" #include "playingField.h" #include "screenBuffer.h" int main(void) { Tetris tetrisGame = Tetris(); Screen screenBuffer = Screen(80, 30); PlayingField playingField = PlayingField(); Utils gameUtils = Utils(playingField, tetrisGame, screenBuffer); while (!tetrisGame.gameOver) { // Timing this_thread::sleep_for(50ms); tetrisGame.speedCounter++; tetrisGame.forceDown = (tetrisGame.speed == tetrisGame.speedCounter); // Input gameUtils.processInput(tetrisGame.fallingPiece()); // Logic gameUtils.computNextState(); //Render Output gameUtils.draw(tetrisGame.fallingPiece()); } CloseHandle(screenBuffer.hConsole); cout &lt;&lt; "Game Over! Score:" &lt;&lt; tetrisGame.score &lt;&lt; endl; system("pause"); return 0; } </code></pre> <p><strong>Tetromino.h</strong></p> <pre><code>#pragma once #include &lt;iostream&gt; // Tetromino Class //============================================================== class Tetromino { public: int y; int x; int rotation; const std::wstring layout; Tetromino(std::wstring layout) : layout(layout), y(0), x(6), rotation(0) {} }; </code></pre> <p><strong>PlayingField.h</strong></p> <pre><code>#pragma once // Playing Field Class //============================================================== class PlayingField { public: const int fieldWidth; const int fieldHeight; unsigned char *pField; PlayingField() : fieldWidth(12), fieldHeight(18), pField(nullptr) { // Creating play field buffer pField = new unsigned char[fieldHeight * fieldWidth]; for (int x = 0; x &lt; fieldWidth; x++) for (int y = 0; y &lt; fieldHeight; y++) // 0 characters are spaces and 9 are borders pField[y * fieldWidth + x] = (x == 0 || x == fieldWidth - 1 || y == fieldHeight - 1) ? 9 : 0; } }; </code></pre> <p><strong>ScreenBuffer.h</strong></p> <pre><code>#pragma once #include &lt;Windows.h&gt; // Screen buffer class //============================================================== class Screen { public: const int screenWidth; const int screenHeight; wchar_t *screen; HANDLE hConsole; DWORD dwBytesWritten; Screen(const int screenWidth, const int screenHeight) : screenWidth(screenWidth), screenHeight(screenHeight) { screen = new wchar_t[screenWidth * screenHeight]; for (int i = 0; i &lt; screenWidth * screenHeight; i++) screen[i] = L' '; hConsole = CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL); SetConsoleActiveScreenBuffer(hConsole); dwBytesWritten = 0; } }; </code></pre> <p><strong>Tetris.h</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include "tetromino.h" // Game class //============================================================== class Tetris { public: Tetris(); int score; int lines; int speed; bool key[4]; bool gameOver; int nextPiece; bool forceDown; bool rotateHold; int pieceCount; int speedCounter; int currentPiece; std::vector&lt;int&gt; fullLines; std::vector&lt;Tetromino&gt;tetromino; Tetromino&amp; fallingPiece(); Tetromino&amp; nextFallingPiece(); void setUpNextPiece(); }; </code></pre> <p><strong>Tetris.cpp</strong></p> <pre><code>#include &lt;vector&gt; #include "Tetris.h" #include "Tetromino.h" Tetris::Tetris() : speed(20), score(0), lines(0), pieceCount(0), speedCounter(0), gameOver(false), forceDown(false), nextPiece(rand() % 7), currentPiece(rand() % 7), rotateHold(true) { // Generate pieces tetromino.push_back(Tetromino(L"..X...X...X...X.")); tetromino.push_back(Tetromino(L"..X..XX...X.....")); tetromino.push_back(Tetromino(L".....XX..XX.....")); tetromino.push_back(Tetromino(L"..X..XX..X......")); tetromino.push_back(Tetromino(L".X...XX...X.....")); tetromino.push_back(Tetromino(L".X...X...XX.....")); tetromino.push_back(Tetromino(L"..X...X..XX.....")); } void Tetris::setUpNextPiece() { currentPiece = nextPiece; nextPiece = rand() % 7; fallingPiece().rotation = 0; fallingPiece().y = 0; fallingPiece().x = 6; score += 25; } Tetromino&amp; Tetris::fallingPiece() { return tetromino[currentPiece]; } Tetromino&amp; Tetris::nextFallingPiece() { return tetromino[nextPiece]; } </code></pre> <p><strong>Utils.h</strong></p> <pre><code>#pragma once #include "tetris.h" #include "tetromino.h" #include "playingField.h" #include "screenBuffer.h" // Utils //============================================================== class Utils { public: void computNextState(); Utils(PlayingField&amp;, Tetris&amp;, Screen&amp;); void draw(const Tetromino&amp; tetromino); void processInput(Tetromino&amp; tetromino); void checkLines(const Tetromino&amp; tetromino); void lockPieceOnField(const Tetromino&amp; tetromino); int rotate(const int x, const int y, const int rotation); bool doesPieceFit(const Tetromino&amp; tetromino, const int rotation, const int x, const int y); private: Tetris&amp; game; Screen&amp; screenBuffer; PlayingField&amp; playingField; }; </code></pre> <p><strong>Utils.cpp</strong></p> <pre><code>#include &lt;iostream&gt; using namespace std; #include "Utils.h" #include &lt;thread&gt; #define XPADDING 34 #define YPADDING 5 Utils::Utils(PlayingField&amp; playingField, Tetris&amp; game, Screen&amp; screenBuffer) : playingField(playingField), game(game), screenBuffer(screenBuffer) {} void Utils::computNextState() { if (game.forceDown) { if (doesPieceFit(game.fallingPiece(), game.fallingPiece().rotation, game.fallingPiece().x, game.fallingPiece().y + 1)) { game.fallingPiece().y++; } else { lockPieceOnField(game.fallingPiece()); game.pieceCount++; // Increse game speed every 10 tics if (game.pieceCount % 10 == 0) if (game.speed &gt;= 10) game.speed--; checkLines(game.fallingPiece()); game.setUpNextPiece(); if (!game.fullLines.empty()) game.score += (1 &lt;&lt; game.fullLines.size()) * 100; // Game over if it doesn't fit game.gameOver = !doesPieceFit(game.fallingPiece(), game.fallingPiece().rotation, game.fallingPiece().x, game.fallingPiece().y); } game.speedCounter = 0; } } int Utils::rotate(const int x, const int y, const int rotation) { /* * Rotates piece layout * string based on given angle * 'rotation' */ switch (rotation % 4) { case 0: return y * 4 + x; // 0 degress case 1: return 12 + y - (x * 4); // 90 degress case 2: return 15 - (y * 4) - x; // 180 degress case 3: return 3 - y + (x * 4); // 270 degress } return 0; } bool Utils::doesPieceFit(const Tetromino&amp; tetromino, const int rotation, const int x, const int y) { for (int px = 0; px &lt; 4; px++) for (int py = 0; py &lt; 4; py++) { int pi = rotate(px, py, rotation); int fi = (y + py) * playingField.fieldWidth + (x + px); if (x + px &gt;= 0 &amp;&amp; x + px &lt; playingField.fieldWidth) if (y + py &gt;= 0 &amp;&amp; y + py &lt; playingField.fieldHeight) // if cell value != 0, it's occupied if (tetromino.layout[pi] != L'.' &amp;&amp; playingField.pField[fi] != 0) return false; } return true; } void Utils::processInput(Tetromino&amp; tetromino) { bool key[4]; // x27 = right arrow key // x25 = left arrow key // x28 = down arrow key for (int k = 0; k &lt; 4; k++) key[k] = (0x8000 &amp; GetAsyncKeyState((unsigned char) ("\x27\x25\x28Z"[k]))) != 0; // Handling input tetromino.x += (key[0] &amp;&amp; doesPieceFit(tetromino, tetromino.rotation, tetromino.x + 1, tetromino.y)) ? 1 : 0; tetromino.x -= (key[1] &amp;&amp; doesPieceFit(tetromino, tetromino.rotation, tetromino.x - 1, tetromino.y)) ? 1 : 0; tetromino.y += (key[2] &amp;&amp; doesPieceFit(tetromino, tetromino.rotation, tetromino.x, tetromino.y + 1)) ? 1 : 0; if (key[3]) { tetromino.rotation += (game.rotateHold &amp;&amp; doesPieceFit(tetromino, tetromino.rotation + 1, tetromino.x, tetromino.y)) ? 1 : 0; game.rotateHold = false; } else { game.rotateHold = true; } } void Utils::checkLines(const Tetromino&amp; tetromino) { for (int py = 0; py &lt; 4; py++) { if (tetromino.y + py &lt; playingField.fieldHeight - 1) { bool line = true; for (int px = 1; px &lt; playingField.fieldWidth - 1; px++) // if any cell is empty, line isn't complete line &amp;= (playingField.pField[(tetromino.y + py) * playingField.fieldWidth + px]) != 0; if (line) { // draw '=' symbols for (int px = 1; px &lt; playingField.fieldWidth - 1; px++) playingField.pField[(tetromino.y + py) * playingField.fieldWidth + px] = 8; game.fullLines.push_back(tetromino.y + py); game.lines++; } } } } void Utils::lockPieceOnField(const Tetromino&amp; tetromino) { for (int px = 0; px &lt; 4; px++) for (int py = 0; py &lt; 4; py++) if (tetromino.layout[rotate(px, py, tetromino.rotation)] != L'.') // 0 means empty spots in the playing field playingField.pField[(tetromino.y + py) * playingField.fieldWidth + (tetromino.x + px)] = 1; } void Utils::draw(const Tetromino&amp; tetromino) { // Draw playing field for (int x = 0; x &lt; playingField.fieldWidth; x++) for (int y = 0; y &lt; playingField.fieldHeight; y++) //mapping playing field (' ', 1,..., 9) to Screen characters (' ', A,...,#) screenBuffer.screen[(y + YPADDING) * screenBuffer.screenWidth + (x + XPADDING)] = L" ▒▒▒▒▒▒▒=▓"[playingField.pField[y * playingField.fieldWidth + x]]; // Draw pieces for (int px = 0; px &lt; 4; px++) for (int py = 0; py &lt; 4; py++) { if (tetromino.layout[rotate(px, py, tetromino.rotation)] == L'X') // Drawing current piece ( n + ASCII code of character 'A') 0 . A, 1 - &gt; B, ... screenBuffer.screen[(tetromino.y + py + YPADDING) * screenBuffer.screenWidth + (tetromino.x + px + XPADDING)] = 0x2592; if (game.nextFallingPiece().layout[rotate(px, py, game.nextFallingPiece().rotation)] == L'X') // Drawing next piece ( n + ASCII code of character 'A') 0 . A, 1 - &gt; B, ... screenBuffer.screen[(YPADDING + 3 + py) * screenBuffer.screenWidth + (XPADDING / 2 + px + 3)] = 0x2592; else screenBuffer.screen[(YPADDING + 3 + py) * screenBuffer.screenWidth + (XPADDING / 2 + px + 3)] = ' '; } // Draw text swprintf_s(&amp;screenBuffer.screen[YPADDING * screenBuffer.screenWidth + XPADDING / 4], 16, L"SCORE: %8d", game.score); swprintf_s(&amp;screenBuffer.screen[(YPADDING + 1) * screenBuffer.screenWidth + XPADDING / 4], 16, L"LINES: %8d", game.lines); swprintf_s(&amp;screenBuffer.screen[(YPADDING + 4) * screenBuffer.screenWidth + XPADDING / 4], 13, L"NEXT PIECE: "); if (!game.fullLines.empty()) { WriteConsoleOutputCharacter(screenBuffer.hConsole, screenBuffer.screen, screenBuffer.screenWidth * screenBuffer.screenHeight, {0,0}, &amp;screenBuffer.dwBytesWritten); this_thread::sleep_for(400ms); for (auto &amp;v : game.fullLines) for (int px = 1; px &lt; playingField.fieldWidth - 1; px++) { for (int py = v; py &gt; 0; py--) // clear line, moving lines above one unit down playingField.pField[py * playingField.fieldWidth + px] = playingField.pField[(py - 1) * playingField.fieldWidth + px]; playingField.pField[px] = 0; } game.fullLines.clear(); } // Display Frame WriteConsoleOutputCharacter(screenBuffer.hConsole, screenBuffer.screen, screenBuffer.screenWidth * screenBuffer.screenHeight, {0,0}, &amp;screenBuffer.dwBytesWritten); } </code></pre>
[]
[ { "body": "<h1>Game Play</h1>\n<ol>\n<li>most Tetris games use the up-arrow to rotate the piece. Unless you have a very specific reason you need to do otherwise, I'd use up-arrow like everybody else.</li>\n<li>I'd consider making each individual block of a tetromino two character cells wide (and still only one high). At least in most western European fonts, characters are about twice as tall as they are wide, so your &quot;squares&quot; aren't very square. This is particularly misleading with a block that's 2x3 squares, but 3 squares wide is actually portrayed narrower than 2 squares tall.</li>\n<li>the cursor keys are <em>extremely</em> sensitive--to the point that it's often difficult to get a block to the desired column--you get back and forth and can't quite get it to stop in the right place.</li>\n<li>You haven't called <code>srand</code> anywhere, so every game has the exact same sequence of game pieces.</li>\n</ol>\n<h1>Early Exit</h1>\n<p>Right now, if the user decides to quite the game early (e.g., with <kbd>ctrl</kbd>+<kbd>C</kbd>) they're left with a console that does't really function normally. In my opinion, it would be better to handle this so the user gets a normally functioning console.</p>\n<p>One way to do that would be to add a call to <code>SetConsoleCtrlHandler</code>, to set up a handler that will close the handle to the console when/if the user kills the application.</p>\n<h1>Structure</h1>\n<p>Right now, most of the game's top-level logic is actually hidden in Utils.cpp. Normally, I'd expect something named &quot;utils.cpp&quot; to contain things that are quite generic, with no relationship to the specific program at hand, beyond some extremely general thing it does (e.g., it does some sort of string processing, so our utilities include some string stuff).</p>\n<h1>Code vs. Comments</h1>\n<p>I'm not overly fond of code like this:</p>\n<pre><code>// 0 characters are spaces and 9 are borders\npField[y * fieldWidth + x] = (x == 0 || x == fieldWidth - 1 || y == fieldHeight - 1) ? 9 : 0;\n</code></pre>\n<p>I'd prefer something like this instead:</p>\n<pre><code>static const char space = '\\x0';\nstatic const char border = '\\x9';\n\npField[y+fieldWidth+x] = (x==0 || x == fieldWidth-1 || y == fieldHeight-1) ? border : space;\n</code></pre>\n<h1>Separation of Concerns</h1>\n<p>Right now, your <code>PlayField</code> manually allocates storage for the playing field. And it simulates 2D addressing in linear memory. And it knows about where the borders go in Tetris. And it doesn't do those very well--for example, it has a ctor that allocates memory with <code>new</code>, but there's no code to delete that memory anywhere, so the memory is leaked.</p>\n<p>In my opinion, it would be better to use <code>std::vector</code> to manage the raw memory. Then write a simple wrapper to manage 2D addressing on top of that. Finally, add a layer to manage the Tetris border.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T05:49:44.137", "Id": "221570", "ParentId": "221567", "Score": "5" } } ]
{ "AcceptedAnswerId": "221570", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T01:57:30.530", "Id": "221567", "Score": "5", "Tags": [ "c++", "object-oriented", "tetris" ], "Title": "Classic Tetris implementation for Windows console (Follow up)" }
221567
<p>This is a <a href="https://leetcode.com/problems/minesweeper/" rel="noreferrer">Leetcode problem</a> -</p> <blockquote> <p><em>Let's play the Minesweeper game (<a href="https://en.wikipedia.org/wiki/Minesweeper_(video_game)" rel="noreferrer">Wikipedia</a>, <a href="http://minesweeperonline.com/" rel="noreferrer">online game</a>)!</em></p> <p><em>You are given a 2D char matrix representing the game board. '<strong>M</strong>' represents an <strong>unrevealed</strong> mine, '<strong>E</strong>' represents an <strong>unrevealed</strong> empty square, '<strong>B</strong>' represents a <strong>revealed</strong> blank square that has no adjacent (above, below, left, right, and all 4 diagonals) mines, <strong>digit</strong> (<code>1</code> to <code>8</code>) represents how many mines are adjacent to this <strong>revealed</strong> square, and finally '<strong>X</strong>' represents a <strong>revealed</strong> mine.</em></p> <p><em>Now given the next click position (row and column indices) among all the <strong>unrevealed</strong> squares (<code>M</code> or <code>E</code>), return the board after revealing this position according to the following rules -</em></p> <ul> <li><em>If a mine (<code>M</code>) is revealed, then the game is over - change it to '<strong>X</strong>'.</em></li> <li><em>If an empty square (<code>E</code>) with <strong>no adjacent mines</strong> is revealed, then change it to a revealed blank (<code>B</code>) and all of its adjacent <strong>unrevealed</strong> squares should be revealed recursively.</em></li> <li><em>If an empty square (<code>E</code>) with <strong>at least one adjacent mine</strong> is revealed, then change it to a digit (<code>1</code> to <code>8</code>) representing the number of adjacent mines.</em></li> <li><em>Return the board when no more squares will be revealed.</em></li> </ul> <p><strong><em>Example 1</em></strong> -</p> <pre><code>Input: [['E', 'E', 'E', 'E', 'E'], ['E', 'E', 'M', 'E', 'E'], ['E', 'E', 'E', 'E', 'E'], ['E', 'E', 'E', 'E', 'E']] Click : [3,0] Output: [['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] </code></pre> <p><strong><em>Explanation</em></strong> -</p> <p><a href="https://i.stack.imgur.com/sNH47.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sNH47.png" alt="enter image description here"></a></p> <p><strong><em>Example 2</em></strong> -</p> <pre><code>Input: [['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] Click : [1,2] Output: [['B', '1', 'E', '1', 'B'], ['B', '1', 'X', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B']] </code></pre> <p><strong><em>Explanation</em></strong> -</p> <p><a href="https://i.stack.imgur.com/mVWmB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mVWmB.png" alt="enter image description here"></a></p> <p><strong><em>Note</em></strong> -</p> <ul> <li><em>The range of the input matrix's height and width is <code>[1,50]</code>.</em></li> <li><em>The click position will only be an unrevealed square (<code>M</code> or <code>E</code>), which also means the input board contains at least one clickable square.</em></li> <li><em>The input board won't be a stage when the game is over (some mines have been revealed).</em></li> <li><em>For simplicity, not mentioned rules should be ignored in this problem. For example, you <strong>don't</strong> need to reveal all the unrevealed mines when the game is over, consider any cases that you will win the game or flag any squares.</em></li> </ul> </blockquote> <p>Here is my solution to this challenge -</p> <pre><code>class Solution: directions = [(-1, 0), (-1, -1), (-1, 1), (0,-1), (0, 1), (1, -1), (1, 0), (1, 1)] def updateBoard(self, board, click): """ :type board: List[List[str]] :type click: List[int] :rtype: List[List[str]] """ return self.dfs(board, click) def dfs(self, board, click): stack = [(click[0], click[1])] m, n = len(board), len(board[0]) while stack: r, c = stack.pop() # last inserted element if board[r][c] == 'M': board[r][c] = 'X' break # check for adjacent mines mines = 0 for i, j in self.directions: dr = r + i dc = c + j if 0 &lt;= dr &lt; m and 0 &lt;= dc &lt; n and board[dr][dc] == 'M': mines += 1 board[r][c] = str(mines) if mines else 'B' # add neighbors for i, j in self.directions: dr = r + i dc = c + j if 0 &lt;= dr &lt; m and 0 &lt;= dc &lt; n and board[r][c] == 'B' and board[dr][dc] == 'E': stack.append((dr, dc)) return board </code></pre> <p>Here is my Leetcode result (54 test cases) -</p> <p><a href="https://i.stack.imgur.com/BPL7A.png" rel="noreferrer"><img src="https://i.stack.imgur.com/BPL7A.png" alt="enter image description here"></a></p> <p>So, I would like to know whether I could make this program shorter and more efficient.</p> <p>Any help would be highly appreciated.</p>
[]
[ { "body": "<ul>\n<li><p>An <code>M</code> field is never pushed. It may only happen as a result of an unfortunate click. Testing for <code>board[r][c] == 'M'</code> in the loop is a waste of time. Test it once, <code>if board[click[0]][click[1]] == 'M'</code>, before the loop.</p></li>\n<li><p>Similarly, you should not bother with neighbors if the field is not blank. A test for <code>board[r][c] == 'B'</code> happens too late. As implemented, for other fields code still compute neighbors - and does nothing with them.</p></li>\n<li><p>The tests for <code>0 &lt;= dr &lt; m and 0 &lt;= dc &lt; n</code> <em>may</em> also cause performance issues, and do not look Pythonic. Ask forgiveness not permission, e.g.</p>\n\n<pre><code> try:\n if board[dr][dc] == 'M':\n mines += 1\n except IndexError:\n pass\n</code></pre></li>\n<li><p>Quite a few fields are pushed and inspected multiple times. I am not sure wether it is a bottleneck; however the right-hand and scanline methods of <a href=\"https://en.wikipedia.org/wiki/Flood_fill\" rel=\"nofollow noreferrer\">flood fill algorithm</a> do worth investigation.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T04:00:33.377", "Id": "428641", "Score": "1", "body": "Unfortunately, `board[-1][-1]` is not a `IndexError` so that optimization is actually a bug. But if you ask, I’ll forgive you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T04:17:54.963", "Id": "428645", "Score": "1", "body": "@AJNeufeld Forgiveness accepted." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T15:12:26.253", "Id": "221591", "ParentId": "221575", "Score": "4" } }, { "body": "<p>Instead of repeating <code>0 &lt;= dr &lt; m</code> and <code>0 &lt;= dc &lt; n</code> tests in the mine counting loop and the recursive search step, looping over the 2x2, 2x3, 3x2 or 3x3 grid for any <code>r,c</code> coordinate might be better done using a generator expression, using ranges:</p>\n\n<pre><code>while stack:\n r, c = stack.pop()\n\n rows = range(max(0, r-1), min(r+2, m))\n cols = range(max(0, c-1), min(c+2, n))\n\n mines = sum(1 for i in rows for j in cols if board[i][j] == 'M')\n</code></pre>\n\n<p>As a bonus, you get to reuse those ranges if you find a blank square, for the queuing of virtual click coordinates.</p>\n\n<pre><code> if mines:\n board[r][c] = str(mines)\n else:\n board[r][c] = 'B'\n for i in rows:\n for j in cols:\n if board[i][j] == 'E':\n stack.append((i, j))\n</code></pre>\n\n<hr>\n\n<p>When you click on a square, and find it is empty, and there are no mines around it, you mark it <code>B</code>, and immediately \"click\" every <code>E</code> square around it (<code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>f</code>, <code>g</code>, <code>h</code>, &amp; <code>i</code>):</p>\n\n<pre><code>. . . . . . . .\n. . . . . . . .\n. . a b c . . .\n. . d B f . . .\n. . g h i . . .\n. . . . . . . .\n. . . . . . . .\n</code></pre>\n\n<p>This adds positions <code>a</code>, <code>b</code>, <code>c</code>, <code>d</code>, <code>f</code>, <code>g</code>, <code>h</code>, &amp; <code>i</code> to <code>stack</code>. You pop position <code>i</code> off the stack, and if it turns out to also be surrounded by 0 mines, you add its <code>E</code> neighbours to <code>stack</code>, including <code>f</code> and <code>h</code> a second time. Eventually, you'll pop <code>h</code> off the stack, and add if it is surrounded by zero mines, add <code>d</code> &amp; <code>g</code> a second time, and <code>f</code> a third time. This leads to needlessly counting up the mines around various positions multiple times during one <code>dfs</code> call. Needless repeated counting will, of course, waste time and slow your algorithm down.</p>\n\n<p>Instead of using a <code>list</code> as a <code>stack</code>, you could use a <code>set</code>, which would ignore any duplicate coordinates which are attempted to be queued for subsequent processing.</p>\n\n<p>Alternately, you could mark the \"just queued\" position with a different symbol, say <code>_</code>, which will eventually be filled in with the number of mines surrounding that square (or <code>B</code>) once that position is popped off the stack for processing. However, it will no longer be an <code>E</code>, so it won't be accidentally queued multiple times.</p>\n\n<pre><code> else:\n for i in rows:\n for j in cols:\n if board[i][j] == 'E':\n stack.append((i, j))\n board[i][j] = '_' # Temporary mark to prevent repeated queueing\n</code></pre>\n\n<hr>\n\n<p>Using slices for counting the number of mines may be slightly faster, due to the fewer indexing operations:</p>\n\n<pre><code>while stack:\n r, c = stack.pop()\n\n rmin, rmax = max(0, r-1), min(r+2, m)\n cmin, cmax = max(0, c-1), min(c+2, n)\n\n mines = sum(cell == 'M' for row in board[rmin:rmax] for cell in row[cmin:cmax])\n if mines:\n board[r][c] = str(mines)\n else:\n board[r][c] = 'B'\n for i in range(rmin, rmax):\n for j in range(cmin, cmax):\n if board[i][j] == 'E':\n stack.append((i, j))\n board[i][j] = '_' # Temporary mark to prevent repeated queueing\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T03:24:38.573", "Id": "221622", "ParentId": "221575", "Score": "4" } } ]
{ "AcceptedAnswerId": "221622", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T07:20:06.543", "Id": "221575", "Score": "5", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "depth-first-search" ], "Title": "(Leetcode) Minesweeper game" }
221575
<p>I tried to apply for software engineer - intern with this task, and there is no reply since I sent it, so I guess I failed. Can you give me a direction in what way I should improve my code?</p> <p><strong>Task:</strong> The point of this task is to create a service, which will generate a mosaic for given images downloaded from provided URLs.</p> <p><code>mosaic.py</code> takes a list of images in cv2 format (for example jpg) and creates a mosaic from them. <code>server.py</code> allows to run a server on your computer from command line, so by entering <code>localhost:8080</code> in your web browser you can provide a link with urls. The server downloads all images and passes it to the mosaic function, so the mosaic is displayed in the web browser.</p> <p>Example with 3 images: When this URL is provided, one of possible outcomes: <a href="http://localhost:8080/mozaika?losowo=1&amp;rozdzielczosc=512x512&amp;zdjecia=https://www.humanesociety.org/sites/default/files/styles/768x326/public/2018/08/kitten-440379.jpg?h=f6a7b1af&amp;itok=vU0J0uZR,https://cdn.britannica.com/67/197567-131-1645A26E.jpg,https://images.unsplash.com/photo-1518791841217-8f162f1e1131?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;w=1000&amp;q=80" rel="nofollow noreferrer">http://localhost:8080/mozaika?losowo=1&amp;rozdzielczosc=512x512&amp;zdjecia=https://www.humanesociety.org/sites/default/files/styles/768x326/public/2018/08/kitten-440379.jpg?h=f6a7b1af&amp;itok=vU0J0uZR,https://cdn.britannica.com/67/197567-131-1645A26E.jpg,https://images.unsplash.com/photo-1518791841217-8f162f1e1131?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;w=1000&amp;q=80</a> <a href="https://i.stack.imgur.com/YA7kt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YA7kt.jpg" alt="enter image description here"></a></p> <p>To run:</p> <ul> <li>Required libraries: http.server, numpy, opencv-python</li> <li>Github: <a href="https://github.com/Krzysztof-Wojtczak/Allegro-Task" rel="nofollow noreferrer">https://github.com/Krzysztof-Wojtczak/Allegro-Task</a></li> <li>Run server.py</li> <li><p>In your browser type: <a href="http://localhost:8080/mozaika?losowo=Z&amp;rozdzielczosc=XxY&amp;zdjecia=URL1,URL2,URL3" rel="nofollow noreferrer">http://localhost:8080/mozaika?losowo=Z&amp;rozdzielczosc=XxY&amp;zdjecia=URL1,URL2,URL3</a>...</p> <p>where: <code>losowo</code> - optional parameter, if Z = 1 images places are random. <code>rozdzielczosc</code> - optional parameter, defines width and height. Default is 2048x2048 <code>URL1,URL2,URL3...</code> image addresses, 1 to 9.(or copy the link above).</p></li> </ul> <p>mosaic.py:</p> <pre><code>import cv2 import numpy as np import random from math import ceil class Mozaika: """Class Mozaika takes 1 required attribute: list of images in cv2 format, 3 optional attributes: random image positioning, width of output image, height of output image. Output image is stored in variable 'output_image'. Class is looking for the least proportional image and returns it in (0,0) - top left corner if no random positioning""" def __init__(self, image_list, losowo, w=2048, h=2048): self.losowo = losowo # defines whether image position is random self.w = int(w) # width of output image self.h = int(h) # height of output image self.output_image = 0 # variables are stored in 3 lists: image_names for sorted name strings, image_list for image in cv2 format, # image_dict for height and width for every image self.image_names = [] # Names of images self.image_list = image_list # list of files (images) if self.losowo == 1: random.shuffle(self.image_list) for i in range(len(self.image_list)): self.image_names.append(f"img{i}") self.image_dict = {} for image in range(len(self.image_list)): key = self.image_names[image] h, w = self.image_list[image].shape[:2] # height, width of each image self.image_dict[key] = [h, w] self.how_many_images() def how_many_images(self): number_of_images = len(self.image_dict) # checks how many images is given if number_of_images == 1: self.make_square() self.resize_huge_image() elif number_of_images == 2: self.rectangle_image(2) elif number_of_images == 3 or number_of_images == 4: self.grid2x2() elif number_of_images &gt; 4: self.grid3x3() def rectangle_image(self, images=1): # the least proportional image will become a rectangle ratios = [] self.check_ratio() ratios = [e[2] for e in list(self.image_dict.values())] # getting image ratio(s) max_ratio = max(ratios) for name, value in self.image_dict.items(): # finding highest/longest image if value[2] == max_ratio: name_max = name list_index_max = self.image_names.index(name) if images == 1: # method is called for 1 image if self.image_dict[name_max][1] &gt; self.image_dict[name_max][0]: # checks if width or height of the image is greater return self.make_horizontal_rectangle(name_max, list_index_max, max_ratio), 0, name_max # return image, horizontal/vertical, name of image elif self.image_dict[name_max][1] &lt; self.image_dict[name_max][0]: return self.make_vertical_rectangle(name_max, list_index_max, max_ratio), 1, name_max elif images == 2: #it will only work if there are 2 images, creates mosaic of 2 images i = 0 if self.image_dict[name_max][1] &gt; self.image_dict[name_max][0]: for name, value in self.image_dict.items(): # checks ratio the least proportional image and decides self.make_horizontal_rectangle(name, i, value[2]) # whether images should be vertical or horizontal i += 1 self.merge_two_images_horizontally() # merge 2 images with minimum quality loss elif self.image_dict[name_max][1] &lt; self.image_dict[name_max][0]: for name, value in self.image_dict.items(): self.make_vertical_rectangle(name, i, value[2]) i += 1 self.merge_two_images_vertically() def check_ratio(self): # appends to dictionary height to width (or width to height) ratio i = 0 for image in self.image_dict: if self.image_dict[image][0] &gt; self.image_dict[image][1]: ratio = self.image_dict[image][0]/self.image_dict[image][1] else: ratio = self.image_dict[image][1]/self.image_dict[image][0] self.image_dict[image].append(ratio) def make_square(self): # centralizes picture and cuts it so it becomes a square i = 0 for image in self.image_dict.values(): # check in dictionary for width/height if image[0] &gt; image[1]: cut = int((image[0] - image[1])/2) self.image_list[i] = self.image_list[i][cut : -cut, :image[1]] # numpy operation on image elif image[0] &lt; image[1]: cut = int((image[1] - image[0])/2) self.image_list[i] = self.image_list[i][:image[0], cut : -cut] i += 1 def make_horizontal_rectangle(self, name, list_index, ratio): # if ratio == 2, it's perfect rectangle. Otherwise it is cut to this ratio if ratio &lt; 2: cut = int( (self.image_dict[name][0] - (self.image_dict[name][0] / (2/ratio)))/2 ) return self.image_list[list_index][cut : -cut, : self.image_dict[name][1]] elif ratio &gt; 2: if self.image_dict[name][1] &gt; self.image_dict[name][0]: cut = int( (self.image_dict[name][0] - (self.image_dict[name][0] / (ratio/2)))/2 ) return self.image_list[list_index][: self.image_dict[name][0], cut : -cut] def make_vertical_rectangle(self, name, list_index, ratio): if ratio &lt; 2: cut = int( (self.image_dict[name][1] - (self.image_dict[name][1] / (2/ratio)))/2 ) return self.image_list[list_index][: self.image_dict[name][0], cut : -cut] elif ratio &gt; 2: cut = int( (self.image_dict[name][1] - (self.image_dict[name][1] / (ratio/2)))/2 ) return self.image_list[list_index][cut : -cut, : self.image_dict[name][1]] def merge_two_images_horizontally(self): # method takes 2 horizontal images and merges them self.image_list[0] = cv2.resize(self.image_list[0], (self.w, int(self.h/2))) self.image_list[1] = cv2.resize(self.image_list[1], (self.w, int(self.h/2))) self.output_image = np.concatenate((self.image_list[0], self.image_list[1]), axis=0) def merge_two_images_vertically(self): # method takes 2 vertical images and merges them self.image_list[0] = cv2.resize(self.image_list[0], (int(self.w/2), self.h)) self.image_list[1] = cv2.resize(self.image_list[1], (int(self.w/2), self.h)) self.output_image = np.concatenate((self.image_list[0], self.image_list[1]), axis=1) def resize_huge_image(self): # returns one image of the size of the output image self.output_image = cv2.resize(self.image_list[0], (self.w, self.h)) def resize_big_image(self, index): # returns one image of 2/3 width/height of the output image name = self.image_names[index] return cv2.resize(self.image_list[index], (int(self.w/(3/2)), int(self.h/(3/2)))), name def resize_medium_image(self, index): # returns one image of 1/2 width/height of the output image return cv2.resize(self.image_list[index], (int(self.w/2), int(self.h/2))) def resize_small_image(self, index): # returns one image of 1/3 width/height of the output image return cv2.resize(self.image_list[index], (int(self.w/3), int(self.h/3))) def grid2x2(self): placement = self.put_image2x2() # defines where to put images decrease_h = ceil(2*(self.h/2 - int(self.h/2))) # decrease size of output image due to roundings, so there are no black spaces decrease_w = ceil(2*(self.w/2 - int(self.w/2))) vis = np.zeros((self.h - decrease_h, self.w - decrease_w, 3), np.uint8) # smaller image due to roundings num = 0 for i in range(0,2): # grid 2x2, so 4 squares to fill for k in range(0,2): vis[i*int(self.h/2) : (i+1)*int(self.h/2), k*int(self.w/2) : (k+1)*int(self.w/2)] = placement[num] num += 1 self.output_image = cv2.resize(vis, (self.w, self.h)) # optional, scales image to match requirements accurately def grid3x3(self): placement = self.put_image3x3() # defines where to put images decrease_h = ceil(3*(self.h/3 - int(self.h/3))) # decrease size of output image due to roundings, so there are no black spaces decrease_w = ceil(3*(self.w/3 - int(self.w/3))) vis = np.zeros((self.h - decrease_h, self.w - decrease_w, 3), np.uint8) # smaller image due to roundings num = 0 for i in range(0,3): # grid 3x3, so nine squares to fill for k in range(0,3): vis[i*int(self.h/3) : (i+1)*int(self.h/3), k*int(self.w/3) : (k+1)*int(self.w/3)] = placement[num] num += 1 self.output_image = cv2.resize(vis, (self.w, self.h)) # optional, scales image to match requirements accurately def put_image2x2(self): placement = [0]*4 # it'll store images if len(self.image_names) == 3: # to do if there are 3 images rect_image, vertical, name = self.rectangle_image() index = self.image_names.index(name) self.image_list.pop(index) # deleting rectangle image from image_list, so there will be no duplicates other_position = [e for e in range(4)] # 4 possibilities to put 1 image if vertical: # 1 vertical image rect_image = cv2.resize(rect_image, (int(self.w/2), self.h)) if self.losowo == 1: position = random.randrange(0,2) # choose random position for image else: position = 0 # or fixed position other_position.remove(position) # rectangle image takes 2 places other_position.remove(position + 2) placement[position] = rect_image[:int(self.h/2), :int(self.w/2)] placement[position + 2] = rect_image[int(self.h/2):self.h, :int(self.w/2)] else: # 1 horizontal image rect_image = cv2.resize(rect_image, (self.w, int(self.h/2))) if self.losowo == 1: position = random.randrange(0,3,2) # possible positions are top left and bottom left else: position = 0 other_position.remove(position) other_position.remove(position + 1) placement[position] = rect_image[:int(self.h/2), :int(self.w/2)] placement[position + 1] = rect_image[:int(self.h/2), int(self.w/2):self.w] num = 0 for i in other_position: # after puting bigger image fill other places with smalles images placement[i] = self.resize_medium_image(num) num += 1 else: # 4 images for i in range(len(self.image_list)): placement[i] = self.resize_medium_image(i) # fill 4 places with medium images return placement def put_image3x3(self): placement = [0]*9 img2x = [] # list of rectangle images img4x = [] # list of big square images num_img = len(self.image_names) var = 0 var1 = 0 while num_img &lt; 9: if 9 - num_img &lt; 3: # big image can't fit, increase number of takes space by making rectangles img2x.append(self.rectangle_image()) remove_image = img2x[var][2] # get image name self.image_dict.pop(remove_image) # delete image to avoid duplicates (there are 3 places where it is) index = self.image_names.index(remove_image) self.image_names.remove(remove_image) self.image_list.pop(index) num_img += 1 var += 1 else: img4x.append(self.resize_big_image(0)) remove_image = img4x[var1][1] # get image name self.image_dict.pop(remove_image) # delete image to avoid duplicates index = self.image_names.index(remove_image) self.image_names.remove(remove_image) self.image_list.pop(index) var1 += 1 num_img += 3 biash = ceil(self.h*(2/3) - int(self.h*(2/3))) # image can be to big to fit in square, need to decrease it biasw = ceil(self.w*(2/3) - int(self.w*(2/3))) other_position = set([e for e in range(9)]) # 9 possible places for one image for img in img4x: # takes big image and tries to fit it square_img = img[0] other_position, position = self.find_big_position(other_position) # find possible position placement[position] = square_img[:int(self.h/3), :int(self.w/3)] # top left corner of the image placement[position + 1] = square_img[:int(self.h/3), int(self.w/3):int(self.w*(2/3)) - biasw] # top right corner placement[position + 3] = square_img[int(self.h/3):int(self.h*(2/3)) - biash, :int(self.w/3)] # bottom left corner placement[position + 4] = square_img[int(self.h/3):int(self.h*(2/3)) - biash, int(self.w/3):int(self.w*(2/3)) - biasw] # bottom right corner for img in img2x: # takes rectangles and tries to fit them rect_image, vertical = img[:2] # check if rectangle is vertical if vertical: rect_image = cv2.resize(rect_image, (int(self.w/3), int(self.h*(2/3)))) other_position, position = self.find_vertical_position(other_position) # checks for vertical possibilities placement[position] = rect_image[:int(self.h/3), :int(self.w/3)] placement[position + 3] = rect_image[int(self.h/3):int(self.h*(2/3)) - biash, :int(self.w/3)] else: rect_image = cv2.resize(rect_image, (int(self.w*(2/3)), int(self.h/3))) other_position, position = self.find_horizontal_position(other_position) # checks for horizontal possibilities placement[position] = rect_image[:int(self.h/3), :int(self.w/3)] placement[position + 1] = rect_image[:int(self.h/3), int(self.w/3):int(self.w*(2/3)) - biasw] num = 0 for i in other_position: # after puting bigger image fill other places with smaller images placement[i] = self.resize_small_image(num) num += 1 return placement def find_big_position(self, avaiable_pos): # find position for 2/3 width/height image myList = avaiable_pos mylistshifted=[x-1 for x in myList] possible_position = [0,1,3,4] # only possible possisions for big image intersection_set = list(set(myList) &amp; set(mylistshifted) &amp; set(possible_position)) if self.losowo == 1: position = random.choice(intersection_set) else: position = intersection_set[0] myList.remove(position) # removes places from other_position, so no other image can take these places myList.remove(position + 1) myList.remove(position + 3) myList.remove(position + 4) return myList, position def find_horizontal_position(self, avaiable_pos): # find position for horizontal rectangle image myList = avaiable_pos mylistshifted=[x-1 for x in myList] possible_position = [0,1,3,4,6,7] # positions where image is not cut in half intersection_set = list(set(myList) &amp; set(mylistshifted) &amp; set(possible_position)) if self.losowo == 1: position = random.choice(intersection_set) else: position = intersection_set[0] myList.remove(position) # removes places from other_position, so no other image can take these places myList.remove(position + 1) return myList, position def find_vertical_position(self, avaiable_pos): # find position vertical rectangle image myList = avaiable_pos mylistshifted=[x-3 for x in myList] possible_position = [e for e in range(6)] # positions where image is not cut in half intersection_set = list(set(myList) &amp; set(mylistshifted) &amp; set(possible_position)) if self.losowo == 1: position = random.choice(intersection_set) else: position = intersection_set[0] myList.remove(position) # removes places from other_position, so no other image can take these places myList.remove(position + 3) return myList, position </code></pre> <p>server.py</p> <pre><code>from http.server import HTTPServer, BaseHTTPRequestHandler import re from urllib.request import urlopen import cv2 import numpy as np from mozaika import Mozaika class Serv(BaseHTTPRequestHandler): def do_GET(self): w = 2048 # default width h = 2048 # default height losowo = 1 # random image placement = true urls = [] # images URLs if self.path.startswith("/mozaika?"): # keyword for getting mosaic, URL should be put in format: parameters = self.path.split("&amp;") # http://localhost:8080/mozaika?losowo=Z&amp;rozdzielczosc=XxY&amp;zdjecia=URL1,URL2,URL3.. for par in parameters: if par.find("losowo") == -1: pass else: losowo_index = par.find("losowo") try: losowo = int(par[losowo_index + 7]) except: pass if par.find("rozdzielczosc") == -1: pass else: try: w, h = re.findall('\d+', par) except: pass if par.find("zdjecia=") == -1: pass else: urls = self.path[self.path.find("zdjecia=") + 8 :] urls = urls.split(",") try: image_list = create_images_list(urls) # call mosaic creator # 1 required attribute: list of images in cv2 format, # 3 optional attributes: random image positioning, width of output image, height of output image mozaika = Mozaika(image_list, losowo, w, h) img = mozaika.output_image # store output image f = cv2.imencode('.jpg', img)[1].tostring() # encode to binary format self.send_response(200) self.send_header('Content-type', 'image/jpg') except: self.send_response(404) self.end_headers() self.wfile.write(f) # send output image #return def url_to_image(url): # gets image from URL and converts it to cv2 color image format resp = urlopen(url) image = np.asarray(bytearray(resp.read()), dtype="uint8") image = cv2.imdecode(image, cv2.IMREAD_COLOR) return image def create_images_list(urls): # takes URLs list and creates list of images image_list = [] for url in urls: image = url_to_image(url) if image is not None: image_list.append(image) return image_list httpd = HTTPServer(("localhost", 8080), Serv) httpd.serve_forever() </code></pre>
[]
[ { "body": "<ul>\n<li>You have a god-class <code>Mozaika</code>, you should define image mutations on another class <code>Image</code>.</li>\n<li><p>You have <em>three mutating containers</em> that hold the information you need. This is <em>really really really bad</em>. If I were an interviewer the second I see that I'd know I wouldn't want you.</p>\n\n<p>This is because it makes your code hard to read, and really fragile.</p></li>\n</ul>\n\n<p>Below is what, a segment of, your code would look like without these two <em>massive</em> problems:</p>\n\n<pre><code>import cv2\nimport numpy as np\nimport random\nfrom math import ceil\n\n\nclass Image:\n def __init__(self, image):\n self._image = image\n self.height, self.width = image.shape[:2]\n\n @property\n def ratio(self):\n return max(self.height, self.width) / min(self.height, self.width)\n\n def square(self):\n if self.height &gt; self.width:\n cut = int((self.height - self.width) / 2)\n return Image(self._image[cut : -cut, :self.width])\n else:\n cut = int((self.width - self.height) / 2)\n return Image(self._image[:self.height, cut : -cut])\n\n def make_horizontal_rectangle(self):\n ratio = self.ratio\n if ratio &lt; 2:\n cut = int((self.height - ratio * self.height / 2) / 2)\n return Image(self._image[cut : -cut, : self.width])\n elif ratio &gt; 2:\n if self.width &gt; self.height:\n cut = int((self.height - 2 * self.height / ratio) / 2)\n return Image(self._image[: self.height, cut : -cut])\n return self\n\n def make_vertical_rectangle(self):\n ratio = self.ratio\n if ratio &lt; 2:\n cut = int((self.width - ratio * self.width / 2) / 2)\n return Image(self._image[: self.height, cut : -cut])\n elif ratio &gt; 2:\n cut = int((self.width - 2 * self.width / ratio) / 2)\n return Image(self._image[cut : -cut, : self.width])\n return self\n\n def resize(self, width, height):\n return cv2.resize(self._image, (width, height))\n\n def merge(self, other, horizontally=True):\n axis = 0 if horizontally else 1\n return Image((self._image, other._image), axis=axis)\n\n\nclass Mozaika:\n def __init__(self, image_list, losowo, w=2048, h=2048):\n self.losowo = losowo # defines whether image position is random\n self.w = int(w) # width of output image\n self.h = int(h) # height of output image\n self.output_image = 0\n\n self.images = [Image(i) for i in image_list]\n if self.losowo == 1:\n random.shuffle(self.images)\n self.how_many_images()\n\n def how_many_images(self):\n number_of_images = len(self.image_dict) # checks how many images is given\n if number_of_images == 1:\n self.output_image = self.images[0].square().resize(self.w, self.h)\n elif number_of_images == 2:\n self.output_image = self.rectangle_image(2)[0]\n elif number_of_images == 3 or number_of_images == 4:\n self.grid2x2()\n elif number_of_images &gt; 4:\n self.grid3x3()\n\n def rectangle_image(self, images=1):\n largest = max(self.images, key=lambda i: i.ratio)\n maxratio = largest.ratio\n\n if images == 1:\n if largest.width &gt; largest.height:\n return largest.make_horizontal_rectangle(), 0\n elif self.width &lt; self.height:\n return largest.make_vertical_rectangle(), 1\n elif images == 2:\n # ...\n</code></pre>\n\n<p>To get a better review you should change the rest of the code to follow the same style the above is. To help you out I'll give you some 'rules':</p>\n\n<ul>\n<li><p>You're only allowed to overwrite <code>self.images</code>.</p>\n\n<p>This means:</p>\n\n<pre><code># Not allowed\nself.images[0] = ...\nimages = self.images\nimages[0] = ...\nself.images = images\n\n# Allowed\nself.images = [...]\n\nimport copy\nimages = copy.copy(self.images)\nimages[0] = ...\nself.images = images\n</code></pre>\n\n<p>Mutating data can lead to unpredictable things to happen. Overwriting data allows people to understand everything that's happening. Even if it's more verbose.</p>\n\n<p>If you post another question someone will probably say my recommendations are bad. And they are in their own way, but doing by following them you'll have gotten rid of some <em>larger</em> problems, that almost makes your code <em>un-reviewable</em>.</p></li>\n<li><p>You're only allowed to overwrite <code>Mozakia.images</code> <em>once</em> per function call.</p></li>\n<li><p>Only <code>Mozaika.images</code> is allowed to contain <code>Image</code>s.</p>\n\n<p>You are allowed local variables that hold <code>Image</code>s too. (Like <code>images</code> in the above code snippet.)</p></li>\n<li><p>You're not allowed to touch <code>Image._image</code> outside of <code>Image</code>.</p></li>\n<li>Only <code>Image.merge</code> is allowed to be passed another <code>Image</code>.</li>\n<li>You're not allowed to change <code>Image.merge</code>.</li>\n</ul>\n\n<p>This will mean that your code doesn't abuse mutations, and your code will be split up correctly into different segments. Meaning that it'll be <em>far easier</em> to review.</p>\n\n<p>I <em>highly</em> recommend you follow the above rules and come back and post another question.</p>\n\n<hr>\n\n<p>Additional notes:</p>\n\n<ul>\n<li>All the functions in <code>Image</code> return a new <code>Image</code>, in your code, sometimes the code wouldn't mutate <code>Mozaika.image_list</code>, and so in these cases they return <code>self</code>.</li>\n<li>Your code looks like it has some bugs, you always do <code>if a &gt; b: elif a &lt; b:</code> never with an <code>else</code>. This means that your code can fail <code>if a == b</code>.</li>\n<li><code>make_horizontal_rectangle</code> has an additional <code>if</code> that <code>make_vertical_rectangle</code>. That looks like a bug.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T09:50:09.670", "Id": "429673", "Score": "0", "body": "Thank you! I can see now one more massive problem, where I thought it'll be easier to understand, but no... There are 3 functions merging images, you didn't mention the 2 more important - I should have really deleted function merging 2 images. put_image2x2 and 3x3 are using grids of zeros to put images there. I think they should be in Mozaika class, and Image class will be for operations on single images, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T11:18:34.397", "Id": "429682", "Score": "0", "body": "@Plajerity As your code because too complex for me to reasonably review, I didn't look at the code after where I put the `# ...`. Whilst I havn't looked at the code, you should be able to convert `put_image2x2` and `put_image3x3` to use `Image.merge`. `Image` is for a single image. `Image.merge` is to merge two images. `Mozaika` should only position the images, and defer to `Image` when it needs to merge or resize an image. Try following the above rules, and post another answer, it will surely benefit you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T20:57:00.840", "Id": "431091", "Score": "0", "body": "I feel I should mention it... It's not possible to use Image.merge (with concatenate) for more than 2 images. Concatenate requires to merge images of the same width/height. We would need to write in which order it merges, and it depends on where is rectangle image - random position. When I was writing it, first I created function to merge 2 images, and then realised that it's not possible with more images. Therefore there are more merging functions, and I decided to leave \"the simplest one\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T21:02:08.577", "Id": "431093", "Score": "0", "body": "@Plajerity I'm not sure this is the case. However I may be wrong. Can you show me an example image that would need these other merge functions, as the one in the OP doesn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T21:04:20.220", "Id": "431094", "Score": "0", "body": "Take a look at given image above. Firstly we need to merge vertically, then horizontally. Otherwise it won't work.\nIf image with the highest ratio was horizontal, we would need to merge 2 smaller images horizontally and then merge them all vertically. There are to many combinations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T21:05:36.750", "Id": "431095", "Score": "0", "body": "@Plajerity I don't see what the problem is. You've literally said it's doable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T21:06:21.270", "Id": "431097", "Score": "0", "body": "Don't forget that image positions are random." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T21:07:54.930", "Id": "431098", "Score": "0", "body": "@Plajerity Not forgotten, still doable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-20T21:08:50.390", "Id": "431099", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/95198/discussion-between-plajerity-and-peilonrayz)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T13:44:39.180", "Id": "222024", "ParentId": "221583", "Score": "4" } } ]
{ "AcceptedAnswerId": "222024", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T11:24:20.257", "Id": "221583", "Score": "5", "Tags": [ "python", "python-3.x", "image" ], "Title": "Create mosaic task" }
221583
<p>This is a <a href="https://leetcode.com/problems/burst-balloons/" rel="nofollow noreferrer">Leetcode problem</a> -</p> <blockquote> <p><em>Given <code>n</code> balloons, indexed from <code>0</code> to <code>n-1</code>. Each balloon is painted with a number on it represented by array <code>nums</code>. You are asked to burst all the balloons. If you burst the balloon <code>i</code> you will get <code>nums[left] * nums[i] * nums[right]</code> coins. Here <code>left</code> and <code>right</code> are adjacent indices of <code>i</code>. After the burst, the <code>left</code> and <code>right</code> then become adjacent.</em></p> <p><em>Find the maximum coins you can collect by bursting the balloons wisely.</em></p> <p><strong><em>Note -</em></strong></p> <ul> <li><em>You may imagine <code>nums[-1] = nums[n] = 1</code>. They are not real, therefore, you can not burst them.</em></li> <li><em><span class="math-container">\$0\$</span> <span class="math-container">\$≤\$</span> <code>n</code> <span class="math-container">\$≤\$</span> <span class="math-container">\$500\$</span><span class="math-container">\$,\$</span> <span class="math-container">\$0\$</span> <span class="math-container">\$≤\$</span> <code>nums[i]</code> <span class="math-container">\$≤\$</span> <span class="math-container">\$100\$</span></em></li> </ul> <p><strong><em>Example -</em></strong></p> <pre><code>Input: [3,1,5,8] Output: 167 Explanation: nums = [3,1,5,8] --&gt; [3,5,8] --&gt; [3,8] --&gt; [8] --&gt; [] coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 </code></pre> </blockquote> <p>Here is my solution to this challenge -</p> <pre><code># Uses dynamic programming def max_coins(nums): """ :type nums: List[int] :rtype: int """ nums = [1] + nums + [1] n = len(nums) dp = [[0] * n for i in range(n)] for j in range(2, n): for i in range(j - 2, -1, -1): for k in range(i + 1,j): dp[i][j] = max(dp[i][j], dp[i][k] + dp[k][j] + nums[i] * nums[j] * nums[k]) return dp[0][-1] </code></pre> <p>Here is the Leetcode result (70 test cases) -</p> <p><a href="https://i.stack.imgur.com/P1GvX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P1GvX.png" alt="enter image description here"></a></p> <p>So, I would like to know whether I could make this program shorter and more efficient.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T12:36:20.320", "Id": "428534", "Score": "0", "body": "Is code length your primary concern? If I see that code, eliminating the doubly nested for-loop would be mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T12:58:53.560", "Id": "428535", "Score": "0", "body": "Well, my main concern is efficiency and it would just be better if it could be made shorter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T14:34:06.350", "Id": "428897", "Score": "0", "body": "Small things `dp = [[0] * n for i in range(n)]` can be `dp = [[0] * n for _ in range(n)]`. By convention in python if we dont use the index variable we just use `_`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T12:06:39.777", "Id": "221587", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "dynamic-programming" ], "Title": "Bursting Balloons" }
221587
<p><code>lodash.isEmpty([{}])</code> returns <code>false</code> even though the object contained in the array is empty. </p> <p>I need something that considers these kind of nested objects empty too and wrote the below recursive function. It looks a bit ugly and doesn't use any <code>JavaScript</code> specific tricks. Any comments welcome.</p> <pre><code>export function isDeepEmpty(input) { // catch null or undefined object if (!input) return true if (typeof(input) === 'object') { for (const entry of Object.values(input)) { if (!isDeepEmpty(entry)) { return false } } return true } // if input is not an object return false return false } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T15:13:21.873", "Id": "428555", "Score": "0", "body": "You return `true` if any item is `!= true` eg `isDeepEmpty([0])` and which to me seams wrong, Could you be more specific in regards to what you mean by empty." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T15:30:12.543", "Id": "428558", "Score": "0", "body": "Good point, thanks very much! Let me think more." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T16:24:57.133", "Id": "428562", "Score": "0", "body": "It appears [lodash](https://lodash.com) is an utility library, and this is where your [isEmpty()](https://lodash.com/docs/4.17.11#isEmpty) function comes from. It tests for quite a lot of things. You seem to want to extend its capability. In that case I would expect you to use this `isEmpty()` function inside your `isDeepEmpty()` function. Why don't you? Please note that **Code Review** is only for code that is _actually working_. It says so in the [How to Ask](https://codereview.stackexchange.com/questions/ask) box, when you ask a question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:38:18.427", "Id": "428583", "Score": "0", "body": "@KIKOSoftware Your comment was very helpful, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:41:46.333", "Id": "428585", "Score": "0", "body": "@M3RS Was that cynical or serious? I can't tell. Perhaps that is the intention? Well, let's assume it was serious. If you have solved your own question you can answer your own question. There's nothing wrong with that. After all, SO is a place for people to learn from others. Your question is still unanswered, so your answer would be welcomed. Don't forget to _review_ your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T07:57:20.520", "Id": "428667", "Score": "0", "body": "No, sorry, it was serious. It was a v good point that maybe I should build this around `lodash.isEmpty()`, so extend it. Also, I understand that the could should be working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T10:22:29.247", "Id": "428682", "Score": "0", "body": "Is an object empty if it contains values that are empty arrays? I suspect @Blindman67 misinterpreted this, since your example loops values of an object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T11:00:47.730", "Id": "428691", "Score": "0", "body": "Arrays are objects, so `Object.values(array)` can be used to loop through array items." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:33:53.923", "Id": "428736", "Score": "2", "body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 2 → 1" } ]
[ { "body": "<h2>Some issues?</h2>\n\n<ul>\n<li><p><code>typeof</code> is not a function. eg <code>typeof(input) === 'object'</code> is written <code>typeof input === 'object'</code></p></li>\n<li><p><code>null</code> is an <code>Object</code> so when you test for an object using <code>typeof</code> you MUST make sure it is not <code>null</code> as well.</p></li>\n<li><p>The test that you comment as <code>// catch null or undefined object</code> will catch any value that evaluates to a falsey, such as <code>false</code>, <code>0</code>, <code>\"\"</code></p></li>\n</ul>\n\n<h2>What is empty?</h2>\n\n<p>As it is unclear what you define as empty so I will make some assumptions, they are arbitrary and may or may not fit your needs.</p>\n\n<ol>\n<li>An array is empty if it contains only empty items.</li>\n<li>An object is empty if it is <code>null</code> or contains no own properties. If it has properties that are <code>null</code> or (defined as) <code>undefined</code> it is not empty.</li>\n<li>A string is empty if it contains no characters</li>\n<li>Empty items are <code>null</code>, <code>undefined</code>, <code>{}</code>, <code>[]</code>, and <code>\"\"</code></li>\n</ol>\n\n<h3>Examples</h3>\n\n<p>Empty</p>\n\n<pre><code>[], \n{}, \n[undefined],\n[null],\n[[], [], []], \n[{},,[],[[[null],[undefined]],[,,,,,]],\nnew Array(10),\nnull,\nundefined,\n\"\"\n</code></pre>\n\n<p>Not empty</p>\n\n<pre><code>[0]\n[{A:null}], \n{A:undefined}, \n[,,,0],\n[[], [], [1]], \n[{},,[],[[[1],[]],[]],\n(new Array(10))[1] = 0,\nfalse,\ntrue,\n\" \",\n</code></pre>\n\n<h2>Rewrite</h2>\n\n<p>With the above assumptions you can rewrite the code as a two functions.</p>\n\n<p>As a non empty object mean we return false, and thus we do not need to iterate its values.</p>\n\n<p>The entry point is <code>isItemEmpty</code> you would call it as you did <code>isDeepEmpty</code> </p>\n\n<pre><code>const isObjEmpty = obj =&gt; obj === null || Object.keys(obj).length === 0;\nconst isItemEmpty = item =&gt; item === undefined || item === \"\" ||\n (Array.isArray(item) &amp;&amp; array.every(isItemEmpty)) ||\n (typeof item === \"object\" &amp;&amp; isObjEmpty(item));\n</code></pre>\n\n<p>Usage</p>\n\n<pre><code>isItemEmpty([{},[],[[]]]); // returns true\nisItemEmpty([{A:0},[],[[]]]); // returns false\nisItemEmpty(\"\"); // returns true\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T02:04:37.930", "Id": "221619", "ParentId": "221589", "Score": "4" } }, { "body": "<p>This is my improved version.</p>\n\n<ul>\n<li>it builds on top of <code>isEmpty()</code></li>\n<li>correctly treats <code>undefined</code> in my test cases (tricky as <code>undefined</code> is not an object unlike <code>null</code>)</li>\n<li><code>isDeepEmpty([0]) = true</code> and return values for other test cases are pretty intuitive </li>\n<li><code>isDeepEmpty(42) = false</code>, but <code>isEmpty(42)</code> behaves the same way</li>\n</ul>\n\n<p>Here:</p>\n\n<pre><code>import isEmpty from 'lodash/fp/isEmpty'\n\nexport function isDeepEmpty(input) {\n if(isEmpty(input)) {\n return true\n }\n if(typeof input === 'object') {\n for(const item of Object.values(input)) {\n // if item is not undefined and is a primitive, return false\n // otherwise dig deeper\n if((item !== undefined &amp;&amp; typeof item !== 'object') || !isDeepEmpty(item)) {\n return false\n }\n }\n return true\n }\n return isEmpty(input)\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:59:42.750", "Id": "221663", "ParentId": "221589", "Score": "1" } }, { "body": "<p><strong>My review</strong></p>\n<ul>\n<li>the presented code is not generic enough to handle what can be considered as an empty value;</li>\n<li>the check <code>if (!input) return true</code> is not robust for all possibile use cases of what can be considered as <code>null</code>, <code>undefined</code>, or empty;</li>\n</ul>\n<p><strong>Alternative solution</strong></p>\n<p>This version, differently that last proposed solution, it avoids to use <code>lodash</code> library, thus recursively calling an <code>empty</code> function (inspired to the PHP <code>empty</code>), that supports as input a empty values list <code>emptyValues</code>, in order to explicitly define what is empty, like <code>[undefined, null, '']</code> or <code>[undefined, null, '', 0]</code>:</p>\n<pre><code>function emptyDeep(mixedVar, emptyValues = [undefined, null, '']) {\n var key, i, len\n for (i = 0, len = emptyValues.length; i &lt; len; i++) {\n if (mixedVar === emptyValues[i]) {\n return true\n }\n }\n if (typeof mixedVar === 'object') {\n for (const item of Object.values(mixedVar)) {\n if (!emptyDeep(item, emptyValues)) {\n return false\n }\n }\n return true\n }\n return false\n}\n</code></pre>\n<p>Examples:</p>\n<pre><code>emptyDeep([{},[],[[]]]);\ntrue\nemptyDeep([{A:0},[],[[]]])\nfalse\nemptyDeep([{A:0},[],[[]]], [undefined, null, '', 0])\ntrue\nemptyDeep({x:[{},[],[[]]]})\ntrue\nemptyDeep(0, [undefined, null, '']);\nfalse\nemptyDeep(0, [undefined, null, '', 0])\ntrue\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-27T08:56:49.433", "Id": "515585", "Score": "1", "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-05-26T17:17:37.523", "Id": "261252", "ParentId": "221589", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T14:30:41.923", "Id": "221589", "Score": "5", "Tags": [ "javascript" ], "Title": "Check if object contains only empty nested objects" }
221589
<p>I'm testing the Stripe payment API. I couldn't find a Python wrapper that provides asynchronous requests so I'm writing one. My first goal was to implement the async equivalent of <a href="https://stripe.com/docs/api/payment_intents/create?lang=python" rel="nofollow noreferrer"><code>stripe.PaymentIntent.create</code></a>. </p> <p>I used <a href="https://aiohttp.readthedocs.io/en/stable/client_quickstart.html" rel="nofollow noreferrer">aiohttp client</a> for my tests. One implementation detail: the Stripe API can take HTTP requests containing tables and maps. They are respectively encoded as <code>"table[]=1,2"</code> and <code>"map[a]=1&amp;map[b]=2"</code>. The aiohttp client doesn't seem to have any rewriting tool for this kind of parameters. I could have passed parameters as key value pairs: <code>params={"table[]": "1,2"}</code> but it seemed a bit ugly to me. Instead I decided to have input parameters of the form <code>params={"table": [1, 2]}</code> and have them automatically translated to their string forms on the fly. The same goes for maps, and <code>{"map": {a:1, b:2}}</code> is automatically translated to <code>"map[a]=1&amp;map[b]=2"</code>.</p> <p>Here is my current implementation: </p> <pre class="lang-py prettyprint-override"><code>import asynctools from aiohttp_params import session_complex_params from aiohttp import client_exceptions import uuid API_KEY = "" # Your Stripe API key ROOT_URL = "https://api.stripe.com/v1/payment_intents" class Stripe(asynctools.AbstractSessionContainer): def __init__(self): super().__init__(raise_for_status=True) async def session_hook(self, session): return session_complex_params(session) @asynctools.attach_session async def create_payment(self, session=None, **kwargs): params = { **kwargs, "payment_method_types": ["card"], "metadata": { "order_id": 6735, }, } async with session.post(ROOT_URL, params=params, headers=stripe_header()) as response: return await response.json() def stripe_header(): return { "Idempotency-Key": str(uuid.uuid4()), "Authorization": f"Bearer {API_KEY}", } async def main(): async with Stripe() as stripe: try: x = await stripe.create_payment(amount="1000" , currency="eur", receipt_email="me@web.com") print(x) except client_exceptions.ClientResponseError as e: print("Error", e) if __name__ == "__main__": import asyncio asyncio.run(main()) </code></pre> <p>The <a href="https://github.com/cglacet/aiohttp-sessions-helpers" rel="nofollow noreferrer"><code>asynctools</code></a> module simply allows to turn a class into an asynchronous aiohttp session manager (by inheriting <code>asynctools.AbstractSessionContainer</code>). Inside the class, the session can be retrieved by any method using the decorator <code>@asynctools.attach_session</code>. </p> <p>It then allows to simply use <code>Stripe</code> as a :</p> <pre class="lang-py prettyprint-override"><code>async with Stripe() as stripe: pass # Unique aiohttp session used for all requests # aiohttp session closed </code></pre> <p>Finally, the code from <code>aiohttp_params</code> is the following:</p> <pre class="lang-py prettyprint-override"><code>def session_complex_params(session): session.post = patch_params(session.post) return session def patch_params(request_method): def decorated_request(*args, **kwargs): try: kwargs["params"] = format_params(kwargs["params"]) except KeyError: pass return request_method(*args, **kwargs) return decorated_request def format_params(params): return '&amp;'.join(format_param(*item) for item in params.items()) def format_param(k, v): if isinstance(v, list): return format_list_param(k, v) if isinstance(v, dict): return format_dict_param(k, v) return format_simple_param(k, v) def format_dict_param(key, dic): return '&amp;'.join(f"{key}[{k}]={str(v)}" for k, v in dic.items()) def format_list_param(key, li): li = map(str, li) return f"{key}[]={','.join(li)}" def format_simple_param(key, value): return f"{key}={value}" </code></pre> <p>Is there anything important missing, or any improvement you think I could add ? Note that I just discovered the Stripe API so there is a good chance I'm not using it properly either. Any comment is welcome. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T14:59:45.280", "Id": "221590", "Score": "4", "Tags": [ "python", "python-3.x", "asynchronous", "e-commerce" ], "Title": "Asynchronous Stripe API and aiohttp parameters formatting" }
221590
<p>I am learning more about python using the book "Automate The Boring Stuff". The problem I completed was "Excel To CSV Converter". I want to kick bad habits to the curb, and make sure I'm learning the best python practices to further my development. I would really appreciate feedback on code efficiency, and code neatness. Is my code PEP-8 compliant? Does it implement all the best practices possible? Thank you in advance, all feedback is appreciated and considered!</p> <pre><code>import openpyxl, csv, os, re, shutil path = os.getcwd() new_path = path + '\\' + 'csv_files' for excel in os.listdir('.'): if not excel.endswith('xlsx'): continue workbook = openpyxl.load_workbook(excel) for sheets in workbook.sheetnames: wb_name = re.sub('.xlsx', '', excel) csv_name = wb_name + '_' + sheets + '.csv' csv_file = open(csv_name, 'w', newline='') csv_writer = csv.writer(csv_file) sheet = workbook.active for row_number in range(1, sheet.max_row + 1): row_info = [] for col_number in range(1, sheet.max_column + 1): data = sheet.cell(row=row_number, column=col_number).value row_info.append(data) csv_writer.writerow(row_info) csv_file.close() shutil.move(os.path.join(path, csv_name), os.path.join(new_path, csv_name)) </code></pre>
[]
[ { "body": "<p>There are a few things you could improve. First, the most important if you want to write Python code that scales to more than a script that does just one thing, you should write functions (or classes). They have the nice feature that you can give them a name, which tells you roughly what they do, and you can give them a <code>docstring</code> which can describe what they do in even more detail.</p>\n\n<hr>\n\n<p><strong>Bug</strong>:</p>\n\n<p>While you do iterate over the sheet names, you do not actually change sheets. <code>workbook.active</code> does not automatically switch to another name. Instead, directly iterate over the workbook.</p>\n\n<hr>\n\n<p>Otherwise here are a few suggestions:</p>\n\n<ul>\n<li><p>Instead of using <code>os.listdir</code>, you can use <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib.Path</code></a>, which has a <code>glob</code> method, to get all excel files in the current directory:</p>\n\n<pre><code>from pathlib import Path\n\nexcel_files = Path(\".\").glob(\"*.xlsx\")\n</code></pre>\n\n<p>This way you also don't have to deal with different path delimiters in Unix and Windows and manually getting the current directory.</p>\n\n<p>Python can also work with relative paths, so no need to get the current directory at all.</p></li>\n<li><p>You should use the <a href=\"https://effbot.org/zone/python-with-statement.htm\" rel=\"nofollow noreferrer\"><code>with</code></a> keyword to ensure that the files you open are closed, even in the event of an exception.</p></li>\n<li><p><code>openpyxl</code> sheets have the attributes <code>rows</code> and <code>columns</code>, which lets you easily iterate over them. You should also learn about <a href=\"https://www.pythonforbeginners.com/basics/list-comprehensions-in-python\" rel=\"nofollow noreferrer\">list comprehensions</a>. In addition, a <code>csv.writer</code> has the <code>writerows</code> method that can take an iterable of rows to write.</p></li>\n<li><p>Using regex just to replace a single string with nothing is overkill. You could just use <a href=\"https://www.w3schools.com/python/ref_string_replace.asp\" rel=\"nofollow noreferrer\"><code>str.replace</code></a>. But here building the string constructively is probably easier. Learn about <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><code>f-string</code>s in Python 3.6+</a>.</p></li>\n<li><p>Instead of moving the file afterwards with <code>shutils</code>, directly save it to the right file.</p></li>\n<li><p>Use a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __ name__ == \"__main__\":</code> guard</a> to allow importing from this script from another script.</p></li>\n</ul>\n\n<p>With these changes your code could become:</p>\n\n<pre><code>import csv\nimport openpyxl\nfrom pathlib import Path\n\ndef convert_all_sheets_to_csv(file_name, target_dir=\".\"):\n \"\"\"Convert all sheets to csv files saved in the folder `target_dir`.\"\"\"\n workbook = openpyxl.load_workbook(file_name)\n out_file_name_template = Path(target_dir) / Path(file_name).stem\n for sheet in workbook:\n out_file_name = f\"{out_file_name_template}_{sheet.title}.csv\"\n convert_sheet_to_csv(sheet, out_file_name)\n\ndef convert_sheet_to_csv(sheet, file_name):\n \"\"\"Convert the content of an excel sheet to a csv file.\"\"\"\n with open(file_name, \"w\") as f:\n writer = csv.writer(f)\n writer.writerows([cell.value for cell in row] for row in sheet.rows)\n\nif __name__ == \"__main__\":\n for excel_file in Path(\".\").glob(\"*.xlsx\"):\n convert_all_sheets_to_csv(excel_file, target_dir=\"csv_files\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T17:08:59.900", "Id": "221596", "ParentId": "221592", "Score": "3" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/users/98493/graipher\">@Graipher</a> already shows you how your code can look like if you follow PEP8. But since you've explicetely mentioned the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide</a>, let's have a look closer look at some parts.</p>\n\n<h2>Imports</h2>\n\n<p>Your import look like this at the moment:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import openpyxl, csv, os, re, shutil\n</code></pre>\n\n<p>Now listen and repeat after PEP8 - <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">Imports</a>:</p>\n\n<blockquote>\n <ul>\n <li>Imports should usually be on separate lines.</li>\n <li><p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and\n constants.</p>\n \n <p>Imports should be grouped in the following order:</p>\n \n <ol>\n <li>Standard library imports.</li>\n <li>Related third party imports.</li>\n <li>Local application/library specific imports.</li>\n </ol>\n \n <p><br/>You should put a blank line between each group of imports.</p></li>\n </ul>\n</blockquote>\n\n<p>Strictly following the Style Guide would lead to something like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import os\nimport re\nimport csv\nimport shutil\n\nimport openpyxl\n</code></pre>\n\n<p>I think it should be quite obvious to see how this would be applied to @Graipher's answer.</p>\n\n<h2>Docstrings</h2>\n\n<p><code>\"\"\"docstrings\"\"\"</code> have not yet found their way into your code, but again @Graipher presents a good execution of their use in his answer. They are also introduced in the Style Guide in section <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">Documentation Strings</a>, and even more detailed in <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP257</a>. Using the syntax as shown by @Graipher and the Style Guide has the nice benefit that Python's built-in <code>help(...)</code> as well as basically all Python IDEs will be able to find it easily. I highly recommend to get used to them, once you're at a point where you work on a program that spreads out over several files, these nifty little lines of documentation (together with an IDE that is able to read them) will likely help you to maintain your mental health.</p>\n\n<h2>Bonus: Automate the Boring Stuff</h2>\n\n<p>Maintaining a consistent, PEP8-compliant style can become tedious, especially on a larger scale. Luckily, there are a lot of good tools to automate the boring stuff for you. First, there are tools like <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">pylint</a>, <a href=\"https://pycodestyle.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">pycodestyle</a>, and <a href=\"http://flake8.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">flake8</a> that can perform style checking on your code. But you can go even further! At the moment, these tools leave fixing the \"issues\" they find in your code to you. Enter tools like <a href=\"https://black.readthedocs.io/\" rel=\"nofollow noreferrer\">black</a> or <a href=\"https://github.com/google/yapf\" rel=\"nofollow noreferrer\">yapf</a>, just to name two of them. They can auto-format your to follow style guidelines, e.g. PEP8. If you use a feature-rich code editor like Visual Studio Code (or Atom - not 100% sure here), they can even perform the task on-the-fly while you're writing code. All<sup>[citation needed]</sup> the tools mentioned above are configurable so you don't have to have to figth windmills if they work against a pet peeve of yours. But often the default configuration will work quite reasonable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T12:27:38.563", "Id": "429205", "Score": "0", "body": "Atom does have ([at least one](https://atom.io/packages/atom-beautify), probably multiple) package for that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T17:58:50.547", "Id": "221599", "ParentId": "221592", "Score": "2" } } ]
{ "AcceptedAnswerId": "221596", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T15:47:44.217", "Id": "221592", "Score": "3", "Tags": [ "python", "excel", "csv", "converting" ], "Title": "Excel To CSV Converter Ch 9 ATBS" }
221592
<p>I wrote this function that will toggle a class of a targeted element. Applying the class <code>js_class_toggle</code> to any element will trigger the function when clicking on it.</p> <p>To define what the target element is and the class you want to toggle is, you have to add <code>data-class-toggle="target_element_id.className"</code> to the element. You can also add this to any element on the page and it will work the same since its targeting the element by its id.</p> <p>For example:</p> <pre><code>&lt;div id="test_element" class="js_class_toggle" data-class-toggle="test_element.className"&gt; This element will have a class toggled &lt;/div&gt; </code></pre> <p>JS:</p> <pre><code>$(document).on("click", ".js_class_toggle", function(e){ //Set variables var element = $(e.currentTarget), elementsClasses = element.attr('data-class-toggle'), elementsClassesSplit = elementsClasses.split('.'), targetElement = elementsClassesSplit[0], targetClass = elementsClassesSplit[1]; //Toggle the class $("#"+targetElement).toggleClass(targetClass); }); </code></pre> <p>Here is a working example of it: <a href="https://jsfiddle.net/fxo1a5w3/2/" rel="nofollow noreferrer">https://jsfiddle.net/fxo1a5w3/2/</a></p> <p>What i will work on next is to be able to have multiple toggles in the same request, for example:</p> <pre><code>&lt;div id="test_element" class="js_class_toggle" data-class-toggle="element1.className2,element2.className2"&gt; This element will have its class toggled &lt;/div&gt; </code></pre> <p>But before that i want to know if there is a better way of doing what i have done so far. The goal is for it to be a function that can be used in any project.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T17:34:14.973", "Id": "428568", "Score": "0", "body": "I like the idea but I wonder what added value a small framework around toggleClass could provide. Maybe your extended framework would clarify this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T17:58:43.727", "Id": "428570", "Score": "0", "body": "Sorry i don't understand exactly what you mean, are you asking how i am using this code in my actual project?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T18:00:19.020", "Id": "428571", "Score": "0", "body": "I am more interested to see your extended API with support for multiple class toggles. This simple API you have so far doesn't show me the potential of your API yet :)" } ]
[ { "body": "<h2>Suggestions for simplifying</h2>\n\n<blockquote>\n<pre><code>elementsClasses = element.attr('data-class-toggle'),\n</code></pre>\n</blockquote>\n\n<p>There's a jQuery method for simplifying that: <a href=\"https://api.jquery.com/data\" rel=\"nofollow noreferrer\"><code>.data()</code></a>. It only allows typing five fewer characters:</p>\n\n<pre><code>elementsClasses = element.data('class-toggle')\n</code></pre>\n\n<hr>\n\n<p>The click handler registration could be simplified from</p>\n\n<blockquote>\n<pre><code>$(document).on(\"click\", \".js_class_toggle\", function(e){\n</code></pre>\n</blockquote>\n\n<p>to:</p>\n\n<pre><code>$('.js_class_toggle').click(function(e){\n</code></pre>\n\n<hr>\n\n<p>If you utilize <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged &#39;ecmascript-6&#39;\" rel=\"tag\">ecmascript-6</a> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring\" rel=\"nofollow noreferrer\">Array destructuring assignment</a>, then the following three lines could be simplified:</p>\n\n<blockquote>\n<pre><code>elementsClassesSplit = elementsClasses.split('.'),\ntargetElement = elementsClassesSplit[0],\ntargetClass = elementsClassesSplit[1];\n</code></pre>\n</blockquote>\n\n<p>To a single line:</p>\n\n<pre><code>[targetElement, targetClass] = elementsClasses.split('.')\n</code></pre>\n\n<p>Though make sure you are aware of the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Browser_compatibility\" rel=\"nofollow noreferrer\">Browser support</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T17:58:01.553", "Id": "428569", "Score": "0", "body": "Right, i forgot about .data()! I used the .on() function because if an element is loaded through ajax that should have this functionality, this function wont work on it (as far as i know and have tested) because that element would have been loaded after the document has loaded. Anywhere i read about this says to use .on instead of .click, but maybe i'm/they`re wrong. And i didn't know that last suggestion exists! I'll update my code and see how its going after that. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T17:48:46.983", "Id": "221598", "ParentId": "221597", "Score": "2" } }, { "body": "<p>You can access the data element via <code>dataset</code> property and camelCase data name</p>\n\n<pre><code>const data = element.dataset.classToggle;\n</code></pre>\n\n<p>You can add a click event to the document as follows that will only do something if the target is class <code>js_class_toggle</code></p>\n\n<pre><code>const togClass = `.js_class_toggle`;\n\naddEventListener(\"click\", e =&gt; {\n if (e.target.classList.contains(togClass)) {\n /* ...do stuff... */\n }\n}\n</code></pre>\n\n<p>Or you can add a click to each element containing the class.</p>\n\n<pre><code>document.querySelectorAll(togClass).forEach(el =&gt; el.addEventListener(\"click\", toggleClick));\n</code></pre>\n\n<p>By the looks you are toggling the class on the element that is clicked so there is no need to add the reference</p>\n\n<pre><code>&lt;div class=\"js_class_toggle toggle-me\" data-class-toggle=\"toggle-me\"&gt;\n This element will have a class toggled\n&lt;/div&gt;\n</code></pre>\n\n<p>making the function to toggle very simple</p>\n\n<pre><code>function toggleClick(e) {\n e.target.classList.toggle(e.target.dataset.classToggle);\n}\n</code></pre>\n\n<p>To include the reference id you can make the data JSON like</p>\n\n<pre><code>&lt;div id = \"foo\" class=\"js_class_toggle toggle-me\" \n data-class-toggle='{\"query\": \"#foo\", \"toggleClass\": \"toggle-me\"}'&gt;\n This element will have a class toggled\n&lt;/div&gt;\n</code></pre>\n\n<p>Then the function becomes</p>\n\n<pre><code>function toggleClick(e) {\n const data = JSON.parse(e.target.dataset.classToggle);\n const el = document.querySelector(data.query);\n if (el) { el.classList.toggle(data.toggleClass) }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T18:08:53.167", "Id": "428745", "Score": "0", "body": "Thanks for the feedback! I actually use this code for toggling other elements classes too. For example, i have a button that when you click on it, a form loads on to the page, the form loads in place of another element that says \"start typing\". clicking on either the button or the \"start typing\" element, will give the \"start typing\" element a class that will show a loading indicator. So when i click on either that element, or on the button, i want that loader to show. I also add another class to the actual button when clicking on it. So i toggle 2 classes for 2 different elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T18:10:49.360", "Id": "428746", "Score": "0", "body": "And i actually did just convert the code to use JSON instead of what i had before, and with the suggestions of some i managed to reduce the amount of code in the function as well as make it simpler. So yes to the JSON suggestion!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T02:52:34.793", "Id": "221620", "ParentId": "221597", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T17:21:57.507", "Id": "221597", "Score": "3", "Tags": [ "javascript", "jquery", "html", "event-handling", "dom" ], "Title": "jQuery dynamic toggle class function" }
221597
<p><strong>Overview</strong></p> <p>I am constructing a Graph with randomly generated nodes called <code>Position</code>s. The Graph has a width and a height and is represented using an adjacency list <code>std::map&lt;std::pair&lt;int, int&gt;, mrrobo::Position&gt; m_maze;</code>, that are open, closed, and may not have a route back to the root. I want to find a single path to the Position with an x value of width - 1 of and y value of height - 1, the end of the maze. If not possible I return an empty array. Also, the generation of the maze Positions is handled by a function managed by another developer namespace called <code>bool otherns::generate_postion(int x, int y)</code> so that's abstracted and given to my code in an assumed valid state.</p> <p>The primary feedback I'm looking for is with my implementation of graph search in <code>Graph::search()</code>. As well as how I determine <code>possible_edge = { {x, y-1}, {x-1, y}, {x+1, y}, {x, y+1} }</code> in my <code>Graph::get_position_edges()</code> function. Using C++17 features I want to find ways to optimize this graph search if possible.</p> <p><strong>Main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include "graph.cpp" int main() { mrrobo::Graph graph; std::cout &lt;&lt; "width: " &lt;&lt; graph.width() &lt;&lt; '\n'; std::cout &lt;&lt; "height: " &lt;&lt; graph.height() &lt;&lt; '\n'; graph.get_position_edges(); graph.search(); return 0; } </code></pre> <p><strong>Graph.h</strong></p> <pre><code>#ifndef GRAPH_H #define GRAPH_H #include &lt;cstring&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;queue&gt; #include &lt;stack&gt; #include &lt;string&gt; #include &lt;utility&gt; #include &lt;vector&gt; #include &lt;stdio.h&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;map&gt; namespace mrrobo { struct Position { int x; int y; bool is_open; bool is_visited; std::vector&lt;Position&gt; edges; }; class Graph { private: int m_height; int m_width; public: Graph(); std::map&lt;std::pair&lt;int, int&gt;, mrrobo::Position&gt; m_graph; int width(); int height(); void get_position_edges(); void search(); }; } #endif /* GRAPH_H */ </code></pre> <p><strong>Graph.cpp</strong></p> <pre><code>#include "graph.h" mrrobo::Graph::Graph() { otherns::set_width_and_height(); } int mrrobo::Graph::width() { return m_width; } int mrrobo::Graph::height() { return m_height; } void mrrobo::Graph::get_position_edges() { std::ostringstream oss; std::vector&lt;std::pair&lt;int, int&gt;&gt; open_postions; mrrobo::Position p; p.is_visited = false; for (int y = 0; y &lt; m_height; ++y) { for (int x = 0; x &lt; m_width; ++x) { bool result = otherns::generate_postion(x,y); if(result) { p.is_open = true; m_graph.insert( {{x,y}, p} ); open_postions.push_back({x,y}); oss &lt;&lt; "○ "; } else { p.is_open = false; m_graph.insert( {{x,y}, p} ); oss &lt;&lt; "● "; } } oss &lt;&lt; '\n'; } std::cout &lt;&lt; '\n' &lt;&lt; oss.str() &lt;&lt; '\n'; for(int n=0; n &lt; open_postions.size(); ++n) { int x = open_postions[n].first; int y = open_postions[n].second; std::vector&lt;std::pair&lt;int, int&gt;&gt; possible_edge = { {x, y-1}, {x-1, y}, {x+1, y}, {x, y+1} }; for(int i=0; i &lt; possible_edge.size(); ++i) { int x_edge = possible_edge[i].first; int y_edge = possible_edge[i].second; if((x_edge &gt; -1 &amp;&amp; x_edge &lt; m_width + 1) &amp;&amp; (y_edge &gt; -1 &amp;&amp; y_edge &lt; m_height + 1) &amp;&amp; m_graph[{x_edge, y_edge}].is_open) { m_graph[{x,y}].edges.push_back( {x_edge, y_edge} ); } } } } void mrrobo::Graph::search() { std::stack&lt;std::pair&lt;int,int&gt;&gt; reversed_path; int x = 0; int y = 0; bool dead_end = true; if(m_graph[{x,y}].is_open) { reversed_path.push({x,y}); while((x &lt; m_width || y &lt; m_height) &amp;&amp; !reversed_path.empty()) { if(x == m_width - 1 &amp;&amp; y == m_height - 1) { m_graph[{x,y}].is_visited = true; reversed_path.push({x,y}); break; } dead_end = true; for(auto edge : m_graph[{x,y}].edges) { if(m_graph[{edge.x,edge.y}].is_open &amp;&amp; m_graph[{edge.x,edge.y}].is_visited == false) { m_graph[{x,y}].is_visited = true; reversed_path.push({x,y}); x = edge.x; y = edge.y; dead_end = false; break; } } if(dead_end) { m_graph[{x,y}].is_visited = true; x = reversed_path.top().first; y = reversed_path.top().second; reversed_path.pop(); } } } std::stringstream solution_stream; if(reversed_path.empty()) { solution_stream &lt;&lt; "[]"; } else { std::stack&lt;std::pair&lt;int,int&gt;&gt; path; while(reversed_path.empty() == false) { path.push(reversed_path.top()); reversed_path.pop(); } solution_stream &lt;&lt; '['; path.pop(); while(path.empty() == false) { x = path.top().first; y = path.top().second; if(x != m_width - 1 || y != m_width - 1) { solution_stream &lt;&lt; "{\"x\": " &lt;&lt; x &lt;&lt; ", \"y\": " &lt;&lt; y &lt;&lt; "}, "; } else { solution_stream &lt;&lt; "{\"x\": " &lt;&lt; x &lt;&lt; ", \"y\": " &lt;&lt; y &lt;&lt; "}"; } path.pop(); } solution_stream &lt;&lt; ']'; } std::cout &lt;&lt; solution_stream.str() &lt;&lt; '\n'; } </code></pre> <p><strong>Sample output</strong></p> <pre><code>width: 6 height: 6 ○ ○ ● ○ ○ ○ ○ ● ○ ● ● ○ ○ ● ○ ● ● ● ○ ○ ○ ○ ○ ○ ● ● ● ● ● ○ ○ ○ ○ ○ ○ ○ [{"x": 0, "y": 0}, {"x": 0, "y": 1}, {"x": 0, "y": 2}, {"x": 0, "y": 3}, {"x": 1, "y": 3}, {"x": 2, "y": 3}, {"x": 3, "y": 3}, {"x": 4, "y": 3}, {"x": 5, "y": 3}, {"x": 5, "y": 4}, {"x": 5, "y": 5}] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:33:39.773", "Id": "428581", "Score": "1", "body": "`mrrobo::Garph graph;` Does this really work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:37:03.657", "Id": "428582", "Score": "0", "body": "Yes is there a syntax error here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:38:53.903", "Id": "428584", "Score": "0", "body": "No, just a typo: `Garph`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:42:53.343", "Id": "428586", "Score": "0", "body": "Fixed it, must have been a copy paste error when formatting the code" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:18:29.790", "Id": "221605", "Score": "3", "Tags": [ "c++", "graph", "c++17" ], "Title": "Graph Search in C++17" }
221605
<p>I often use the Index Match function in daily reporting tasks. I was looking for a quicker way to utilize Index Match, as I find the formula cumbersome to enter. I ended up creating a userform that allows you to pull columns using Index Match between sheets in your open workbooks. </p> <p>You can download the userform files <a href="https://drive.google.com/drive/folders/1YwbFsFNLCnwYSXjeXfN56pDs4W1UFXKQ?usp=sharing" rel="nofollow noreferrer">here</a> and a macro which launches the form <a href="https://drive.google.com/file/d/13kgvPrGpoyMqG6nSFxdmumqi2GjxMCcj/view?usp=sharing" rel="nofollow noreferrer">here</a>. Simply download these files to your computer and import them into your personal macro workbook to use the userform pictured below: <a href="https://i.stack.imgur.com/8d7I2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8d7I2.png" alt="enter image description here"></a></p> <p>After some back and forth I decided to only accommodate Excel sheets with data beginning in the first row and first column (as indicated in the text box pictured in the interface). I had debated adding additional controls to adjust first rows and columns, but found this only helped me in limited situations and cluttered the interface.</p> <p>I welcome any feedback on this userform as a concept as well as the relevant code which I have included below. This is a work in progress, so there are certainly some inconsistencies in the code below which I am working to address. With any luck this userform is helpful to anyone tasked with lots of vlookups, Index Matching, etc. </p> <p>Cheers,</p> <p>Peter</p> <pre><code>Public wb As Workbook Public ws As Worksheet Public SrcWbNm As String Public TargWbNm As String Public SrcShtNm As String Public TargShtNm As String Public strName As String Public SourceIDcol As Integer Public TargIDcol As Integer 'Peter Domanico, May 2019 Private Sub UserForm_Initialize() 'Declare variables and data types Dim i As Single, j As Single 'Go through open workbooks and add names to comboboxes For j = 1 To Workbooks.Count If Workbooks(j).Name &lt;&gt; "PERSONAL.XLSB" Then Me.CB_SourceWB.AddItem Workbooks(j).Name Me.CB_TargetWB.AddItem Workbooks(j).Name End If Next j 'if only 1 workbook open, set as default value for comboboxes If Me.CB_SourceWB.ListCount = 1 Then Me.CB_SourceWB.Text = Me.CB_SourceWB.List(0) If Me.CB_TargetWB.ListCount = 1 Then Me.CB_TargetWB.Text = Me.CB_TargetWB.List(0) End Sub Private Sub CB_SourceWB_Change() SrcWbNm = Me.CB_SourceWB.Text Set wb = Workbooks(SrcWbNm) Me.CB_SourceSheet.Clear For Each ws In wb.Worksheets strName = ws.Name Me.CB_SourceSheet.AddItem strName Next 'if only 1 worksheet in workbook, set as default value for comboboxes If Me.CB_SourceSheet.ListCount = 1 Then Me.CB_SourceSheet.Text = Me.CB_SourceSheet.List(0) End Sub Private Sub CB_TargetWB_Change() TargWbNm = Me.CB_TargetWB.Text Set wb = Workbooks(TargWbNm) Me.CB_TargetSheet.Clear For Each ws In wb.Worksheets strName = ws.Name Me.CB_TargetSheet.AddItem strName Next 'if only 1 worksheet in workbook, set as default value for comboboxes If Me.CB_TargetSheet.ListCount = 1 Then CB_TargetSheet.Text = CB_TargetSheet.List(0) End Sub Private Sub CB_SourceSheet_Change() SrcWbNm = Me.CB_SourceWB.Text SrcShtNm = Me.CB_SourceSheet.Text Me.CB_SourceID.Clear Me.LB_SourceColumns.Clear Select Case SrcShtNm Case Is = "" GoTo WeOut Case Else Set wb = Workbooks(SrcWbNm) Set ws = wb.Worksheets(SrcShtNm) LastColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column For i = 1 To LastColumn Me.CB_SourceID.AddItem ws.Cells(1, i).Text Me.LB_SourceColumns.AddItem ws.Cells(1, i).Text Next i End Select WeOut: End Sub Private Sub CB_TargetSheet_Change() TargWbNm = Me.CB_TargetWB TargShtNm = Me.CB_TargetSheet Me.CB_TargetID.Clear Select Case TargShtNm Case Is = "" GoTo WeOut Case Else Set wb = Workbooks(TargWbNm) Set ws = wb.Worksheets(TargShtNm) LastColumn = ws.Cells(1, Columns.Count).End(xlToLeft).Column For i = 1 To LastColumn Me.CB_TargetID.AddItem ws.Cells(1, i).Text Next i End Select WeOut: End Sub Private Sub CB_SourceID_Change() SourceIDcol = Me.CB_SourceID.ListIndex + 1 End Sub Private Sub CB_TargetID_Change() TargIDcol = Me.CB_TargetID.ListIndex + 1 End Sub Private Sub CBTN_Pull_Columns_Click() 'performance With Application .ScreenUpdating = False .EnableEvents = False .Calculation = xlCalculationManual End With 'dims Dim SourceWb As Workbook Set SourceWb = Workbooks(SrcWbNm) Dim TargWb As Workbook Set TargWb = Workbooks(TargWbNm) Dim SrcWs As Worksheet Set SrcWs = SourceWb.Worksheets(SrcShtNm) Dim TargWs As Worksheet Set TargWs = TargWb.Worksheets(TargShtNm) LastSrc = SrcWs.Cells(Rows.Count, SourceIDcol).End(xlUp).Row LastTarg = TargWs.Cells(Rows.Count, TargIDcol).End(xlUp).Row NextTargCol = TargWs.Cells(1, Columns.Count).End(xlToLeft).Column + 1 Dim ValuesToPull As Range, TargetIDs As Range, SourceIDs As Range, MyRange As Range 'count number of select items in LB_SourceColumns Dim SelCt As Integer For i = 0 To LB_SourceColumns.ListCount - 1 If LB_SourceColumns.Selected(i) = True Then SelCt = SelCt + 1 Next i Select Case SelCt Case Is = 0 MsgBox "No source columns selected!", vbCritical, "!!!" GoTo CleanExit End Select 'create array of columns from LB_SourceColumns Dim arr() As Variant ReDim arr(1 To SelCt) j = 1 For i = 0 To LB_SourceColumns.ListCount - 1 If LB_SourceColumns.Selected(i) = True Then arr(j) = i + 1 j = j + 1 End If Next i 'set ranges for use in Index Match With SrcWs Set SourceIDs = .Range(.Cells(1, SourceIDcol), .Cells(LastSrc, SourceIDcol)) End With With TargWs Set TargetIDs = .Range(.Cells(1, TargIDcol), .Cells(LastTarg, TargIDcol)) End With 'perform Index Match For i = LBound(arr) To UBound(arr) With SrcWs Set ValuesToPull = .Range(.Cells(1, arr(i)), .Cells(LastSrc, arr(i))) End With With TargWs Set MyRange = .Range(.Cells(1, NextTargCol), .Cells(LastTarg, NextTargCol)) End With MyRange = Application.index(ValuesToPull, Application.Match(TargetIDs, SourceIDs, 0)) TargWs.Cells(1, NextTargCol) = SrcWs.Cells(1, arr(i)) '&lt;~copy header from source sheet NextTargCol = NextTargCol + 1 Next i 'formatting TargWb.Activate With TargWs .Columns.AutoFit .Activate End With 'performance With Application .ScreenUpdating = True .EnableEvents = True .Calculation = xlCalculationAutomatic .StatusBar = Ready End With CleanExit: End Sub Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) If CloseMode = 0 Then Dim ans As VbMsgBoxResult ans = MsgBox("Are you sure you want to exit?", vbYesNo, "???") If ans = vbYes Then GoTo CleanExit Else Cancel = True End If CleanExit: End Sub </code></pre>
[]
[ { "body": "<blockquote>\n <p>I often use the Index Match function in daily reporting tasks. I was\n looking for a quicker way to utilize Index Match, as I find the\n formula cumbersome to enter.</p>\n</blockquote>\n\n<p>However, a quick look at the form, implementing it into any workbook/application will be cumbersome and any user has to perform many steps - most accomplished Excel users will complete and auto-fill an INDEX/MATCH series in the time it would take to load and complete the form!</p>\n\n<p>Your logic and general flow requires review - I am not going to go through it all. Try to understand your decision points and how this flows through each step. Break things down into helper functions if required. It looks like you coded this on the run and have not done your own review.</p>\n\n<p>As an example, let us take the last event handler:</p>\n\n<pre><code>Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)\n If CloseMode = 0 Then\n Dim ans As VbMsgBoxResult\n ans = MsgBox(\"Are you sure you want to exit?\", vbYesNo, \"???\")\n If ans = vbYes Then GoTo CleanExit Else Cancel = True\n End If\nCleanExit:\nEnd Sub\n</code></pre>\n\n<p>Firstly, anytime you use <code>GoTo</code> you raise a huge code stink. Flag it, review it! And then work out if your really need it. I doubt you ran through this routine in your mind because the last effective statement in the code says to go to the next line!</p>\n\n<p>You also assign a Boolean in a complicated way. Let me rewrite this one for you:</p>\n\n<pre><code>Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)\n If CloseMode = 0 Then\n Dim ans As VbMsgBoxResult\n ans = MsgBox(\"Are you sure you want to exit?\", vbYesNo, \"???\")\n Cancel = Not (ans = vbYes)\n End If\nEnd Sub\n</code></pre>\n\n<p>Oh, and <code>Option Explicit</code> at the top of modules, always. Not sure if you have used it in this case. </p>\n\n<p>You haven't provided an example of how the results of the form would be used. Why so many public variables - the easy approach is to create a public property that returns a string that can be put into a formula property of a range.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T21:24:05.653", "Id": "221612", "ParentId": "221606", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:22:46.000", "Id": "221606", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Excel VBA Userform to assist in the use of Index Match function" }
221606
<p>I'm trying to create a very basic compiler, and I'm working on the lexer. I decided to store keywords and operators in an unordered_set, and use regex to match identifiers and literals (no comments yet).</p> <p><strong>Tokens.h</strong></p> <pre><code>#ifndef TOKENS_H #define TOKENS_H #include&lt;unordered_set&gt; #include&lt;string&gt; namespace AVSL { enum class TokenType { Identifier, Keyword, String, Literal, Comment, Operator, Delim }; static const std::unordered_set&lt;std::string&gt; keywords = { "var", "for", "while", "print", "constant"}; static const std::unordered_set&lt;std::string&gt; operators = { "+", "-", "*", "/", "=", "==", "+=", "-=", "*=", "/=" }; static const std::unordered_set&lt;char&gt; delims = { '(', ')', ';' }; static const std::unordered_set&lt;char&gt; whitespace = { '\n', '\r', '\t', ' ' }; struct Token { std::string tokenValue; TokenType tokenType; Token() = delete; Token(const std::string&amp; tokenValue_, TokenType tokenType_): tokenValue(tokenValue_), tokenType(tokenType_){ /* empty */ } Token(const Token&amp; token): tokenValue(token.tokenValue), tokenType(token.tokenType) { /* empty */ } }; } #endif </code></pre> <p><strong>Lexer.h</strong></p> <pre><code>#ifndef LEXER_H #define LEXER_H #include "Tokens.h" using LineNo = unsigned int; namespace AVSL { std::vector&lt;Token&gt; Tokenize(std::string filename); Token getToken(std::string buffer, LineNo line); } #endif </code></pre> <p><strong>Lexer.cpp</strong></p> <pre><code>#include "Lexer.h" #include&lt;fstream&gt; #include&lt;iostream&gt; #include&lt;regex&gt; namespace AVSL { Token getToken(std::string buffer, LineNo line) { if (operators.find(buffer) != operators.end()) { return Token(buffer, TokenType::Operator); } else if (keywords.find(buffer) != keywords.end()) { return Token(buffer, TokenType::Keyword); } std::regex iden("[a-zA-Z][a-zA-Z0-9_]*"); std::regex str("\".*\""); std::regex lit("^[0-9]+$"); //std::regex; if (std::regex_match(buffer, iden)) { return Token(buffer, TokenType::Identifier); } if (std::regex_match(buffer, str)) { return Token(buffer, TokenType::String); } if (std::regex_match(buffer, lit)) { return Token(buffer, TokenType::Literal); } /* No support for comments yet*/ /* Will only reach here if all else fails, invalid string */ std::cout &lt;&lt; "Invalid expression at line number " &lt;&lt; line &lt;&lt; " : " &lt;&lt; buffer; std::cin.get(); exit(0); } std::vector&lt;Token&gt; Tokenize(std::string filename) { std::ifstream file(filename, std::ios::in); if (file.fail()) { std::cout &lt;&lt; "Unable to open file!\n"; std::cin.get(); exit(0); } LineNo line = 1; std::string buffer = ""; char ch; std::vector&lt;Token&gt; tokens; while (file &gt;&gt; std::noskipws &gt;&gt; ch) { if (ch == '\n' || ch == '\r') line += 1; if (delims.find(ch) != delims.end()) { if (buffer != "") { tokens.push_back(getToken(buffer, line)); buffer = ""; } tokens.push_back(Token(std::string(1, ch), TokenType::Delim)); continue; } else if (whitespace.find(ch) != whitespace.end()) { if (buffer != "") { tokens.push_back(getToken(buffer, line)); buffer = ""; } continue; } else { buffer += ch; } } //std::cout &lt;&lt; line &lt;&lt; "\n"; return tokens; } } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include "Tokens.h" #include "Lexer.h" #include&lt;iostream&gt; #include&lt;unordered_map&gt; #include&lt;fstream&gt; int main(int argc, char** argv) { std::unordered_map&lt;AVSL::TokenType, std::string&gt; tokenMap = { {AVSL::TokenType::Keyword, "Keyword"}, {AVSL::TokenType::Identifier, "Identifier"}, {AVSL::TokenType::Operator, "Operator"}, {AVSL::TokenType::Literal, "Literal"}, {AVSL::TokenType::Delim, "Delim" } }; auto vec = AVSL::Tokenize("dummy.txt"); for (auto x : vec) { std::cout &lt;&lt; x.tokenValue &lt;&lt; "-&gt;" &lt;&lt; tokenMap.find(x.tokenType)-&gt;second &lt;&lt; "\n"; } std::cin.get(); return 0; } </code></pre> <p>The lexer works fine so far. On a dummy file: <code>var i = 42;</code> It prints out:</p> <pre><code>var-&gt;Keyword i-&gt;Identifier =-&gt;Operator 42-&gt;Literal ;-&gt;Delim </code></pre> <p>Also, on invalid inputs, it will print out the line number and invalid string:</p> <pre><code>var i = 42; i += 2a; </code></pre> <p><code>Invalid expression at line number 5 : 2a</code></p> <p>Any advice/comments would be appreciated. I'm mostly concerned of error handling. Right now, all it does is print to stdout and exit the program. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:57:31.573", "Id": "428589", "Score": "0", "body": "I'm afraid the regex approach will get back at you once you start using escape sequences, literal escapes, quoting, etc. => str = \"my \\\"quoted\\\" string\" or \\u0022my string started with an escape sequence\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T21:36:34.463", "Id": "428619", "Score": "3", "body": "Welcome to Code Review! Great first question! Not only is the code clear, and the title good, but you've also done a good job of showing the context with an example. I look forward to seeing more good questions from you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T22:39:52.223", "Id": "428623", "Score": "0", "body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 2 → 1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T00:29:12.453", "Id": "428630", "Score": "3", "body": "I would look into how to use Lex/Bison most of this can be done automatically with the correct tools." } ]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Use all required <code>#include</code>s</h2>\n\n<p>The <code>Lexer.h</code> file uses <code>std::string</code> and <code>std::vector</code> as part of its interface, but does not include <code>&lt;vector&gt;</code> at all, and only indirectly includes <code>&lt;string&gt;</code> because that's part of <code>Tokens.h</code>. I'd recommend explicitly putting both <code>&lt;vector&gt;</code> <em>and</em> <code>&lt;string&gt;</code> in <code>Lexer.h</code> so that if, for example, one wanted to alter the interface for <code>Token</code> to not use <code>std::string</code>, this file would still remain the same.</p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>In this program's <code>main()</code>, <code>argc</code>, <code>argv</code> are unused and should be eliminated from the program. Or perhaps use the next suggestion instead.</p>\n\n<h2>Allow the user to specify input file</h2>\n\n<p>The file names are currently hardcoded which certainly greatly restricts the usefulness of the program. Consider using <code>argc</code> and <code>argv</code> to allow the user to specify file names on the command line. </p>\n\n<h2>Consider allowing a <code>std::istream</code> parameter for input</h2>\n\n<p>As it stands, the <code>Tokenize()</code> function is only capable of reading its input from a file with the passed name, but not, say, <code>std::cin</code> or any other stream. Instead of handling file I/O there, change it to take a <code>std::istream &amp;</code>. This makes the function much more flexible and also somewhat smaller and simpler.</p>\n\n<h2>Keep associated things closer together</h2>\n\n<p>Right now there is an <code>AVSL::TokenTyp::Keyword</code> and an <code>unordered_map</code> that contains the string \"Keyword\" and a list of <code>keywords</code> and then part of the parser also looks for those. They are literally spread out over all files. Keeping associated things together is exactly a job for an object. First, I'd rename <code>TokenType</code> to <code>Type</code> and put it inside <code>struct Token</code> so now we have <code>Token::Type</code> everywhere that <code>TokenType</code> is currently used. Next, we could create a more generic <code>Classifier</code> class:</p>\n\n<pre><code>class Classifier {\npublic:\n Classifier(Token::Type ttype, std::string name, std::unordered_set&lt;std::string&gt; tokens) :\n my_type{ttype},\n my_name{name},\n my_tokens{tokens}\n {}\n bool among(const std::string&amp; word) const { return my_tokens.find(word) != my_tokens.end(); }\n Token::Type type() const { return my_type; }\nprivate:\n Token::Type my_type;\n std::string my_name;\n std::unordered_set&lt;std::string&gt; my_tokens;\n};\n\nstatic const std::vector&lt;Classifier&gt; classifiers {\n { Token::Type::Keyword, \"Keyword\", { \"var\", \"for\", \"while\", \"print\", \"constant\"} },\n { Token::Type::Operator, \"Operator\", { \"+\", \"-\", \"*\", \"/\", \"=\", \"==\", \"+=\", \"-=\", \"*=\", \"/=\" } },\n};\n</code></pre>\n\n<p>Now the first part of <code>getToken</code> could look like this:</p>\n\n<pre><code>for (const auto &amp;thing : classifiers) {\n if (thing.among(buffer)) {\n return Token(buffer, thing.type());\n }\n}\n</code></pre>\n\n<p>Alternatively, one could include a function in the <code>Token</code> class that would emit the type name for printing. If you have C++17, I'd suggest returning a <code>std::string_view</code> for that purpose.</p>\n\n<h2>Wrap the regex operations into classes</h2>\n\n<p>It's not too difficult to imagine how, like the basic static <code>Classifier</code> object above, one could use a slightly more sophisticated version to employ a <code>std::regex</code>. If you have both kinds of classifiers derive from the same base object, then even more goodness can happen because now your code is <em>data-driven</em> which makes things easier to maintain and to understand.</p>\n\n<h2>Use a standard tool instead</h2>\n\n<p>There are a lot of inefficiencies with the current code. For one thing, the same buffer is scanned many times in trying to find a match. This is very inefficient and will make a big difference with larger files or more complex lexers. I'd recommend instead using <a href=\"https://en.wikipedia.org/wiki/Flex_(lexical_analyser_generator)\" rel=\"nofollow noreferrer\"><code>flex++</code></a> instead to create a lexer which is both very easy to maintain and read and also very efficient and fast.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T22:30:10.773", "Id": "428621", "Score": "0", "body": "Thanks! I've thought a lot about utilizing Flex or some other parser generator, but this project is purely for my own academic interests and for such a lightweight \"language\", it seems overkill. Maybe if I do decide to implement more features, I might use something like that. \nAlso, I really liked the idea of using `Classifier` class, and I might do something like that. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T22:55:36.797", "Id": "428627", "Score": "2", "body": "In my experience, the time invested in learning how to use `flex` and `bison` **far** outweighed the time spent creating my own lexers and parsers in terms of value received for time spent. The latest releases of both have much improved C++ interfaces and facilities, so if you'd looked at them before but didn't spend time on them because they seemed very C-centric, it may well be worth another look." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T23:21:12.320", "Id": "428628", "Score": "0", "body": "Then I might look into them. Thanks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T21:34:54.837", "Id": "221614", "ParentId": "221608", "Score": "8" } } ]
{ "AcceptedAnswerId": "221614", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:46:57.457", "Id": "221608", "Score": "6", "Tags": [ "c++", "lexer" ], "Title": "Lexer using C++ and Regex" }
221608
<p>I currently have a dictionary (<code>Duplicate_combos</code>) that has a unique identifying number for the key value and the value is a list with two elements, a company code and then either a yes or no (both of these values are currently stored as strings). I am essentially just trying to see where the company code is equal and the second term is no for both. So if this was my dictionary:</p> <pre><code>{1234: ['123' , 'No'] , 1235:['123', 'No'], 1236: ['123','Yes'], 1237: [124,'No']} </code></pre> <p>I would only want to return 1234 and 1235. The code below is what I currently have and I really need to optimize it because while it does work when I tested it on a small data set, I will need to use it on a much larger one (43,000 lines) and in early testing, it is taking 45+ minutes with seemingly no sign of ending soon.</p> <pre><code>def open_file(): in_file = open("./Data.csv","r") blank = in_file.readline() titles = in_file.readline() titles = titles.strip() titles = titles.split(',') cost_center = [] # 0 cost_center_name = []# 1 management_site = [] # 15 sub_function = [] #19 LER = [] #41 Company_name = [] #3 Business_group = [] #7 Value_center = [] #9 Performance_center = [] #10 Profit_center = [] #11 total_lines = {} for line in in_file: line = line.strip() line = line.split(',') cost_center.append(line[0]) cost_center_name.append(line[1]) management_site.append(line[15]) sub_function.append(line[19]) LER.append(line[41]) Company_name.append(line[3]) Business_group.append(line[7]) Value_center.append(line[9]) Performance_center.append(line[10]) Profit_center.append(line[11]) # create a dictionary of all the lines with the key being the unique cost center number (cost_center list) total_lines[line[0]] = line[1:] return(cost_center, cost_center_name, management_site, sub_function, LER, Company_name, Business_group, total_lines, titles, Value_center, Performance_center, Profit_center) def find_duplicates(Duplicate_combos): Real_duplicates = [] archive_duplicates = [] # loop through the dictionary of duplicate combos by the keys for key in Duplicate_combos: code = Duplicate_combos[key][0] for key2 in Duplicate_combos: # if the two keys are equal to each other, it means you are comparing the key to itself, which we don't want to do so we continue if key == key2: continue # if the company codes are the same and they are BOTH NOT going to be consolidated, we have found a real duplicate elif Duplicate_combos[key2][0] == code and Duplicate_combos[key2][1] == 'No' and Duplicate_combos[key][1] == 'No': # make sure that we haven't already dealt with this key before if key not in archive_duplicates: Real_duplicates.append(key) archive_duplicates.append(key) if key2 not in archive_duplicates: Real_duplicates.append(key2) archive_duplicates.append(key2) continue return(Real_duplicates) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:57:45.713", "Id": "428590", "Score": "1", "body": "Where does the data for `Duplicate_combos` come from? The right performance fix would likely involve putting that data into a more appropriate data structure for this task." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T20:00:31.140", "Id": "428593", "Score": "0", "body": "The data comes from a csv file that I read in as part of earlier functions. Based on when I have been running it, this function seems to be the one that is taking significantly longer to run" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T20:09:01.243", "Id": "428595", "Score": "0", "body": "In that case, I recommend including the CSV-reading code, as well as an excerpt from the CSV file, so that we can give you the proper advice. Also, please fix your indentation. One easy way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T20:17:59.103", "Id": "428596", "Score": "0", "body": "I added the open file function, a lot of the stuff that is returned is used elsewhere so idk if it helps at all. As for the data, I can't share that but from the testing that I did, I know that everything was being read in correctly and all that. At this point, the code that I have works, just REALLY NOT optimally so that's the main thing that I was looking for. I haven't had too much experience with optimization so I was hoping to get some ideas on how exactly to do that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T20:20:39.960", "Id": "428599", "Score": "1", "body": "Interesting! That is a very unconventional way to read a CSV, and now I'm intrigued as to how you make use of those weird lists. You could probably benefit _a lot_ from putting your entire program up for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T20:27:52.477", "Id": "428602", "Score": "0", "body": "The lists essentially act as the columns. Because the file gets read in line by line, when I split the line by the commas, I get the various columns and then I use them throughout the program whenever I need to compare to that specific column" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T20:30:25.133", "Id": "428603", "Score": "0", "body": "Yes, I see that those lists represent columns, which is what is unusual. CSV files are almost always read as rows, and the code would probably be improved that way." } ]
[ { "body": "<ol>\n<li><p>It's easier to read code that tuple unpacks the values in the <code>for</code> from <code>dict.items()</code>.</p>\n\n<pre><code>for key1, (code1, option1) in Duplicate_combos.items():\n</code></pre></li>\n<li><code>archive_duplicates</code> is a duplicate of <code>Real_duplicates</code>. There's no need for it.</li>\n<li><p>It doesn't seem like the output needs to be ordered, and so you can just make <code>Real_duplicates</code> a set. This means it won't have duplicates, and you don't have to loop through it twice each time you want to add a value.</p>\n\n<p>This alone speeds up your program from <span class=\"math-container\">\\$O(n^3)\\$</span> to <span class=\"math-container\">\\$O(n^2)\\$</span>.</p></li>\n<li><p>Your variable names are quite poor, and don't adhere to PEP8. I have changed them to somewhat generic names, but it'd be better if you replace, say, <code>items</code> with what it actually is.</p></li>\n</ol>\n\n<pre><code>def find_duplicates(items):\n duplicates = set()\n for key1, (code1, option1) in items.items():\n for key2, (code2, option2) in items.items():\n if key1 == key2:\n continue\n elif code1 == code2 and option1 == option2 == 'No':\n duplicates.add(key1)\n duplicates.add(key2)\n return list(duplicates)\n</code></pre>\n\n<ol start=\"5\">\n<li><p>You don't need to loop over <code>Duplicate_combos</code> twice.</p>\n\n<p>To do this you need to make a new dictionary grouping by the code. And only adding to it if the option is <code>'No'</code>.</p>\n\n<p>After building the new dictionary you can iterate over it's values and return ones where the length of values is greater or equal to two.</p></li>\n</ol>\n\n<pre><code>def find_duplicates(items):\n by_code = {}\n for key, (code, option) in items.items():\n if option == 'No':\n by_code.setdefault(code, []).append(key)\n\n return [\n key\n for keys in by_code.values()\n if len(keys) &gt;= 2\n for key in keys\n ]\n</code></pre>\n\n<p>This now runs in <span class=\"math-container\">\\$O(n)\\$</span> time rather than <span class=\"math-container\">\\$O(n^3)\\$</span> time.</p>\n\n<pre><code>&gt;&gt;&gt; find_duplicates({\n 101: ['1', 'No'], 102: ['1', 'No'],\n 103: ['1','Yes'], 104: ['1', 'No'],\n 201: ['2', 'No'], 202: ['2', 'No'],\n 301: ['3', 'No'], 401: ['4', 'No'],\n})\n[101, 102, 104, 201, 202]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T20:34:27.140", "Id": "428605", "Score": "0", "body": "so this would output all of the keys that have the duplicates not just one? I was iterating twice in order to compare each element to all the others so I would get all of the keys that share the duplicate values" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T20:38:26.037", "Id": "428606", "Score": "0", "body": "@BenNaylor Yes this would do that. Please see the update with the example showing this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T12:20:16.943", "Id": "428714", "Score": "0", "body": "Thank you so much, this really really helps!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T20:24:34.670", "Id": "221611", "ParentId": "221609", "Score": "7" } }, { "body": "<p>Doing</p>\n\n<pre><code>def get_dupes(df):\n if sum(df.loc[1]=='No')&lt;2:\n return None\n else:\n return list(df.loc[:,df.loc[1]=='No'].columns)\ndf.groupby(axis=1,by=df.loc[0]).apply(get_dupes)\n</code></pre>\n\n<p>Got me</p>\n\n<pre><code> 0\n 124 None\n 123 [1234, 1235]\n dtype: object\n</code></pre>\n\n<p>Your question wasn't quite clear on what you want the output to be if there are multiple company values with duplicate values (e.g. if the input is <code>{1234: ['123' , 'No'] , 1235:['123', 'No'], 1236: ['123','Yes'], 1237: [124,'No'],1238: [124,'No']}\n</code> do you want <code>[1234, 1235, 1237, 1238]</code> or <code>[[1234, 1235], [1237, 1238]]</code>), so you can modify this code accordingly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T10:05:55.183", "Id": "428679", "Score": "1", "body": "You could just take a look at how the current code behaves to understand what output is expected..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T10:07:22.060", "Id": "428680", "Score": "2", "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": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T23:16:36.690", "Id": "221615", "ParentId": "221609", "Score": "0" } }, { "body": "<p>When reading your data, you <code>open</code> a file but never <code>.close()</code> it. You should take the habit to use the <code>with</code> keyword to avoid this issue.</p>\n\n<p>You should also benefit from the <a href=\"https://docs.python.org/3/library/csv.html#csv.reader\" rel=\"nofollow noreferrer\"><code>csv</code></a> module to read this file as it will remove boilerplate and handle special cases for you:</p>\n\n<pre><code>def open_file(filename='./Data.csv'):\n cost_center = [] # 0\n cost_center_name = []# 1\n management_site = [] # 15\n sub_function = [] #19\n LER = [] #41\n Company_name = [] #3\n Business_group = [] #7\n Value_center = [] #9\n Performance_center = [] #10\n Profit_center = [] #11\n total_lines = {}\n\n with open(filename) as in_file:\n next(in_file) # skip blank line\n reader = csv.reader(in_file, delimiter=',')\n\n for line in reader:\n cost_center.append(line[0])\n cost_center_name.append(line[1])\n management_site.append(line[15])\n sub_function.append(line[19])\n LER.append(line[41])\n Company_name.append(line[3])\n Business_group.append(line[7])\n Value_center.append(line[9])\n Performance_center.append(line[10])\n Profit_center.append(line[11])\n\n # create a dictionary of all the lines with the key being the unique cost center number (cost_center list)\n total_lines[line[0]] = line[1:]\n\n return cost_center, cost_center_name, management_site, sub_function, LER, Company_name, Business_group, total_lines, titles, Value_center, Performance_center, Profit_center\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T10:39:31.917", "Id": "428686", "Score": "0", "body": "I'd personally use something like `columns = zip(*reader)` and then define each value once. `cost_center = columns[0]`. This would make `total_lines` a bit more finicky tho." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T12:46:48.510", "Id": "428717", "Score": "0", "body": "@Peilonrayz When I read `LER.append(line[41])` and there is only 10 columns of interest, I’m not sure this is really worth it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T08:15:35.667", "Id": "221631", "ParentId": "221609", "Score": "4" } } ]
{ "AcceptedAnswerId": "221611", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:52:31.817", "Id": "221609", "Score": "7", "Tags": [ "python", "time-limit-exceeded", "hash-map" ], "Title": "Finding dictionary keys whose values are duplicates" }
221609
<p>I have been working on this thread pool for awhile to make it as simple to use as possible. I need some tips on improving performance, and some good ways to test its performance. I was wondering if anyone had any opinions/suggestions!</p> <p>Here is the class:</p> <pre><code>#pragma once #include&lt;thread&gt; #include&lt;vector&gt; #include&lt;queue&gt; #include&lt;mutex&gt; #include&lt;condition_variable&gt; #include&lt;functional&gt; #include&lt;future&gt; #define MAX_THREADS std::thread::hardware_concurrency() - 1; //portable way to null the copy and assignment operators #define NULL_COPY_AND_ASSIGN(T) \ T(const T&amp; other) {(void)other;} \ void operator=(const T&amp; other) { (void)other; } /* ThreadPool class It is a singleton. To prevent spawning tons of threads, I made it a singleton */ class ThreadPool{ public: //getInstance to allow the second constructor to be called static ThreadPool&amp; getInstance(int numThreads){ static ThreadPool instance(numThreads); return instance; } //add any arg # function to queue template &lt;typename Func, typename... Args &gt; inline auto push(Func&amp;&amp; f, Args&amp;&amp;... args){ //get return type of the function typedef decltype(f(args...)) retType; //package the task std::packaged_task&lt;retType()&gt; task(std::move(std::bind(f, args...))); // lock jobqueue mutex, add job to the job queue std::unique_lock&lt;std::mutex&gt; lock(JobMutex); //get the future from the task before the task is moved into the jobqueue std::future&lt;retType&gt; future = task.get_future(); //place the job into the queue JobQueue.emplace( std::make_shared&lt;AnyJob&lt;retType&gt; &gt; (std::move(task)) ); //notify a thread that there is a new job thread.notify_one(); //return the future for the function so the user can get the return value return future; } /* utility functions will go here*/ inline void resize(int newTCount){ int tmp = MAX_THREADS; if(newTCount &gt; tmp || newTCount &lt; 1){ tmp = numThreads; numThreads = MAX_THREADS; Pool.resize(newTCount); for (int i = tmp; i != numThreads; ++i) { Pool.emplace_back(std::thread(&amp;ThreadPool::threadManager, this)); Pool.back().detach(); } } else if (newTCount &gt; numThreads) { uint8_t tmp = numThreads; numThreads = newTCount; Pool.resize(numThreads); for (int i = tmp; i != numThreads; ++i) { Pool.emplace_back(std::thread(&amp;ThreadPool::threadManager, this)); Pool.back().detach(); } } else { numThreads = (uint8_t)newTCount; Pool.resize(newTCount); } } inline uint8_t getThreadCount(){ return numThreads; } private: //used polymorphism to store any type of function in the job queue class Job { private: std::packaged_task&lt;void()&gt; func; public: virtual ~Job() {} virtual void execute() = 0; }; template &lt;typename RetType&gt; class AnyJob : public Job { private: std::packaged_task&lt;RetType()&gt; func; public: AnyJob(std::packaged_task&lt;RetType()&gt; func) : func(std::move(func)) {} void execute() { func(); } }; // end member classes //member variables uint8_t numThreads; // number of threads in the pool std::vector&lt;std::thread&gt; Pool; //the actual thread pool std::queue&lt;std::shared_ptr&lt;Job&gt;&gt; JobQueue; std::condition_variable thread;// used to notify threads about available jobs std::mutex JobMutex; // used to push/pop jobs to/from the queue //end member variables /* infinite loop function */ inline void threadManager() { while (true) { std::unique_lock&lt;std::mutex&gt; lock(JobMutex); thread.wait(lock, [this] {return !JobQueue.empty(); }); //strange bug where it will continue even if the job queue is empty if (JobQueue.size() &lt; 1) continue; (*JobQueue.front()).execute(); JobQueue.pop(); } } /* Constructors */ ThreadPool(); //prevent default constructor from being called //real constructor that is used inline ThreadPool(uint8_t numThreads) : numThreads(numThreads) { int tmp = MAX_THREADS; if(numThreads &gt; tmp){ numThreads = tmp; } Pool.reserve(numThreads); for(int i = 0; i != numThreads; ++i){ Pool.emplace_back(std::thread(&amp;ThreadPool::threadManager, this)); Pool.back().detach(); } } /* end constructors */ NULL_COPY_AND_ASSIGN(ThreadPool); }; /* end ThreadPool Class */ </code></pre> <p>Here is example usage:</p> <pre><code>#include "ThreadPool.h" #include &lt;iostream&gt; int main(){ ThreadPool&amp; pool = ThreadPool::getInstance(4); //create pool with 4 threads auto testFunc = [](int x){ return x*x; }; auto returnValue = pool.push(testFunc, 5); std::cout &lt;&lt; returnValue.get() &lt;&lt; std::endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T20:08:28.053", "Id": "428761", "Score": "2", "body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back [Rev 4 → 2](https://codereview.stackexchange.com/posts/221617/revisions)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:06:35.293", "Id": "428816", "Score": "1", "body": "Care to share a link to your final revised code as a gist?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T21:55:40.863", "Id": "429112", "Score": "1", "body": "@jb here is the final code https://github.com/PaulRitaldato1/ThreadPool" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T05:01:52.310", "Id": "429138", "Score": "0", "body": "@Paul awesome! thanks for sharing." } ]
[ { "body": "<p>Funny how the universe works - I <em>just</em> finished my own implementation of a thread pool (albeit in C++17), and it looks a lot like yours. I found this question on the front page when I went to post my own - here's hoping we're both on the right track!</p>\n<h3>Mark the copy c'tor and operator= as deleted</h3>\n<p>Instead of actually implementing something that you don't want to be used, in C++11 and newer you can explicitly disallow invocations of the copy constructor and assignment operator:</p>\n<pre><code>ThreadPool(const ThreadPool&amp;) = delete;\nThreadPool &amp;operator=(const ThreadPool&amp;) = delete;\n</code></pre>\n<p>Or, if you would rather stick with the macro:</p>\n<pre><code>#define DISALLOW_COPY_AND_ASSIGN(T) \\\n T(const T&amp;) = delete; \\\n T &amp;operator=(const T&amp;) = delete;\n</code></pre>\n<p>When a function is marked as deleted, attempting to invoke it results in a compile-time error.</p>\n<h3>Do not declare a default constructor</h3>\n<pre><code>ThreadPool(); //prevent default constructor from being called\n\n//real constructor that is used\ninline ThreadPool(uint8_t numThreads);\n</code></pre>\n<p>The declaration of the default constructor above does nothing, other than obscure the <em>real</em> reason the program won't build if you try to invoke the default ctor. A default constructor is compiler-defined if, <em>and only if</em>, there are no constructors explicitly declared.</p>\n<p>By declaring a default constructor but not implementing it, you make it legal for a compiler to build code that attempts to invoke it - only to find yourself in a position where the linker will instead fail, which is not the expected outcome of building code that is (supposed to be) ill-formed.</p>\n<h3>Drop the inline specifier</h3>\n<p>According to <a href=\"http://eel.is/c++draft/dcl.inline\" rel=\"noreferrer\">9.1.6 [dcl.inline]</a>:</p>\n<blockquote>\n<ol start=\"4\">\n<li>A function defined within a class definition is an inline function.</li>\n</ol>\n</blockquote>\n<p>Your <code>inline</code> specifiers do nothing!</p>\n<h3>Get rid of <code>Job::func</code></h3>\n<p>What is the point of declaring <code>Job::func</code>, only to have it shadowed by <code>AnyJob&lt;T&gt;::func</code>? The base class member variable never even gets touched - it's just adding complexity to the code without any purpose. The <em>only</em> point of <code>Job</code> is to serve as a common base to different types of polymorphic functors (your <code>AnyJob&lt;T&gt;</code>s). Make it as simple as possible.</p>\n<h3>Use good names for your variables, and get rid of redundant ones</h3>\n<pre><code>//member variables\nuint8_t numThreads; // number of threads in the pool\nstd::vector&lt;std::thread&gt; Pool; //the actual thread pool\nstd::queue&lt;std::shared_ptr&lt;Job&gt;&gt; JobQueue;\nstd::condition_variable thread;// used to notify threads about available jobs\nstd::mutex JobMutex; // used to push/pop jobs to/from the queue\n//end member variables\n</code></pre>\n<p>Why do you have <code>numThreads</code> in the first place, if your vector of threads already keeps track of that information? Why is <code>thread</code> the name of a <code>condition_variable</code>? I'd expect that to be a thread object or container. <code>Pool</code> is also not a great name - something such as <code>workers</code> or <code>threads</code> would be better.</p>\n<p>Further, what's with the naming convention? You have camel case (<code>numThreads</code>) and Pascal case (<code>JobQueue</code>) mixed together - that's pretty weird. If you want to take it a step further and make it more C++ey, the <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rl-camel\" rel=\"noreferrer\">C++ Core Guidelines advise you to prefer underscore case</a>.</p>\n<h3>Make threadManager <code>private</code> - or get rid of it altogether</h3>\n<p><code>ThreadPool::threadManager</code> is clearly not meant to be called by the thread that owns the <code>ThreadPool</code> object. Why make it available? It's always better to make it difficult or impossible for mistakes to be done (if within the realm of reason).</p>\n<p>In light of the fact that it its only purpose is transitioning the worker threads from working to idle and vice versa, the name is a bit odd. Further, why not simply pass a lambda to the <code>std::thread</code> constructor? This would make your implementation more succinct.</p>\n<h3>And other things</h3>\n<p>I would also take into consideration things such as the constructor silently capping the number of threads to a set number - is that Funny Behavior™, that the programmer should instead be warned about? Maybe we want the program to be able to have more threads than the processor? It could be possible that one of the tasks given to you waits on I/O a significant amount of time - context switching can be your friend!</p>\n<h1>but, overall...</h1>\n<p>From what I can tell, this is good code. I was fairly nitpicky with it - but with the intention that in doing so, you can make your code better and hopefully learn a few tricks along the way. Good job!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T06:31:23.207", "Id": "428657", "Score": "1", "body": "Yep that naming convention just went to hell. Mostly because I was just trying to get everything to work. Ill get rid of the numThreads as im not sure why I put it there.\n\nAs far as inline goes, the functions are inside a class definition, so I believe it applies here. Also my threadManager() function is already private. \n\nThank you for the tips! Ill be making the changes you suggest!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T06:43:57.173", "Id": "428661", "Score": "1", "body": "@Paul my mistake about `threadManager` - it is a public member of a privately declared class, hence my confusion. My point about the `inline` declarations is that since all of your functions are defined within the class definition, they are all already implicitly declared `inline`. But regardless, I'm glad I could help! You've got some good code going on there :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T04:58:20.737", "Id": "221624", "ParentId": "221617", "Score": "39" } }, { "body": "<p>@osuka_ has already provided a thorough review, but I want to show an important point that is missing from his review: The choice of making your class a singleton and the way that you implemented it.</p>\n\n<p>I suppose that you have a really good reason to make this class a singleton. But sometimes, the singleton pattern is considered an anti-pattern because it often makes testing harder (among other downsides). Alternatives would be to simply make the <code>ThreadPool</code> a normal class and use dependency injection/inversion techniques to locate a shared object.</p>\n\n<p>A possible source for problems can be found in your <code>getInstance</code> method:</p>\n\n<pre><code> //getInstance to allow the second constructor to be called\n static ThreadPool&amp; getInstance(int numThreads){\n static ThreadPool instance(numThreads);\n\n return instance;\n }\n</code></pre>\n\n<p>This constructs a single instance with a given value of <code>numThreads</code> on the first usage. The problem is: you have to take care that either</p>\n\n<ul>\n<li>this method is ALWAYS called with the same <code>numThreads</code></li>\n<li><strong>or</strong> the very first usage is ALWAYS at a point where you can be completely sure that the value is correct.</li>\n</ul>\n\n<p>Both result in maintainability issues. Consider for example the following function:</p>\n\n<pre><code>void doWork() {\n auto&amp; pool = ThreadPool::getInstance(4);\n // ... use the pool\n}\n</code></pre>\n\n<p>This would later get changed to</p>\n\n<pre><code>void doWork() {\n prepareWork();\n auto&amp; pool = ThreadPool::getInstance(4);\n // ... use the pool\n}\n</code></pre>\n\n<p>Here, you would have to check whether <code>prepareWork()</code> also uses the <code>ThreadPool</code> and, if so, whether it passes the correct number of threads. In larger codebases, this can easily lead to avoidable bugs.</p>\n\n<p><strong>Conclusion:</strong> Please reconsider whether making this class a singleton is really the best choice, and maybe select a better way of initializing the number of threads.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T19:13:36.667", "Id": "428750", "Score": "0", "body": "I know a lot of people consider singletons to be a bad practice. The reason I did this was because of hardware limitations. I did not want the user to be able to create many different instances. 100 instances of a thread pool all using the max threads possible seemed like a bad idea to me, but I have no experience in what would happen in that case. Would it just slow to a crawl until no memory is left or crash?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T14:59:07.033", "Id": "428898", "Score": "0", "body": "Implementation-defined, but making the thread pool itself a singleton is _still_ the wrong way to handle this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T04:15:16.600", "Id": "428967", "Score": "1", "body": "@Paul: If that many threads are just waiting for I/O (e.g. listening on network sockets), then no big deal. If they're all doing CPU-bound work that doesn't touch much memory, everything will be slow but not unusable on e.g. an 8-core system. Your OS's scheduling timeslice is short enough that interactive programs will get CPU time occasionally. (And with a good OS with a heuristic that boosts the priority of tasks that \"look interactive\", e.g. don't use up their full timeslice, it might not be very noticeable). If they use much RAM, you get swap space thrashing or at least L3 cache." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T12:41:12.860", "Id": "221645", "ParentId": "221617", "Score": "8" } }, { "body": "<p>@osuka_ and @anderas gave some very good advice. I just have a couple things I want to add:</p>\n\n<h3>Macros</h3>\n\n<pre><code>#define MAX_THREADS std::thread::hardware_concurrency() - 1;\n</code></pre>\n\n<p>While it doesn't really make sense to do arithmetic on this, macros like this should be surrounded by parentheses so the order of operations works correctly. Without it you get weird stuff like (assume <code>std::thread::hardware_concurrency()</code> is 4): <code>MAX_THREADS * 5 =&gt; 4 - 1 * 5 =&gt; -1</code> instead of <code>MAX_THREAD * 5 =&gt; (4 - 1) * 5 =&gt; 15</code>. Also, macros <em>should not</em> end in a semicolon. The user of the macro should add the semicolon (like you did - <code>int tmp = MAX_THREADS;</code>).</p>\n\n<p>Alternatively, avoid macros altogether (this is C++ after all) and use <code>const auto MAX_THREADS = std::thread::hardware_concurrency() - 1;</code></p>\n\n<h3>In <code>push()</code>:</h3>\n\n<pre><code>std::unique_lock&lt;std::mutex&gt; lock(JobMutex);\n</code></pre>\n\n<p>This is a minor point, but seeing this I would expect something to unlock <code>lock</code> at some point (like the condition variable in <code>threadManager()</code>, which by the way has the confusing name <code>thread</code>). If the lock should be held until the end of its scope like in this case use a <code>std::lock_guard&lt;std::mutex&gt;</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T14:18:18.693", "Id": "428725", "Score": "1", "body": "`hardware_concurrency` is not constexpr (compile time constant), so your `MAX_THREADS` variable should be `const`. When discussing the macro, you should mention that the macro definition should _not_ end in a semicolon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:05:46.697", "Id": "428730", "Score": "0", "body": "@1201ProgramAlarm Thanks, edited. I didn't even notice the semicolon!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T14:00:25.397", "Id": "221650", "ParentId": "221617", "Score": "14" } }, { "body": "<p>std::thread::hardware_concurrency() can return 0,you should handle this case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T21:03:22.600", "Id": "428774", "Score": "3", "body": "Or `1` which is even more possible I think." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T16:55:34.717", "Id": "221669", "ParentId": "221617", "Score": "9" } }, { "body": "<p>There are a lot of good comments here already, overall good work ... </p>\n\n<p>The <code>resize</code> function is not threadsafe, especially since you are using a singleton you don't know where this will be called from, not making this threadsafe leaves you open to race conditions. </p>\n\n<p>You're not unlocking <code>JobQueue</code> before the call to notify, that seems strange, the thread that gets woken up would at least have to wait for the push call to release the lock. </p>\n\n<p>While the number of cores is definitely a factor that should be taken under consideration, it's really the runtime behavior of the threads that determines the best size of the threadpool, by creating the artificial limit you're limiting the use of your pool. I'd use the <code>std::thread::hardware_concurrency()</code> as a default value for the constructor but not to limit the size of the pool. Anybody playing around with the pool size can now determine the optimal size for their use case.</p>\n\n<p>I have to put in my two cents with regards to singletons, I use singletons in some places in my code but I have not found a good reason to limit construction of singleton objects, by allowing singleton access or new construction of the object you create opportunities for varied use, it makes testing easier, and sometimes lets you get rid of the singleton access. Just make the constructor public anybody looking at your class can see ah i can use the singleton, or i can create one and pass it around. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T17:57:20.777", "Id": "428744", "Score": "1", "body": "Good advice overall - but a singleton that can be instantiated more than once is, by definition, not a singleton. If you can \"use the singleton or create one and pass it around\", it is not a singleton - it's just a global." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T19:34:43.740", "Id": "428752", "Score": "0", "body": "Thank you! I solved the issue with the locking and unlocking. Profiling showed that it was actually slowing performance because the threadManager (since been deleted in place of a lambda) was holding onto the lock WHILE executing the job, preventing every other thread from accessing the queue. Ill edit with the updated code" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T17:46:55.047", "Id": "221672", "ParentId": "221617", "Score": "2" } }, { "body": "<p>You've received good style advice so far.</p>\n\n<p>But your pool doesn't work. So let's try to address that.</p>\n\n<h1>1. 'resize' is both wrong and not needed.</h1>\n\n<p>As others mentioned, it's not thread safe. Making it so is exceedingly difficult. And in practice, you don't need to change the thread pool's size after after start.</p>\n\n<h1>2. You only use one thread at a time.</h1>\n\n<p>In threadManager(), you execute jobs with the mutex taken. That means a single job a time can be executed, negating the very reason you created the pool in the first place. </p>\n\n<p>Fix it by copying the job to a local variable, pop it from the queue, unlock the mutex and only then execute it.</p>\n\n<h1>3. shared_ptr is slower than unique_ptr </h1>\n\n<p>and not needed for the jobs queue. But best to get rid of them both, as suggested at #6.</p>\n\n<h1>4. detach() is lazy and dangerous</h1>\n\n<p>There are only few good uses of it in practice, because it will kill threads at program exit, rather than gracefully wait for jobs to be completed. </p>\n\n<p>Replace it with join() in the class destructor. (One more reason to stop using that singleton that a few others explain it's bad).</p>\n\n<p>You will need to add extra code to control the exit:</p>\n\n<ul>\n<li>add an atomic bool isStopping. </li>\n<li>initialize it to false in the constructor's initializer list. </li>\n<li>On destructor, set it to true. </li>\n<li>Then call notify_all() on the condition variable. This way all threads are woken up and can test for the value of isStopping. </li>\n<li>in threadManager(), before <em>and</em> after executing the job, check if isStopping is set to true, and return if needed, exiting the thread.</li>\n</ul>\n\n<p>You will also need to adjust the condition variable lambda to return if isStopping is true.</p>\n\n<ul>\n<li>Finally, back in the destructor, call join() on all threads.</li>\n</ul>\n\n<p>You can play with two different exit strategies: execute all pending jobs first or discard them. Discarding is a good default, because otherwise the exit will be delayed for an unspecified amount of time untill the queue is processed.</p>\n\n<h1>5. That singleton</h1>\n\n<p>It not only prevents you from closing the thread pool gracefully (because singleton destructors are called very late in the exit process, but can prevent genuine use-cases of your pool. Let's say you want to process two kinds of tasks - one whick is very fast and one which is very slow. Imagine you queue many slow tasks in the pool, which will make the fast tasks wait for them all to be executed.</p>\n\n<p>Having two pools, one for the fast, one for the slow ones allows you to separate resources and offer better performance for the fast ones.</p>\n\n<h1>6. You can replace both Job and AnyJob with std::function</h1>\n\n<p>and a proper initializer with a lambda which captures the packaged_task.</p>\n\n<h1>7. There is no good default for number of threads</h1>\n\n<p>A purely computational load - like scientific simulations - running on a dedicated server will best work with a thread per core (actually even this basic assumption is wrong in the face of hyperthreading). But this is a tiny minority of cases. If you do I/O, you can use effectively many more threads than cores. If you use multiple pools for different parts of your app (one for I/O, one for processing), you'll need to choose wisely the resource distribution between them. And in a server shared by more than one app, you need to keep other tenants in mind.</p>\n\n<p>I suggest removing the use of hardware_concurrency altogether. It invites the user to take lazy and poor decisions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T19:41:39.970", "Id": "428756", "Score": "0", "body": "Those are actual compelling arguments for not using a singleton, Ill take that into consideration. I am about to post revised code ( I actually found that bug where one thread is being used at a time because of the mutex). \n\n\nI would like to see an example of what you mean in #6. I found no way of storing any type of packaged task, as a std::function. I require packaged_task because they allow the use of futures, where std::function, does not.\n\n\nI was not too sure how to get .join() to work. It seemed that if I didnt join in the constructor, I got compile errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T04:05:37.013", "Id": "428966", "Score": "0", "body": "Suggestion for the atomic bool: *initialize* it to false in the constructor. Don't construct it and *then* do an atomic store with `mo_seq_cst` by assigning to it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-08T17:40:21.307", "Id": "429386", "Score": "0", "body": "Two serious problems with the suggestions here: first, discarding tasks is going to result in exceptions thrown (since you’re getting rid of a future that was never fulfilled). Secondly, `std::function` *cannot* be used here as a result of `std::packaged_task` not being copiable (only movable). The standard requires an `std::function` be constructed from a Callable *and* CopyAssignable object; the tasks, in this case, are only one of those." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T19:30:27.507", "Id": "221679", "ParentId": "221617", "Score": "12" } }, { "body": "<p>And another one for posterity ...</p>\n\n<p><strong>Macros</strong> - just say No.</p>\n\n<pre><code>#define MAX_THREADS std::thread::hardware_concurrency() - 1;\n</code></pre>\n\n<ul>\n<li>don't put a semicolon at the end of a macro, it means you can't write <code>resize(MAX_THREADS)</code></li>\n<li><p>do parenthesize your macros, like</p>\n\n<pre><code>#define MAX_THREADS (std::thread::hardware_concurrency() - 1)\n</code></pre>\n\n<p>so you can write <code>resize(MAX_THREADS/2)</code></p></li>\n<li><p>don't use macros in the first place, we're not writing K&amp;R C any more</p>\n\n<pre><code>unsigned int max_threads() {\n return std::thread::hardware_concurrency() - 1;\n}\n</code></pre></li>\n<li><p>don't use <a href=\"https://en.cppreference.com/w/cpp/thread/thread/hardware_concurrency\" rel=\"nofollow noreferrer\"><code>thread::hardware_concurrency()</code></a> either - it doesn't guarantee what you expect anyway:</p>\n\n<blockquote>\n <p>... The value should be considered only a hint.</p>\n</blockquote></li>\n</ul>\n\n<p><strong>Constructors</strong></p>\n\n<pre><code>//portable way to null the copy and assignment operators\n</code></pre>\n\n<p>... it isn't and it doesn't. Just write <code>= delete</code> explicitly, as osuka_ says.</p>\n\n<pre><code>ThreadPool(); //prevent default constructor from being called\n</code></pre>\n\n<p>... you mean because it's private? Just use <code>= delete</code> here too. That expresses your intent so clearly you don't even need a comment, which is why it was added to the language.</p>\n\n<pre><code>inline ThreadPool(uint8_t numThreads)\n</code></pre>\n\n<p>always mark single-argument constructors <code>explicit</code> unless you <em>want</em> implicit conversion from <code>uint8_t</code> (I'm pretty sure you don't). And <code>inline</code> does nothing here.</p>\n\n<p>For some reason you're limiting thread pools to <code>std::numeric_limits&lt;uint8_t&gt;::max()</code> threads at construction time, but allow them to be later resized up to <code>std::numeric_limits&lt;int&gt;::max()</code>. If you really wanted, for some reason, a pool of 260 threads, that's a bit awkward.</p>\n\n<p><strong>Singletons</strong></p>\n\n<pre><code>/* ... To prevent spawning tons of threads, I made it a singleton */\n</code></pre>\n\n<ul>\n<li>Avoid singletons anyway where you can</li>\n<li>If you <em>need</em> a singleton (and you really don't), write a <code>Singleton&lt;T&gt;</code> wrapper instead of baking it into the class. Singleton-ness is not a core concern of a thread pool, and a sane user might quite reasonably want two thread pools, each with a small number of threads, for separating different types of task.</li>\n<li>You already allow your pool to be up to <code>hardware_concurrency()-1</code> in size, and this could legally be <em>enormous</em>, so this doesn't avoid the problem anyway. At some point, you need to just trust that your users aren't going to start a million thread pools with INT_MAX threads each.</li>\n<li>Your <code>getInstance</code> method constructs the single instance with <code>numThreads</code> threads (implicitly truncated to <code>uint8_t</code> as mentioned above) on the <em>first</em> call, but subsequent calls will ignore the <code>numThreads</code> parameter entirely. This is confusing and error-prone, which strongly suggests the instance management and configuration shouldn't be coupled at all.</li>\n</ul>\n\n<p><strong>Threads</strong></p>\n\n<ul>\n<li>when you resize the pool smaller, you detach the surplus worker threads, but you never tell them to die. Any thread pool should have a way to tell worker threads to exit. A <code>virtual bool shutdown()</code> method on the <code>Job</code> would be sufficient, but you also need some way to tell the <code>resize</code> method <em>which</em> threads exited, so it can clean up the pool correctly.</li>\n<li>exactly the same cleanup problem on destruction. If you remove the <code>resize()</code> method entirely, as suggested in another answer, you can use a simple <code>bool shuttingDown</code> flag - otherwise, you can resize to zero and use the same shutdown notification mechanism.</li>\n<li><p>your worker thread keeps holding the mutex while executing each task, so you'll have virtually no actual concurrency.</p>\n\n<p>Move the current task ptr from the queue while holding the lock, and then use a scoped unlocker (like a unique_lock, but exactly backwards) to release the mutex while executing it. </p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T16:10:49.227", "Id": "221728", "ParentId": "221617", "Score": "6" } }, { "body": "<pre><code>/* ThreadPool class\nIt is a singleton. To prevent spawning\ntons of threads, I made it a singleton */\n</code></pre>\n\n<p><code>ThreadPool</code>s can be useful as both singletons and not singletons.</p>\n\n<p>There is zero need to mix the <code>ThreadPool</code> implementation with the \"this is a singleton\" implementation. There is a lot of need to not; there are some nasty things you have to look out for with singletons in non-trivial applications.</p>\n\n<pre><code>class ThreadPool{\n //add any arg # function to queue\n template &lt;typename Func, typename... Args &gt;\n inline auto push(Func&amp;&amp; f, Args&amp;&amp;... args){\n</code></pre>\n\n<p>While <code>std::thread</code> and <code>std::async</code> supports passing arguments to a task, that is in my experience a needless complication.</p>\n\n<p>Just take a nullary function. The caller can bundle up their arguemnts into a lambda really easily if they need to.</p>\n\n<pre><code> //get return type of the function\n typedef decltype(f(args...)) retType;\n\n //package the task\n std::packaged_task&lt;retType()&gt; task(std::move(std::bind(f, args...)));\n</code></pre>\n\n<p>An example of why what you did is a bad idea. You used <code>std::bind</code>. If <code>f</code> was already the result of a <code>std::bind</code>, this doesn't do the same thing as calling <code>f</code> with the arguments <code>args...</code>.</p>\n\n<p>Instead it does the insane thing <code>std::bind</code> does.</p>\n\n<pre><code> // lock jobqueue mutex, add job to the job queue \n std::unique_lock&lt;std::mutex&gt; lock(JobMutex);\n</code></pre>\n\n<p>I'd advise, using the single responsibility principle, to split your job queue off from your thread pool.</p>\n\n<pre><code>template&lt;class T&gt;\nstruct threadsafe_queue;\n</code></pre>\n\n<p>About half of the complexity of your <code>ThreadPool</code> is the queue, the other half is managing threads. By splitting the two, you have two piece of code each half as complex.</p>\n\n<p>And a <code>threadsafe_queue</code> can be reused elsewhere.</p>\n\n<pre><code> /* utility functions will go here*/\n inline void resize(int newTCount){\n</code></pre>\n\n<p>Nix <code>inline</code>.</p>\n\n<p><code>resize</code> is a horrible name. You aren't a container.</p>\n\n<pre><code> int tmp = MAX_THREADS;\n</code></pre>\n\n<p>Having more threads that hardware concurrency size -1 is a perfectly sane thing to do if you know you have lots of blocking operations.</p>\n\n<p>This kind of logic <strong>does not belong in a class named <code>ThreadPool</code></strong>.</p>\n\n<p>Having easy access to \"spawn max concurrency threads\" or \"max concurrency -1 threads\" is good. Setting a hard limit is bad.</p>\n\n<pre><code> Pool.back().detach();\n</code></pre>\n\n<p>Detaching threads is the wrong thing to do 99.999% of the time. Don't do it. Threads running after main ends is extremely dangerous and toxic.</p>\n\n<pre><code> else {\n numThreads = (uint8_t)newTCount;\n Pool.resize(newTCount);\n }\n</code></pre>\n\n<p>You need to be really clear about what shrinking the number of threads means.</p>\n\n<pre><code> //used polymorphism to store any type of function in the job queue\n class Job {\n</code></pre>\n\n<p>While <code>std::function&lt;void()&gt;</code> isn't sufficient, as <code>packaged_task&lt;R()&gt;</code> is move only, a type like it is pretty sane and useful.</p>\n\n<p>The simplest to find type that can store a <code>packaged_task&lt;R()&gt;</code> is a <code>packaged_task&lt;void()&gt;</code>. Try it.</p>\n\n<p>Replace <code>Job</code> with <code>std::packaged_task&lt;void()&gt;</code>. Stop messing with pointers.</p>\n\n<p>But really, find a move-only <code>std::function</code> and use that. When in doubt, use value semantics.</p>\n\n<pre><code> //member variables\n uint8_t numThreads; // number of threads in the pool\n std::vector&lt;std::thread&gt; Pool; //the actual thread pool\n</code></pre>\n\n<p>Belongs in <code>ThreadPool</code>. But really, <code>numThreads</code> is redundant; <code>Pool.size()</code> has that information.</p>\n\n<p>Maybe have a second vector of \"parked threads\".</p>\n\n<p>Also, always <code>=0</code> or whatever data.</p>\n\n<pre><code> std::queue&lt;std::packaged_task&lt;void()&gt;&gt; JobQueue;\n std::condition_variable thread;// used to notify threads about available jobs\n std::mutex JobMutex; // used to push/pop jobs to/from the queue\n //end member variables\n</code></pre>\n\n<p>Belongs in <code>threadsafe_queue</code>.</p>\n\n<pre><code> /* infinite loop function */\n inline void threadManager() {\n while (true) {\n\n std::unique_lock&lt;std::mutex&gt; lock(JobMutex);\n thread.wait(lock, [this] {return !JobQueue.empty(); });\n\n //strange bug where it will continue even if the job queue is empty\n if (JobQueue.size() &lt; 1)\n continue;\n\n (*JobQueue.front()).execute();\n\n JobQueue.pop();\n }\n</code></pre>\n\n<p>don't do the work while the mutex is engaged.</p>\n\n<p>This is an example of where mixing the thread safe queue with the thread pool has messed you up.</p>\n\n<pre><code>threadsafe_queue&lt; std::packaged_task&lt;void()&gt; &gt; jobs;\n\ntemplate&lt;class F&gt;\nauto push_task( F&amp;&amp; f ) {\n using dF = std::decay_t&lt;F&gt;;\n using R = std::result_of_t&lt; dF&amp;() &gt;;\n std::packaged_task&lt; R() &gt; task = std::forward&lt;F&gt;(f);\n auto retval = task.get_future();\n jobs.push_back( std::move(task) ); // may require an explicit cast\n return retval;\n}\n</code></pre>\n\n<p>wow, that is a simpler <code>push</code>.</p>\n\n<pre><code>struct killable_thread {\n std::thread t;\n std::shared_ptr&lt;std::atomic&lt;bool&gt;&gt; kill;\n killable_thread( std::thread tin, std::shared_ptr&lt;std::atomic&lt;bool&gt;&gt; kin ):\n t(std::move(tin)),\n kill(std::move(kin))\n {}\n};\nstd::vector&lt;killable_thread&gt; threads;\n\nvoid add_thread(std::size_t n = 1) {\n while (n &gt; 0 ) {\n auto kill = std::make_shared&lt;std::atomic&lt;bool&gt;&gt;(false);\n std::thread t( [this, kill]{\n while (!*kill) {\n auto job = jobs.pop_back();\n if (!job)\n return; // done\n (*job)();\n }\n });\n threads.emplace_back( std::move(t), std::move(kill) );\n --n;\n }\n}\n</code></pre>\n\n<p><code>remove_thread</code>s sets <code>*kill</code> and moves the threads somewhere else to clean up later.</p>\n\n<p>Possibly we augment the thread code to have them move <em>themselves</em> to a \"to be cleaned up\" queue, and other threads can even clean up that queue, leaving at most one \"waiting to be joined\" task in that queue.</p>\n\n<p>Note that we want <code>threadsafe_queue</code> to support <code>.abort()</code> -- that means <code>pop_back</code> returns an <code>optional&lt;T&gt;</code> (boost or not) instead of a <code>T</code>, so it can return \"pop failed\". An alternative is that it could throw.</p>\n\n<p>If the queue is killed, all pops abort.</p>\n\n<pre><code> /* Constructors */\n ThreadPool(); //prevent default constructor from being called\n</code></pre>\n\n<p><code>=delete</code>.</p>\n\n<pre><code>//real constructor that is used\ninline ThreadPool(uint8_t numThreads) {\n int tmp = MAX_THREADS;\n if(numThreads &gt; tmp){\n numThreads = tmp;\n }\n</code></pre>\n\n<p>again, anti-pattern.</p>\n\n<p>Entire body should read:</p>\n\n<pre><code>ThreadPool(uint8_t numThreads) {\n add_thread(numThreads);\n}\n</code></pre>\n\n<p>DRY -- don't repeat yourself. There should be one function for adding threads, uesd both here and elsewhere </p>\n\n<pre><code>NULL_COPY_AND_ASSIGN(ThreadPool);\n</code></pre>\n\n<p>really?</p>\n\n<pre><code>ThreadPool(ThreadPool const&amp;)=delete;\nThreadPool&amp; operator=(ThreadPool const&amp;)=delete;\n</code></pre>\n\n<p>that is so taxing you'll write a macro to avoid typing it?</p>\n\n<p>Here is a threadsafe queue:</p>\n\n<pre><code>template&lt;class T&gt;\nstruct threaded_queue {\n using lock = std::unique_lock&lt;std::mutex&gt;;\n void push_back( T t ) {\n lock l(m);\n data.push_back(std::move(t));\n cv.notify_one();\n }\n boost::optional&lt;T&gt; pop_front() {\n lock l(m);\n cv.wait(l, [this]{ return abort || !data.empty(); } );\n if (abort) return {};\n auto r = std::move(data.front());\n data.pop_front();\n return std::move(r);\n }\n void terminate() {\n lock l(m);\n abort = true;\n data.clear();\n cv.notify_all();\n }\n ~threaded_queue()\n {\n terminate();\n }\nprivate:\n std::mutex m;\n std::deque&lt;T&gt; data;\n std::condition_variable cv;\n bool abort = false;\n};\n</code></pre>\n\n<p>another operation I find useful is the ability to \"abandon all queued tasks\", without aborting the queue.</p>\n\n<p>You'll notice how much smaller and more clean this is when it isn't mixed in with the thread pool code. The thread pool code also gets cleaner.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-08T18:07:31.707", "Id": "429389", "Score": "1", "body": "Could be just me, but it sounds like wrapping a queue in another class entirely is a significant overkill. Wrapping a thread is also not anything you can’t solve by adding a line to the waiting task implementation. More importantly, it’s awkward (impossible?) to use a queue with `T = std::packaged_task<void()>` if you want to return a `future` with any other T. The point of `Job` and `AnyJob` is to add some type erasure to this structure, so that you can simultaneously return a meaningful value through your future, and store tasks that return different types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-08T18:12:04.497", "Id": "429390", "Score": "1", "body": "And on second thought: mimicking `std::thread` and `std::bind` is a good idea for many reasons: the programmer is probably familiar with it, it’s easier to use, and you avoid making them `#include <functional>` for a bind call. There are many very desirable advantages to his approach, at little cost (since it doesn’t add much complexity)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-08T21:00:46.070", "Id": "429415", "Score": "0", "body": "@osuk *nobody should be using std bind*. Just use lambdas. Packaged task void is a type erasure class; it can store packaged task R for any type R. Using the thread call bindings is much more difficult than using a lambda, because the r/l value transformations of arguments passed are sufficiently obscure that it took msvc multiple versions to get their implementation correct. Most C++ programmers won't get it right; the OP doesn't get it right. You probably didn't notice they got it wrong. Users probably don't know the right magic behaviour, so both wrong and right surprise users." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-08T21:39:36.723", "Id": "429418", "Score": "0", "body": "Why should nobody use bind? It does take a decent understanding of the language to use, but I can't see why it should be avoided at all costs as you seem to suggest. Lambdas have a few oddities (such as the fact that move-capturing a non-copiable object makes the lambda non-copiable). If you understand move semantics and reference binding, implementing something correctly isn't *that* difficult. The problem with using `packaged_task<void()>` is that you cannot, then, accept a callable that returns any type (unless some type erasure happens before it is added to the queue)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-09T00:52:58.530", "Id": "429427", "Score": "0", "body": "@osuka_ `packaged_task<void()>` can accept a `packaged_task<chicken()>`. I can repeat myself again if you want, or you can simply fail to believe me. `std::packaged_task<int()> foo; std::packaged_task<void()> bar = std::move(foo);` is legal code. No, next to nobody understands `std::bind` fully. The only person I know who implemented it and I talked to about it agrees that using it is a bad idea. If you think reference semantics and reference binding are the tricky parts of `std::bind`, then you haven't implemented `std::bind`, and don't understand it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-09T00:56:15.340", "Id": "429428", "Score": "0", "body": "@osuka_ Even ignoring the insanity of what happens when you pass a bind expression to bind, `std::bind` doesn't behave like `std::thread`'s marshaling of arguments. They are similar, but not the same. If you think `std::thread t( f, a, b )` is the same as `std::thread t( std::bind( f, a, b ) )` then you are giving evidence that you shouldn't use `std::bind`; the thread case gets rvalue arguments, the bind case doesn't, because the standard says so and because the thread is guaranteed run-once. Plus, in generic code, the arguments to `std::bind` can do crazy magic that `std::thread` doesn't do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-09T01:02:07.953", "Id": "429430", "Score": "0", "body": "@osuka_ Basically, to continue the point, `std::bind` is really arcane. Like, it has crazy corners. `std::thread` passing arguments? Modest arcane, but enough that std library writers in MSVC++ got it wrong the first time they wrote it. Now, lambdas are a bit arcane, but *everyone should learn lambdas*. With C++14, lambdas can do everything sane that `std::bind` can do with clear syntax, and the insane things are explicitly insane with lambdas (as opposed to magical and obscure with `std::bind`). `std::bind` was brought in C++11 from boost and predates lambdas; C++14 lambdas make it obsolete." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-09T01:39:00.490", "Id": "429435", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/94679/discussion-between-osuka-and-yakk)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-28T21:24:00.643", "Id": "432380", "Score": "1", "body": "@Yakk, `std::packaged_task<int()> foo; std::packaged_task<void()> bar = std::move(foo);` [does not compile](https://godbolt.org/z/7NSSzc), but `std::packaged_task<int()> foo; std::packaged_task<void()> bar(std::move(foo));` does." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T19:54:46.253", "Id": "221739", "ParentId": "221617", "Score": "4" } } ]
{ "AcceptedAnswerId": "221624", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T00:27:10.263", "Id": "221617", "Score": "36", "Tags": [ "c++", "multithreading", "c++14" ], "Title": "Thread Pool C++ Implementation" }
221617
<p>What this tool does update skills for agents on a Contact Center Cluster (Cisco UCCX). The tool reads a csv file called agents.csv from the current working directory. This file has a list of agents and their skills. The skills are updated using <a href="https://developer.cisco.com/docs/contact-center-express/#!system-configuration-apis" rel="nofollow noreferrer">a REST API</a>.</p> <p>Note that UCCX allows a maximum of 400 agents, so that's why I use the sync API for reading a file and csv because I don't think it's going to be performance impacting. </p> <p>This is the line where the agent skills are updated:</p> <pre><code> await axios.put(ccxURI, xml, config); </code></pre> <p>It is done sequentially. I originally wanted to do it concurrently using Promise.all but for some reason the UCCX server responds with a 500 error. So for now I'm doing it one at a time. </p> <p>Code is below:</p> <pre><code>"use strict"; const ora = require("ora"); let throbber; const inquirer = require("inquirer"); const prompts = [ { name: "IP", type: "input", message: "Enter IP address of UCCX publisher: ", }, { name: "user", type: "input", message: "Enter username: ", }, { name: "pass", type: "password", message: "Enter password: ", }, ]; const axios = require("axios"); const https = require("https"); const fs = require("fs"); // csv sync api is used as there can be at most 400 agents on the cluster // hence it should not be performance impacting const parse = require("csv-parse/lib/sync"); const parseOptions = { comment: "#", skip_empty_lines: true, trim: true }; // csv file won"t exceed 1MB so readFileSync should be OK const csv = fs.readFileSync("agents.csv", "utf-8"); const parser = require("xml2json"); (async () =&gt; { console.log("Please verify agents.csv is in the current working directory\n"); const answers = await inquirer.prompt(prompts); const IP = answers.IP; const config = { auth: { username: answers.user, password: answers.pass }, httpsAgent: new https.Agent({ rejectUnauthorized: false }), headers: {"Content-Type": "application/xml"} }; const XMLtemplate = ` &lt;resource&gt; &lt;self&gt;&lt;/self&gt; &lt;userID&gt;&lt;/userID&gt; &lt;firstName&gt;&lt;/firstName&gt; &lt;lastName&gt;&lt;/lastName&gt; &lt;extension&gt;&lt;/extension&gt; &lt;alias&gt;&lt;/alias&gt; &lt;resourceGroup&gt;&lt;/resourceGroup&gt; &lt;skillMap&gt; &lt;skillCompetency&gt;&lt;/skillCompetency&gt; &lt;/skillMap&gt; &lt;autoAvailable&gt;true&lt;/autoAvailable&gt; &lt;type&gt;&lt;/type&gt; &lt;team name="Default"&gt; &lt;refURL&gt;${IP}/adminapi/team/1&lt;/refURL&gt; &lt;/team&gt; &lt;primarySupervisorOf/&gt; &lt;secondarySupervisorOf/&gt; &lt;/resource&gt;`; const resourceGroupMapping = {}; const resourceGroupURI = `https://${IP}/adminapi/resourceGroup`; const resourceGroupList = await axios.get(resourceGroupURI, config); throbber = ora("Updating").start(); for(const resourceGroup of resourceGroupList.data.resourceGroup) { resourceGroupMapping[resourceGroup.name] = resourceGroup.id; } const skillMapping = {}; const skillURI = `https://${IP}/adminapi/skill`; const skillList = await axios.get(skillURI, config); for(const skill of skillList.data.skill) { skillMapping[skill.skillName] = skill.skillId; } const teamMapping = {}; const teamURI = `https://${IP}/adminapi/team`; const teamList = await axios.get(teamURI, config); for(const team of teamList.data.team) { teamMapping[team.teamname] = team.teamId; } // sample csv // #id,firstName,lastName,extension,resourceGroup,team,skill1,competence1,skill2,competence2,skill3,competence3,skill4,competence4 ... // Adrian_A,Adrian,Aldana,1008,1,Saturday-Lending,Lending,Pre_Approved_Loans,9,HELOC,6,Auto_and_Consumer_Loans,4,Loan_Status,7 const records = parse(csv, parseOptions); const recordLength = records.length; const XMLOptions = { object: true, reversible: true, trim: true }; for(let index = 0; index &lt; recordLength; index++) { let skillsAndCompetency; let jsonObject; let xml; let ccxURI; jsonObject = parser.toJson(XMLtemplate, XMLOptions); jsonObject.resource.skillMap.skillCompetency = []; jsonObject.resource.self = { "$t" : `https://${IP}/adminapi/resource/${records[index][0]}` }; jsonObject.resource.userID = { "$t" : `${records[index][0]}` }; jsonObject.resource.firstName = { "$t" : `${records[index][1]}` }; jsonObject.resource.lastName = { "$t" : `${records[index][2]}` }; jsonObject.resource.extension = { "$t" : `${records[index][3]}` }; // include resource type jsonObject.resource.type = { "$t" : `${records[index][4]}` }; // update resource group if(records[index][5]) { jsonObject.resource.resourceGroup.name = `${records[index][5]}`; jsonObject.resource.resourceGroup.refURL = { "$t" : `https://${IP}/adminapi/resourceGroup/${resourceGroupMapping[records[index][5]]}` }; } // update team if(records[index][6] !== "Default") { jsonObject.resource.team.name = records[index][6]; jsonObject.resource.team.refURL = { "$t" : `https://${IP}/adminapi/team/${teamMapping[records[index][6]]}` }; } // update all skills and competency for(let j = 7; j &lt; records[index].length; j += 2) { skillsAndCompetency = { competencelevel : "", skillNameUriPair : { name: "", refURL : "" } }; skillsAndCompetency.competencelevel = { "$t" : `${records[index][j + 1]}` }; skillsAndCompetency.skillNameUriPair.name = `${records[index][j]}`; skillsAndCompetency.skillNameUriPair.refURL = { "$t" : `https://${IP}/adminapi/skill/${skillMapping[records[index][j]]}` }; jsonObject.resource.skillMap.skillCompetency.push(skillsAndCompetency); } // xml payload xml = `&lt;?xml version="1.0" encoding="UTF-8"?&gt;` + parser.toXml(JSON.stringify(jsonObject)); // update skills for the agents ccxURI = `https://${IP}/adminapi/resource/${records[index][0]}`; // if a row in the csv is incorrect, continue processing subsequent rows try { await axios.put(ccxURI, xml, config); } catch (error) { throbber.stop(); console.log(`\nCould not assign skills to ${records[index][0]}\n${error.response.data.apiError[0].errorMessage}\n`); throbber.start(); } } })() .catch(error =&gt; console.log(error.stack)) .then( () =&gt; throbber.stop()); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T03:00:54.200", "Id": "221621", "Score": "4", "Tags": [ "javascript", "node.js", "csv", "rest", "ecmascript-8" ], "Title": "Node.js tool to update Cisco UCCX with CSV data" }
221621
<p>I've created a JS snippet to enhance markdown at display-time with KaTeX math rendering. (Specifically, this is mostly for documentation of math-heavy libraries where the host language documentation tool doesn't have specific math support (e.g. rustdoc).) The snippet itself is the HTML in <code>&lt;head&gt;</code> to load the KaTeX scripts and manipulate the DOM (which would be injected into whatever generated documentation), and the rest of the snippet is to demonstrate the functionality.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;!--KaTeX (preload the two most common fonts)--&gt; &lt;link rel="preload" as="font" type="font/woff2" crossorigin href="https://cdn.jsdelivr.net/npm/katex@0.10.2/dist/fonts/KaTeX_Main-Regular.woff2"&gt; &lt;link rel="preload" as="font" type="font/woff2" crossorigin href="https://cdn.jsdelivr.net/npm/katex@0.10.2/dist/fonts/KaTeX_Math-Italic.woff2"&gt; &lt;link rel="stylesheet" crossorigin href="https://cdn.jsdelivr.net/npm/katex@0.10.2/dist/katex.min.css" integrity="sha384-yFRtMMDnQtDRO8rLpMIKrtPCD5jdktao2TV19YiZYWMDkUR5GQZR/NOVTdquEx1j"&gt; &lt;script defer crossorigin src="https://cdn.jsdelivr.net/npm/katex@0.10.2/dist/katex.min.js" integrity="sha384-9Nhn55MVVN0/4OFx7EE5kpFBPsEMZxKTCnA+4fqDmg12eCTqGi6+BB2LjY8brQxJ" onload="(() =&gt; { const todo = []; // don't mutate document while iterating function processMath(prev, code, displayMode) { prev.splitText(prev.textContent.length - 1).remove(); // remove [ code.childNodes[0].splitText(code.textContent.length - 2).remove(); // remove \] const span = document.createElement('span'); katex.render(code.textContent, span, {displayMode: displayMode, throwOnError: false}); code.parentNode.replaceChild(span, code); } for (const code of document.getElementsByTagName('code')) { const prev = code.previousSibling; if (prev &amp;&amp; prev.nodeType === Node.TEXT_NODE) { if (/\[$/.test(prev.textContent) &amp;&amp; /\\\]$/.test(code.textContent)) { todo.push(() =&gt; processMath(prev, code, true)); } else if (/\($/.test(prev.textContent) &amp;&amp; /\\\)$/.test(code.textContent)) { todo.push(() =&gt; processMath(prev, code, false)); } } } for (const f of todo) f(); })()"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- The following HTML is converted from ```md The quadratic formula is \[` x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}\text{.} \]` The quadratic formula is \(` x = \frac{-b \pm \sqrt{b^2-4ac}}{2a} \)`. ``` --&gt; &lt;p&gt;The quadratic formula is [&lt;code&gt; x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}\text{.} \]&lt;/code&gt;&lt;/p&gt; &lt;p&gt;The quadratic formula is (&lt;code&gt; x = \frac{-b \pm \sqrt{b^2-4ac}}{2a} \)&lt;/code&gt;.&lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>The purpose is to take source Markdown</p> <pre class="lang-none prettyprint-override"><code>The quadratic formula is \[` x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}\text{.} \]` </code></pre> <p>which is processed into the HTML</p> <pre class="lang-html prettyprint-override"><code>&lt;p&gt;The quadratic formula is [&lt;code&gt; x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}\text{.} \]&lt;/code&gt;&lt;/p&gt; </code></pre> <p>And process the block defined by <code>\[` ... \]`</code> into display-style math and <code>\(` ... \)`</code> into inline-style math. (Specific syntax domain issue: the <code>`</code> is uniformly <em>after</em> the brackets because without at least one being inside the markdown code block, we can't tell the difference between the markdown <code>\(`code`\)</code> and <code>(`code`)</code>, the latter of which we do not want to process.) An alternative syntax would be <code>$` ... `$</code> for inline style and <code>$$` ... `$$</code> for display style, but I went with the newer LaTeX-style brackets over the older TeX-style dollars for personal preference. (Feel free to argue why the dollars would be better, if you want!)</p> <p>General review is of course welcome, but here's a few specific points to look at:</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/previousSibling#Notes" rel="nofollow noreferrer">Node.previousSibling</a> supposedly behaves subtly differently on Gecko and Blink. Did I handle this correctly on both engines? (EdgeHTML, disappearing as it is?)</li> <li>All of my custom code is stuffed into katex.onload; this feels icky to me, but it avoids adding globals (other than <code>katex</code>).</li> <li>KaTeX offers <a href="https://katex.org/docs/browser.html#ecmascript-module" rel="nofollow noreferrer">ECMAScript module loading support</a>, but my attempt to use it was noticeably slower (without throttling my connection!), probably due to accidentally serializing something that didn't need to be. Is it better to use the module loading if it's available?</li> <li>Is this a proper use of <code>&lt;link rel="preload"&gt;</code>? (My daily driver is FireFox which has preloading disabled because of an issue, but Chrome shows a render time improvement when throttled to 3G speeds at least.)</li> <li>I don't use Javascript often, so general style issues and browser support. (The markdown syntax was chosen specifically so that noscript fallback isn't <em>too</em> horrid.)</li> </ul> <p>End note: whatever syntax is used should support display-style math within a paragraph, as convention is to treat even display-style math as part of the sentence of the paragraph containing it. Otherwise, <code>```math</code> is translated into <code>&lt;pre&gt;&lt;code class="language-math"&gt;</code> per the CommonMark spec, which is a great target for translating. Unfortunately, this precludes putting a display-style into a paragraph, and makes syntax distinctly different from inline. The bracket style supports almost this style of fencing due to variable-width fences, though: <code>\[```</code>/<code>\]```</code> works just fine, and embeds the resulting processed <code>&lt;span&gt;</code> in a <code>&lt;p&gt;</code> as is semantically correct. (Bare <code>$</code>/<code>$$</code> or <code>\[</code>/<code>\(</code> should also be avoided as these require support from the markdown engine to avoid mangling the contents, whereas literal code blocks give us this for free.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T04:35:59.517", "Id": "428647", "Score": "0", "body": "See also [pulldown-cmark's issue tracker](https://github.com/raphlinus/pulldown-cmark/issues/6#issuecomment-498517534) where I wrote next-to too much about the potential for math extensions to CommonMark markdown. (It includes a slightly modified version of this snippet that handles both bracket-style and dollar-style.)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T03:48:56.393", "Id": "221623", "Score": "2", "Tags": [ "javascript", "html", "markdown", "tex" ], "Title": "KaTeX extension to Markdown" }
221623
<p>To practice my JavaScript skills, I wrote a phrase scrambler. I would appreciate feedback on code efficiency and readability, as I want to know the best practices for further development.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function scramble() { let phrase = document.getElementById('phrase').value; phrase = phrase.split(''); let newPhrase = ""; let length = phrase.length; for(let i = 0; i &lt; length; i++) { let randomNumber = Math.floor(Math.random() * phrase.length); newPhrase += phrase[randomNumber]; phrase.splice(randomNumber, 1); } let output = document.createElement("p"); let output_text = document.createTextNode(newPhrase); output.appendChild(output_text); document.getElementById('output').appendChild(output); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en-US"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Phrase Scrambler&lt;/title&gt; &lt;script src="scramble.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body bgcolor="pink"&gt; &lt;h1&gt;Phrase Scrambler&lt;/h1&gt; &lt;form action="" method="post"&gt; &lt;label&gt;Phrase:&lt;/label&gt; &lt;input type="text" id="phrase"&gt;&lt;br&gt; &lt;button type="button" onclick="scramble()"&gt;Scramble&lt;/button&gt; &lt;/form&gt; &lt;div id="output"&gt; &lt;!-- Output goes here --&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T06:47:17.160", "Id": "428663", "Score": "1", "body": "Is it ok that the scramble has a statistical chance on yielding the exact same result as the source?" } ]
[ { "body": "<p>When I first saw the words \"phrase scrambler\", I thought you would split the phrase into words, not individual characters, and scramble these. I expected your code to solve interesting problems like:</p>\n\n<ul>\n<li>If the phrase starts with an uppercase letter and also contains lowercase letters, make sure that the scrambled phrase also starts with an uppercase letter, making the previously first character lowercase.</li>\n<li>Do not rip emojis apart.</li>\n<li>Split the phrase into words and scramble these.</li>\n<li>Split the phrase into words, scramble each word individually, and then scramble the words. (It would be interesting whether it would still be possible for humans to guess the original phrase.)</li>\n</ul>\n\n<p>Your current code gets the job done efficiently and is easy to understand. To allow for the above improvements or experiments, you should extract the part that scrambles an array into its own function:</p>\n\n<pre><code>function scramble(arr, rnd) {\n const scrambled = [];\n ...\n return scrambled;\n}\n</code></pre>\n\n<p>Having this as a separate function means that you can easily test it. For that, you need a <a href=\"https://stackoverflow.com/questions/521295/seeding-the-random-number-generator-in-javascript\">predictable random number generator</a>. You can then define:</p>\n\n<pre><code>function predictable() {\n return ...; // From the Stack Overflow question linked above\n}\n\nfunction testScramble(str, expected) {\n const actual = scramble(str, predictable);\n if (actual !== expected) {\n console.log('scramble', str, 'is', actual, 'expected', expected);\n }\n}\n\ntest('hello', 'ohlel');\n// TODO: add more test cases\n</code></pre>\n\n<p>To make the <code>scramble</code> function faster, you need to know that <em>shuffle</em> is a common synonym, and the standard algorithm for shuffling an array is the <a href=\"https://en.m.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher–Yates shuffle</a>, which is pretty simple.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T06:13:42.553", "Id": "221628", "ParentId": "221625", "Score": "0" } }, { "body": "<h2>Reusable</h2>\n<p>One of programmings main attributes it the ability to reuse code. You should always write code with this in mind</p>\n<p>When you create code think about how you may need to do the same thing over and over. Write a function to do that task in such a way so that you can add it to a library. This will reduce the amount of work needed to complete the current project and future projects</p>\n<h2>User friendly</h2>\n<p>You can be the greatest programming in the world but if you lack good UI design skills your code will never be great</p>\n<p>It is more important to concentrate on the front end than how you do the back-end because users, the ones that ultimately pay for every line of code, never see a line of it</p>\n<p>This does not mean you can write bad code. You want reduce your work, and you get that by writing good code.</p>\n<p>Some good UI tips</p>\n<ul>\n<li>Reduce the amount of work a user must do to use your app is one of the best ways to create a good user interface.</li>\n<li>Be entertaining, animations and additional quirks go a long way to providing a good user experience. BUT never let the entertainment get in the way of usability.</li>\n<li>Provide feedback. Use tooltips, cursors... etc to help the user use the interface. Again the feedback should never get in the way of the interfaces basic use.</li>\n</ul>\n<h2>Javascript</h2>\n<ul>\n<li>Use direct object reference to access elements by their id</li>\n<li>Create utility functions to reduce code size and noise</li>\n<li>Use up to date JS syntax to reduce code size and keep your skills relevant</li>\n<li>In many cases <code>while</code> loops suit the algorithm better than <code>for</code> loops</li>\n<li><code>splice</code> will return an array of items spliced. You can use bracket notation to get the spliced item</li>\n</ul>\n<h2>DOM</h2>\n<ul>\n<li>Use CSS to hold page styles, don't embed style into the HTML</li>\n<li>If you are not relying on a server to process input you can avoid the <code>&lt;form&gt;</code> and associated overhead</li>\n<li>The input element will not always get focus on load. You can force focus in JS</li>\n<li>Don't add javascript code inline</li>\n</ul>\n<h2>Example</h2>\n<ul>\n<li>Uses utilities that I wrote for other apps.</li>\n<li>UI friendly\n<ul>\n<li>Focuses on text input so user need not click it to add content</li>\n<li>Scrambles on enter and button click</li>\n<li>Inserts new scrambled text at the top of the output so user need not scroll to see new result</li>\n<li>Reduce spacing between lines</li>\n<li>Does not scramble empty like strings</li>\n<li>Adds titles for tool tips to provide user feed back</li>\n<li>Adds placeholder to input for more information for the user</li>\n<li>Adds simple animation to focus users eye on new result and provide a little entertainment (I bet you use this version a few more second than average app doing the same basic functionality)</li>\n<li>Can be used without having to touch the mouse.</li>\n</ul>\n</li>\n<li>Uses CSS to set element styles</li>\n<li>Uses direct object reference to access elements (rather than <code>getElementById</code>)</li>\n</ul>\n<p>I also slightly changed how the phrase is scrambled. It first scrambles the words and then scrambles the characters in each word. The shuffle (JS utility) function takes a second argument that modifies each item as they are shuffled</p>\n<p>With all the extras and excluding the utility functions the code below is only a little longer then your original function and took me very little time to write.</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>// DOM utility functions\nconst tag = (type, props = {}) =&gt; Object.assign(document.createElement(type), props);\nconst insert = (el, ...sibs) =&gt; sibs.reduce(\n (el, sib) =&gt; (el.insertBefore(sib, el.children[0] ? el.children[0] : null), el), el\n);\nconst addEvent = (el, type, func, opts = {}) =&gt; (el.addEventListener(type, func, opts), el);\n\n\n// JS utility functions\nconst shuffle = (a, mod = i =&gt; i, l = a.length) =&gt; {\n while (l) { a.push(mod(a.splice(Math.random() * (l--) | 0, 1)[0])) } \n return a;\n};\n\n\n// Application code\nconst SCRAMBLE_FRAMES = 40; // in frames 40/60 is 2/3rds of a second\n\naddEvent(scrambleBut, \"click\", scramble);\naddEvent(phraseEl, \"keyup\", e =&gt; e.code === \"Enter\" &amp;&amp; scramble());\nphraseEl.focus();\nconst wordShuffle = word =&gt; shuffle([...word]).join(\"\");\nconst animateShuffle = (el, count = SCRAMBLE_FRAMES) =&gt; { \n el.textContent = shuffle(el.textContent.split(\" \"), wordShuffle).join(\" \");\n if (count &gt; 0) { requestAnimationFrame(()=&gt; animateShuffle(el, count -1)) } \n}\nfunction scramble() { \n const phraseText = phraseEl.value.trim();\n if (phraseText) {\n var scrambleRes;\n insert(outputEl, scrambleRes = tag(\"p\", {textContent: phraseText}));\n animateShuffle(scrambleRes);\n }\n phraseEl.focus();\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n background-color: pink;\n font-family: arial;\n}\np {\n margin-block-start: 0.2em;\n margin-block-end: 0.2em;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;h1&gt;Phrase Scrambler&lt;/h1&gt;\n&lt;label&gt;Phrase:&lt;/label&gt;\n&lt;input type=\"text\" id=\"phraseEl\" placeholder=\"Enter a phrase\" title=\"Type a phrase, hit enter or click scramble to scramble the phrase\"&gt;&lt;br&gt;\n&lt;button type=\"button\" id=\"scrambleBut\" title=\"Click to scramble current phrase\"&gt;Scramble&lt;/button&gt;\n&lt;div id=\"outputEl\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:00:42.623", "Id": "221658", "ParentId": "221625", "Score": "2" } } ]
{ "AcceptedAnswerId": "221658", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T05:20:53.340", "Id": "221625", "Score": "2", "Tags": [ "javascript", "html" ], "Title": "Phrase scrambler" }
221625
<p>I've implemented a thread pool in C++17. This is <em>not</em> backwards compatible with C++14, due to the usage of <code>std::invoke_result</code>, which is new to C++17.</p> <p>The focus of this question is on best practices, with the (hopefully) obvious observation that I <em>really</em> want to know if any of this is Looks Funny™ (i.e., any weird moves or things that generally look like they shouldn't be there).</p> <p>You can find the current implementation of this (with post-review fixes and whatnot) <a href="https://github.com/fbastos1/thread_pool_cpp17/" rel="nofollow noreferrer">here</a>.</p> <p>The implementation is divided between two files:</p> <p><strong>threadpool.h</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;thread&gt; #include &lt;future&gt; //packaged_task #include &lt;queue&gt; #include &lt;functional&gt; //bind #include &lt;mutex&gt; #include &lt;condition_variable&gt; #include &lt;type_traits&gt; //invoke_result class thread_pool { public: thread_pool(size_t thread_count); ~thread_pool(); //since std::thread objects are not copiable, it doesn't make sense for a thread_pool // to be copiable. thread_pool(const thread_pool &amp;) = delete; thread_pool &amp;operator=(const thread_pool &amp;) = delete; //F must be Callable, and invoking F with ...Args must be well-formed. template &lt;typename F, typename ...Args&gt; auto execute(F, Args&amp;&amp;...); private: //_task_container_base and _task_container exist simply as a wrapper around a // MoveConstructible - but not CopyConstructible - Callable object. Since an // std::function requires a given Callable to be CopyConstructible, we cannot // construct one from a lambda function that captures a non-CopyConstructible // object (such as the packaged_task declared in execute) - because a lambda // capturing a non-CopyConstructible object is not CopyConstructible. //_task_container_base exists only to serve as an abstract base for _task_container. class _task_container_base { public: virtual ~_task_container_base() {}; virtual void operator()() = 0; }; //_task_container takes a typename F, which must be Callable and MoveConstructible. // Furthermore, F must be callable with no arguments; it can, for example, be a // bind object with no placeholders. // F may or may not be CopyConstructible. template &lt;typename F&gt; class _task_container : public _task_container_base { public: //here, std::forward is needed because we need the construction of _f *not* to // bind an lvalue reference - it is not a guarantee that an object of type F is // CopyConstructible, only that it is MoveConstructible. _task_container(F &amp;&amp;func) : _f(std::forward&lt;F&gt;(func)) {} void operator()() override { _f(); } private: F _f; }; //returns a unique_ptr to a _task_container that wraps around a given function // for details on _task_container_base and _task_container, see above // This exists so that _Func may be inferred from f. template &lt;typename _Func&gt; static std::unique_ptr&lt;_task_container_base&gt; allocate_task_container(_Func &amp;&amp;f) { //in the construction of the _task_container, f must be std::forward'ed because // it may not be CopyConstructible - the only requirement for an instantiation // of a _task_container is that the parameter is of a MoveConstructible type. return std::unique_ptr&lt;_task_container_base&gt;( new _task_container&lt;_Func&gt;(std::forward&lt;_Func&gt;(f)) ); } std::vector&lt;std::thread&gt; _threads; std::queue&lt;std::unique_ptr&lt;_task_container_base&gt;&gt; _tasks; std::mutex _task_mutex; std::condition_variable _task_cv; bool _stop_threads = false; }; template &lt;typename F, typename ...Args&gt; auto thread_pool::execute(F function, Args &amp;&amp;...args) { std::unique_lock&lt;std::mutex&gt; queue_lock(_task_mutex, std::defer_lock); std::packaged_task&lt;std::invoke_result_t&lt;F, Args...&gt;()&gt; task_pkg( std::bind(function, args...) ); std::future&lt;std::invoke_result_t&lt;F, Args...&gt;&gt; future = task_pkg.get_future(); queue_lock.lock(); //this lambda move-captures the packaged_task declared above. Since the packaged_task // type is not CopyConstructible, the function is not CopyConstructible either - // hence the need for a _task_container to wrap around it. _tasks.emplace( allocate_task_container([task(std::move(task_pkg))]() mutable { task(); }) ); queue_lock.unlock(); _task_cv.notify_one(); return std::move(future); } </code></pre> <p><strong>threadpool.cpp</strong></p> <pre><code>#include &quot;threadpool.h&quot; thread_pool::thread_pool(size_t thread_count) { for (size_t i = 0; i &lt; thread_count; ++i) { //start waiting threads. Workers listen for changes through // the thread_pool member condition_variable _threads.emplace_back( std::thread( [&amp;]() { std::unique_lock&lt;std::mutex&gt; queue_lock(_task_mutex, std::defer_lock); while (true) { queue_lock.lock(); _task_cv.wait( queue_lock, [&amp;]() -&gt; bool { return !_tasks.empty() || _stop_threads; } ); //used by dtor to stop all threads without having to // unceremoniously stop tasks. The tasks must all be finished, // lest we break a promise and risk a future object throwing // an exception. if (_stop_threads &amp;&amp; _tasks.empty()) return; //to initialize temp_task, we must move the unique_ptr from the // queue to the local stack. Since a unique_ptr cannot be copied // (obviously), it must be explicitly moved. This transfers // ownership of the pointed-to object to *this, as specified in // 20.11.1.2.1 [unique.ptr.single.ctor]. auto temp_task = std::move(_tasks.front()); _tasks.pop(); queue_lock.unlock(); (*temp_task)(); } } ) ); } } thread_pool::~thread_pool() { _stop_threads = true; _task_cv.notify_all(); for (std::thread &amp;thread : _threads) { thread.join(); } } </code></pre> <p><strong>driver.cpp</strong> <em>(simple file to demonstrate usage. Not tested, does not need to be reviewed)</em></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &quot;threadpool.h&quot; int multiply(int x, int y) { return x * y; } int main() { thread_pool pool(4); std::vector&lt;std::future&lt;int&gt;&gt; futures; for (const int &amp;x : { 2, 4, 7, 13 }) { futures.push_back(pool.execute(multiply, x, 2)); } for (auto &amp;fut : futures) { std::cout &lt;&lt; fut.get() &lt;&lt; std::endl; } return 0; } </code></pre>
[]
[ { "body": "<p>Your code looks extremely nice and well-structured to me. It exhibits modern C++ coding idioms. You also include references to the standard in your code. All of these are greatly appreciated.</p>\n\n<p>Here are some suggestions:</p>\n\n<ol>\n<li><p>I like sorting <code>#include</code>s according to alphabetical order. Like this:</p>\n\n<pre><code>#include &lt;condition_variable&gt;\n#include &lt;functional&gt; //bind\n#include &lt;future&gt; //packaged_task\n#include &lt;mutex&gt;\n#include &lt;queue&gt;\n#include &lt;thread&gt;\n#include &lt;type_traits&gt; //invoke_result\n#include &lt;vector&gt;\n</code></pre></li>\n<li><p>You do not put you class in a namespace. I would suggest doing so.</p></li>\n<li><p>The constructor of <code>std::thread</code> passes the Callable object by rvalue reference. Why not keep consistent with it?</p></li>\n<li><p>Instead of saying</p>\n\n<pre><code>//F must be Callable, and invoking F with ...Args must be well-formed.\n</code></pre>\n\n<p>in a comment, why not express your intent with code?</p>\n\n<pre><code>template &lt;typename F, typename... Args,\n std::enable_if_t&lt;std::is_invocable_v&lt;F&amp;&amp;, Args&amp;&amp;...&gt;, int&gt; = 0&gt;\nauto execute(F&amp;&amp;, Args&amp;&amp;...);\n</code></pre></li>\n<li><p>You precede all of your private types and data members with an underscore. This is probably a styling issue, but it is not really necessary since private members can't introduce name clash anyway.</p></li>\n<li><p><code>std::unique_ptr&lt;_task_container_base&gt;</code> is repeated several types. Consider introducing a name for it. Furthermore, your <code>allocate_task_container</code> function repeats the return type. Instead of</p>\n\n<pre><code>return std::unique_ptr&lt;_task_container_base&gt;(\n new _task_container&lt;_Func&gt;(std::forward&lt;_Func&gt;(f))\n);\n</code></pre>\n\n<p>You can just use</p>\n\n<pre><code>return new _task_container&lt;_Func&gt;(std::forward&lt;_Func&gt;(f));\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T16:05:42.860", "Id": "429240", "Score": "0", "body": "Good advice (*especially* 4) - but regarding 6, wouldn't omitting the explicit `std::unique_ptr` constructor call would make that function ineligible for RVO? It is mandatory in C++17, but only happens when the operand is a prvalue of the same class type as the function return type (which wouldn't apply, had I just returned a `new`ed pointer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-08T01:00:03.960", "Id": "429308", "Score": "0", "body": "@osuka_ RVO elides the move constructor needed to construct the return value from the returned prvalue. When you omit the explicit constructor call, you actually optimized it yourself." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T04:09:20.473", "Id": "221823", "ParentId": "221626", "Score": "2" } }, { "body": "<ol>\n<li><pre><code>//since std::thread objects are not copiable, it doesn't make sense for a thread_pool\n// to be copiable.\n</code></pre>\n\n<p>True. The default copy constructor would be ill-formed, so it is not emitted, so you don't need to manually disable it. Same for the assignment operator. It's even worse for <code>std::mutex</code> and <code>std::condition_variable</code> which cannot even be moved. You can make them and implicitly <code>thread_pool</code> movable by using a <code>std::unique_ptr</code> instead, which might be a reasonable trade-off in favor of usability.</p></li>\n<li><p>I am required to specify the number of threads in the thread-pool. It would be nice if it would default to <code>std::thread::hardware_concurrency()</code> instead.</p></li>\n<li><p>There is a lack of forwarding. I want </p>\n\n<pre><code>thread_pool{1}.execute([up = std::make_unique&lt;int&gt;(1)] (std::unique_ptr&lt;int&gt;) {},\n std::make_unique&lt;int&gt;(42));\n</code></pre>\n\n<p>to compile, but it doesn't, because your <code>std::bind(function, args...)</code> makes a copy of the arguments and the callable. Simply doing </p>\n\n<pre><code>std::bind(std::forward&lt;Function&gt;(function), std::forward&lt;Args&gt;(args)...)\n</code></pre>\n\n<p>does not compile either and I don't like <code>std::bind</code> in general, so here is a lambda instead:</p>\n\n<pre><code>[f = std::move(function), largs = std::make_tuple(std::forward&lt;Args&gt;(args)...)] () mutable {\n return std::apply(std::move(f), std::move(largs));\n}\n</code></pre>\n\n<p>I heard that C++20 will support this properly and allow <code>[largs = std::forward&lt;Args&gt;(args)...]</code>, but C++17 doesn't.</p></li>\n<li><p><code>[task(std::move(task_pkg))]() mutable { task(); }</code> can be replaced by <code>std::move(task_pkg)</code>.</p></li>\n<li><p><code>// This exists so that _Func may be inferred from f.</code>\nYou should not need to do that anymore with functions in C++17. That's what deduction guides are for. In theory you add</p>\n\n<pre><code>template &lt;typename F&gt;\n_task_container(F) -&gt; _task_container&lt;std::decay_t&lt;F&gt;&gt;;\n</code></pre>\n\n<p>and can then replace <code>allocate_task_container</code> with <code>_task_container</code>. In practice ... <a href=\"https://stackoverflow.com/questions/46103102\">things are broken</a>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T08:44:03.177", "Id": "222065", "ParentId": "221626", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T05:31:56.473", "Id": "221626", "Score": "11", "Tags": [ "c++", "object-oriented", "multithreading", "reinventing-the-wheel", "c++17" ], "Title": "C++17 thread pool" }
221626
<blockquote> <p>By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.</p> <p>What is the 10 001st prime number?</p> </blockquote> <p>How can I optimize this code?</p> <pre><code>#include &lt;iostream&gt; bool is_prime(int num) { for (int i = 2; i &lt;= num/2; ++i) { if (num % i == 0) { return false; } } return true; } int main() { int count = 2; for (int i = 5; ; i = i+2) { if (is_prime(i)) { count++; } if (count == 10001) { std::cout &lt;&lt; i; return 0; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T07:17:48.900", "Id": "428665", "Score": "0", "body": "Try this - https://codereview.stackexchange.com/questions/136328/find-the-10001st-prime-number-in-c" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:50:48.097", "Id": "428738", "Score": "3", "body": "This is all about using a better algorithm. https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" } ]
[ { "body": "<p>You really need a better algorithm. Look into <strong>Sieve of Eratosthenes</strong> for a good first prime sieve to implement. That avoids (expensive) division, using instead only addition and simple multiplications (I'm including <code>%</code> as \"division\" here).</p>\n\n<p>In <code>is_prime</code>, you really only need to try dividing by the previously discovered primes, rather than by all numbers. If you don't want to store the discovered primes, you can still reduce to testing against only odd numbers, since you only ever call it with odd <code>num</code> argument. Also, there's no need to test all the way up to <code>num / 2</code> - if you've not found a factor before <code>std::sqrt(num)</code>, you won't find any.</p>\n\n<p>In <code>main()</code>, I recommend ending the output with a newline:</p>\n\n<pre><code> std::cout &lt;&lt; i &lt;&lt; '\\n';\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T19:57:11.853", "Id": "428759", "Score": "0", "body": "How large shall the SoE array be to find the 10001st prime?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T20:43:01.423", "Id": "428771", "Score": "1", "body": "@ThomasWeller Well considering that is the problem trying to be solved (the array size should be the the value of the 10001st prime) the only practical approach is to make it dynamic, though you could always just guess a sufficiently large number." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T22:17:13.780", "Id": "428783", "Score": "1", "body": "@ThomasWeller The probability that a number \"n\" is a prime, is around log(n). The integral of the logarithm is n\\*log(n)-n . Thus, we have around n\\*log(n)-n primes until n." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T20:08:24.763", "Id": "428937", "Score": "0", "body": "@LemonDrop: I really dislike guessing in a `tag:performance` review. I'm interested in the dynamic array approach. How do you cross out the multiples after increasing the size of the array?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T20:28:24.500", "Id": "428944", "Score": "0", "body": "@ThomasWeller The dynamic approach for the sieve though I'd imagine would be to expand the array, copy the old contents to the first part and then mark off in the new portion until you get back to the value where it stopped to expand. Though as peterh mentioned, there is actually a good approximation for how big the array needs to be, and as [this](https://stackoverflow.com/a/7559373/2085551) answer says, there is actually a safe upper bound of `M * (log M + log log M)` which can be used. Additionally there are segmented sieving algorithms which do it with much less memory in a dynamic way." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T08:04:01.343", "Id": "221629", "ParentId": "221627", "Score": "15" } }, { "body": "<p>Use better algorithms: <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"noreferrer\">Sieve_of_Eratosthenes</a></p>\n\n<p>You used a brute force algorithm. But even this can be highly improved.</p>\n\n<p>You increment by 2 each loop.</p>\n\n<pre><code> for (int i = 5; ; i = i+2) {\n</code></pre>\n\n<p>So you have noticed that all even numbers are not prime. You can improve on this. By incrementing by 2 then 4 then 2 then 4. This removes all multiples of 2 and 3 automatically.</p>\n\n<pre><code> int inc = 2;\n for (int i = 5; ; i += inc, inc = 6 - inc) {\n</code></pre>\n\n<p>The brute force check runs up to num/2</p>\n\n<pre><code> for (int i = 2; i &lt;= num/2; ++i)\n</code></pre>\n\n<p>Actually you can do better than that you only need to run up to the <code>sqrt(num)</code> anything larger than this will not divide into num exactly.</p>\n\n<pre><code> int limit = sqrt(num);\n for (int i = 2; i &lt;= limit; ++i)\n</code></pre>\n\n<p>Actually we can take this a step further. There is no need to divide by every number lower than <code>num</code>. Any number that is divisible by a prime is already checked by a prime smaller than it.</p>\n\n<p>For example there is no need to check 4. You already checked 2 and all numbers divisible by 4 are also divisible by 2, so need to do that check. In fact you can skip all numbers that are not prime.</p>\n\n<pre><code>bool is_prime(int num)\n{\n int limit = sqrt(num);\n for (auto const&amp; prime: primes) {\n {\n if (prime &gt; limit) {\n return true;\n }\n if (num % prime == 0) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T19:57:53.660", "Id": "428760", "Score": "0", "body": "How large shall the SoE array be to find the 10001st prime?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T20:12:47.683", "Id": "428762", "Score": "0", "body": "@ThomasWeller : https://codereview.stackexchange.com/q/221678/507" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T05:18:01.747", "Id": "428803", "Score": "0", "body": "I usually do `for (int i = 2; i*i <= n; ++i)` instead of `for (int i = 2; i <= sqrt(n); ++i)`. Not sure if the former offers any performance benefits... but I heard that multiplication is pretty fast out there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T08:58:36.717", "Id": "428842", "Score": "2", "body": "You pulled a fast one there in your last step: Your code doesn’t define `primes`, and defining it efficiently isn’t trivial. Well. Yes, it is. But then you end up with the sieve of Eratosthenes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T16:03:02.143", "Id": "428906", "Score": "0", "body": "@KonradRudolph. Not really. The `is_prime()` using the list of primes is perfectly good for brute force finding of primes. You just start from 2 and work up. So the above function fits squarely with the OP brute force attack he just needs to edit his code to record each new prime as it is discovered." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T16:55:32.577", "Id": "428911", "Score": "0", "body": "@MartinYork I wouldn’t know, since, as I implied, you only posted an incomplete fragment. For all I know the fragment could form part of the sieve since it needs some kind of definition of `primes` which is presumably updated progressively." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T16:01:09.410", "Id": "221664", "ParentId": "221627", "Score": "16" } } ]
{ "AcceptedAnswerId": "221664", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T06:05:22.273", "Id": "221627", "Score": "10", "Tags": [ "c++", "performance", "programming-challenge" ], "Title": "Project Euler #7 10001st prime in C++" }
221627
<pre><code>import threading import os import sys import time l=0 length=[] def File_Opener(keys,l): for lines in keys: l = l + len(lines)-1 length.append(l) l=0 if __name__ == "__main__": start=time.time() f=open(sys.argv[1],"r") print "File to be anaysed is %s" %sys.argv[1] Threads=[] keys=[] for i in range(100): try: for j in range(200000): keys.append(f.next()) except: pass t = threading.Thread(target=File_Opener,args=(keys,l)) t.start() keys=[] print "Created thread %d" %i Threads.append(t) for thread in Threads: thread.join() print "Total Length of words are", sum(length) print "Time taken is %f" %(time.time()-start) print "Done!!" </code></pre> <p>Issue : Takes 5x more time than non-multi threaded code.</p> <p>I am trying to get sum of all chars in a file of very big size. The reason why i used the for loop is to divide the file into small list and pass each to a thread and except is used for in case the file does't come complete in 200000 chars I want to know as to how it can be done with multi threading also. Doing it in python2.7 in Linux</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T08:41:40.197", "Id": "428671", "Score": "0", "body": "Are you trying to get the sum in the file, or have you already accomplished that and you are just looking for an optimal way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T08:59:17.507", "Id": "428673", "Score": "0", "body": "I have accomplished it but the time is the issue" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T12:04:09.883", "Id": "428710", "Score": "0", "body": "Please clarify what you're doing. What are `l`, `length`, `lines` and `keys`? As far as I can tell, you're iterating over the *characters* in `File_Opener`, not the lines. Are you counting lines, counting characters, or are you summing line count or summing character count? Why 100 and 200000? Why do you need multithreading to do this?" } ]
[ { "body": "<p>Before starting to talk about threads in Python, let's compare to a sequential implementation. I’ll start by building a test file using the following code:</p>\n\n<pre><code>import string\nimport random\n\nwith open('test.txt', 'w') as f:\n for _ in range(20000000):\n line = ''.join(random.choice(string.printable) for _ in range(random.randint(0, 10000)))\n print(line, file=f)\n</code></pre>\n\n<p>This is Python 3 syntax, and I could not recommend more to use it instead of the <a href=\"https://pythonclock.org/\" rel=\"nofollow noreferrer\">end-of-life Python 2.7</a>.</p>\n\n<p>Anyway, after a while, I have a 5.9G file of 64 or so million lines (yes, <code>string.printable</code> contains the newline character) so I stopped it. Let's read it and count the length of its lines.</p>\n\n<hr>\n\n<p>For starter (and you may have noticed in the snippet above), you should use the <code>with</code> statement to open files so you don't accidentally forget to close them. You can also iterate directly over the content of the file instead of using <code>next</code>; and if you want to know the line number (to spawn a thread each 200000 lines, for instance), you can always delegate the task to <code>enumerate</code>. This way, you’ll avoid using <code>range</code> instead of <code>xrange</code> and consume memory where you don't need to.</p>\n\n<p>Second, timing should be done using <a href=\"https://docs.python.org/2/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code></a> for better precision and less boilerplate. Let's start by timing the reading of the file only to get a ballpark figure of how much time we can expect to gain. We’ll use part of the <a href=\"https://docs.python.org/2/library/itertools.html#recipes\" rel=\"nofollow noreferrer\"><code>consume</code> recipe from <code>itertools</code></a>:</p>\n\n<pre><code>from collections import deque\n\n\ndef read_file(filename):\n with open(filename) as f:\n deque(f, maxlen=0)\n\n\nif __name__ == '__main__':\n import timeit\n time = timeit.timeit('read_file(\"test.txt\")', 'from __main__ import read_file', number=1)\n print('execution took {}s'.format(time))\n</code></pre>\n\n<p>Result is <code>execution took 41.8203251362s</code> on my machine. This is roughly as fast as I can expect the file to be read… without taking caching into account. If we change the timing part to <code>min(timeit.repeat('read_file(\"test.txt\")', 'from __main__ import read_file', number=1, repeat=5))</code> we get somewhere around 3.5s.</p>\n\n<hr>\n\n<p>Now, on to counting characters. As I read it, you want to remove the newline character that is found at the end of each line. You can, as you do here, subtract 1 from each line length; or, alternatively, sum each line length and subtract the amount of lines afterwards. The second approach is easier as we can use <code>map</code> to produce a list of all line lengths and then, <code>sum</code> it before subtracting its <code>len</code>:</p>\n\n<pre><code>def count_characters(filename):\n with open(filename) as f:\n line_lengths = map(len, f)\n return sum(line_lengths) - len(line_lengths)\n</code></pre>\n\n<p>Timings approaches the same 40s figure for a single execution, but is about 6.5s on repeated executions. This is only 3 seconds of counting characters in 64 million lines; that's somewhat acceptable, but <code>map</code> is building a list in memory which is 64 million items long, so maybe we could speed things up if we didn't:</p>\n\n<pre><code>def count_characters(filename):\n count = 0\n with open(filename) as f:\n for line in f:\n count += len(line) - 1\n return count\n</code></pre>\n\n<p>Unfortunately, a <code>for</code> loop in Python is slower than a <code>for</code> loop in C (which is what <code>map</code> does) so this code is not faster (albeit being roughly as fast).</p>\n\n<hr>\n\n<p>Now, trying to speed things up. To parallelize tasks on chunk of data, we usually use <code>map</code> from <a href=\"https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool\" rel=\"nofollow noreferrer\"><code>multiprocessing.Pool</code></a>. But serializing this much data to feed other processes takes time and isn't worth it. So we are left trying to use <code>threading</code> as you did. However, due to the <a href=\"https://stackoverflow.com/q/1294382/5069029\">GIL</a>, you will not be able to run more than one thread in parallel and will be either reading the file or summing the lines; exactly as it is done in sequential code, but you’ll have more overheads due to using threads and helper data structures to move data around. So all in all, for this kind of problem, you’re better off sticking to the sequential implementation.</p>\n\n<p>But let's analyze your code anyway:</p>\n\n<ul>\n<li>The <code>l</code> parameter is useless, since it's an integer, it is immutable and the local version on each thread won't interfere with others so passing it as a parameter with seemingly a value of 0 and then resetting it to 0 after the computation is useless;</li>\n<li><p>Contrarily, the <code>length</code> list as a global variable is more problematic, I’d rather pass it as a parameter, leading to the threaded functions being:</p>\n\n<pre><code>def count_characters_in_chunk(lines, accumulator):\n length = sum(len(line) - 1 for line in lines)\n accumulator.append(length)\n</code></pre></li>\n<li><p>As said previously, organizing lines into chunks without prior knowledge of its length can be done using <code>enumerate</code> but we need to account for the last chunk not being the full size, if any:</p>\n\n<pre><code>def count_characters_in_file(filename, chunk_size=200000):\n threads = []\n lengths = []\n\n with open(filename) as f:\n lines = []\n for line_number, line in enumerate(f, start=1):\n lines.append(line)\n if line_number % chunk_size == 0:\n t = threading.Thread(target=count_characters, args=(lines, lengths))\n t.start()\n threads.append(t)\n lines = []\n\n if lines:\n t = threading.Thread(target=count_characters, args=(lines, lengths))\n t.start()\n threads.append(t)\n\n for t in threads:\n t.join()\n return sum(lengths)\n</code></pre></li>\n</ul>\n\n<p>However, there is still two issues with this code:</p>\n\n<ol>\n<li>The repetition of thread management is ugly and error-prone, plus the manual handling of the <code>lines</code> list is unnecessarily verbose. You can use <a href=\"https://docs.python.org/2/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice</code></a> to simplify all that;</li>\n<li>The use of a simple list to store resulting lengths is a bad habit to have as threaded code is prone to race-conditions (although highly unlikely in this case) that can lead to loss of data. You should use a <a href=\"https://docs.python.org/2/library/queue.html\" rel=\"nofollow noreferrer\"><code>Queue.Queue</code></a> instead.</li>\n</ol>\n\n<p>Final code being:</p>\n\n<pre><code>import itertools\nimport threading\nimport Queue\n\n\ndef extract_from_queue(queue):\n while not queue.empty():\n yield queue.get()\n\n\ndef count_characters(lines, accumulator):\n length = sum(len(line) - 1 for line in lines)\n accumulator.put(length)\n\n\ndef count_characters_in_file(filename, chunk_size=200000):\n threads = []\n lengths = Queue.Queue()\n\n with open(filename) as f:\n while True:\n lines = list(itertools.islice(f, chunk_size))\n if not lines:\n break\n t = threading.Thread(target=count_characters, args=(lines, lengths))\n t.start()\n threads.append(t)\n\n for t in threads:\n t.join()\n return sum(extract_from_queue(lengths))\n\n\nif __name__ == '__main__':\n import sys\n count_characters_in_file(sys.argv[1])\n</code></pre>\n\n<p>But timings using caching indicates 44 seconds on my machine, so not really worth it given the speed and simplicity of the sequential implementation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:07:59.667", "Id": "428818", "Score": "0", "body": "Is the threading implementation done by me correct and is there any possible improvement in the threading script? I actually want to demonstrate the time status for operation of file analysis when done using multi threading multiprocessing and multiplexing. Is the multi threading version of mine accurate enough. As you mentioned to change the for loop with enumerate that would load the full file first but then diving that file into small parts for each threads would be more expensive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T09:29:11.430", "Id": "428844", "Score": "0", "body": "@Divyanshu Please see updated answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T12:45:05.877", "Id": "221646", "ParentId": "221630", "Score": "3" } } ]
{ "AcceptedAnswerId": "221646", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T08:05:48.063", "Id": "221630", "Score": "1", "Tags": [ "python", "multithreading", "python-2.x" ], "Title": "Reading a long file and getting sum of chars by multithreading" }
221630
<p>I wrote this code. </p> <p>It works, but I think there is a more elegant and Pythonic way to this task. </p> <ol> <li>Groupby and count the different occurences</li> <li>Get the sum of all the occurences</li> <li><p>Divide each occurrence by the total of the occurrences and get the percentage</p> <pre><code>#Creating the dataframe ##The cluster column represent centroid labels of a clustering alghoritm df=pd.DataFrame({'char':['a','b','c','d','e'], 'cluster':[1,1,2,2,2]}) #Counting the frequency of each labels cluster_count=df.groupby('cluster').count() #Calculating the sum of the frequency cluster_sum=cluster_count.sum() #Normalizing the frequency cluster_prct=cluster_count.char.apply(lambda x: 100*x/cluster_sum) print(cluster_prct) </code></pre></li> </ol> <p><strong>Output:</strong></p> <pre><code>cluster 1 40.0 2 60.0 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T11:20:03.473", "Id": "428697", "Score": "0", "body": "For what Python version did you write this? Where does the output come from?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T11:24:02.567", "Id": "428700", "Score": "0", "body": "@Mast for Python 3.0. The output comes out from `print(cluster_prct)`. I edited the question." } ]
[ { "body": "<p>I think your code is already nearly optimal and Pythonic. But there is some little things to improve:</p>\n\n<ul>\n<li><code>cluster_count.sum()</code> returns you a Series object so if you are working with it outside the Pandas, it is better to specify the column: <code>cluster_count.char.sum()</code>. This way you will get an ordinary Python integer.</li>\n<li>Pandas has an ability to manipulate with columns directly so instead of <code>apply</code> function usage you can just write arithmetical operations with column itself: <code>cluster_count.char = cluster_count.char * 100 / cluster_sum</code> (note that this line of code is in-place work).</li>\n</ul>\n\n<p>Here is the final code:</p>\n\n<pre><code>df = pd.DataFrame({'char':['a','b','c','d','e'], 'cluster':[1,1,2,2,2]})\ncluster_count=df.groupby('cluster').count()\ncluster_sum=sum(cluster_count.char)\ncluster_count.char = cluster_count.char * 100 / cluster_sum\n</code></pre>\n\n<hr>\n\n<p><strong>Edit 1:</strong> You can do the magic even without <code>cluster_sum</code> variable, just in one line of code:</p>\n\n<p><code>cluster_count.char = cluster_count.char * 100 / cluster_count.char.sum()</code></p>\n\n<p>But I am not sure about its perfomance (it can probably recalculate the sum for each group).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T10:29:20.407", "Id": "221638", "ParentId": "221636", "Score": "6" } }, { "body": "<p>Just to add in my 2 cents here:</p>\n\n<p>You can approach this with <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.value_counts.html\" rel=\"nofollow noreferrer\"><code>series.value_counts()</code></a> which has a <code>normalize</code> parameter.</p>\n\n<p>From the docs:</p>\n\n<blockquote>\n <p>normalize : boolean, default False\n If True then the object returned will contain the relative frequencies of the unique values.</p>\n</blockquote>\n\n<p>Using this we can do:</p>\n\n<pre><code>s=df.cluster.value_counts(normalize=True,sort=False).mul(100) # mul(100) is == *100\ns.index.name,s.name='cluster','percentage_' #setting the name of index and series\nprint(s.to_frame()) #series.to_frame() returns a dataframe\n</code></pre>\n\n<hr>\n\n<pre><code> percentage_\ncluster \n1 40.0\n2 60.0\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-24T07:39:03.787", "Id": "222846", "ParentId": "221636", "Score": "3" } } ]
{ "AcceptedAnswerId": "221638", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T09:06:20.183", "Id": "221636", "Score": "5", "Tags": [ "python", "python-3.x", "pandas" ], "Title": "Groupby count, then sum and get the percentage" }
221636
<p>This is a <a href="https://leetcode.com/problems/longest-consecutive-sequence/submissions/" rel="nofollow noreferrer">Leetcode problem</a> -</p> <blockquote> <p><em>Given an unsorted array of integers, find the length of the longest consecutive elements' sequence.</em></p> <p><em>Your algorithm should run in <span class="math-container">\$O(n)\$</span> complexity.</em></p> <p><strong><em>Example -</em></strong></p> <pre><code>Input: [100, 4, 200, 1, 3, 2] Output: 4 # Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. </code></pre> </blockquote> <p>Here is my solution to this challenge -</p> <pre><code>def longestConsecutive(nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 nums = list(dict.fromkeys(nums)) nums.sort() count = 1 longest_streak = [] for index, value in enumerate(nums): if index + 1 &gt;= len(nums): break if nums[index + 1] == value + 1: count += 1 longest_streak.append(count) else: count = 1 if not longest_streak: return count return max(longest_streak) </code></pre> <p>Here is my Leetcode result -</p> <blockquote> <p><a href="https://i.stack.imgur.com/56Ynk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/56Ynk.png" alt="enter image description here"></a></p> </blockquote> <p>So, I would like to know whether I could make this program faster and more efficient. </p> <p><strong>NOTE</strong> - Though my solution got accepted, I really have no idea about the time complexity of my program. Maybe someone could cover that too?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T11:51:56.423", "Id": "428709", "Score": "0", "body": "Isn't nums.sort() O(n*logn)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T13:38:09.407", "Id": "428721", "Score": "0", "body": "It is? Honestly, I don't really know why. Could you include this in an answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:50:58.147", "Id": "428739", "Score": "1", "body": "@Justin It is, as Python uses the [Timsort](https://en.wikipedia.org/wiki/Timsort)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T05:43:53.897", "Id": "429142", "Score": "0", "body": "@Justin you can just check the Solution that is provided [here](https://leetcode.com/problems/longest-consecutive-sequence/solution/) . It has a good explanation for three cases: O(n^2), O(n*logn) and O(n). Yours is the second one, and you can see how to do it in O(n) there. You can also check out the Discussions!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T08:27:34.223", "Id": "429167", "Score": "1", "body": "Thanks, @a_faulty_star. I will definitely have a look. Seems like the best thing to do. Thanks again!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T09:30:15.410", "Id": "221637", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "programming-challenge" ], "Title": "(Leetcode) Longest consecutive sequence in Python" }
221637
<p>I wrote a little program that adds and subtracts some algebraic expressions.</p> <p>In my code <code>(2 x 3)</code> represents <span class="math-container">\$2x^3\$</span>.</p> <p>The purpose of this post is to get some feedback; moreover, I would like to know how to make it perform better and improve it.</p> <p>I ran this program on a Mac with SBCL + Emacs.</p> <pre><code>(defun compute (exp) (cond ((term? exp) exp) ((expression? exp) (make (compute (first-expression exp)) (compute (second-expression exp)) (operator exp))) (t (error "Unknown Expression Type --COMPUTE" exp)))) (defun term? (exp) (or (numberp exp) (monomial? exp))) (defun monomial? (exp) (and (consp exp) (numberp (car exp)) (symbolp (car (cdr exp))) (numberp (car (cdr (cdr exp)))))) (defun expression? (exp) (or (eql (car exp) '+) (eql (car exp) '*) (eql (car exp) '-))) (defun first-expression (exp) (car (cdr exp))) (defun second-expression (exp) (car (cdr (cdr exp)))) (defun operator (exp) (car exp)) (defun make (e1 e2 op) (cond ((eql op '+) (make-addition e1 e2)) ((eql op '-) (make-subtraction e1 e2)) (t (make-product e1 e2)))) </code></pre> <p>I wrote the following higher order procedures because version 1 had a lot patterns.</p> <pre><code>(defun make-addition (e1 e2) (make-exp e1 e2 '+ #'add-monomials)) (defun make-subtraction (e1 e2) (make-exp e1 e2 '- #'subtract-monomials)) (defun make-exp (e1 e2 op term) (cond ((eql e1 0) e2) ((eql e2 0) e1) ((&amp;number? e1 e2) (+ e1 e2)) ((&amp;monomial? e1 e2) (funcall term e1 e2)) (t (list op e1 e2)))) ;; make-product (defun make-product (e1 e2) (list '* e1 e2)) (defun &amp;number? (e1 e2) (and (numberp e1) (numberp e1))) (defun &amp;monomial? (e1 e2) (and (monomial? e1) (monomial? e2))) (defun add-monomials (e1 e2) (compute-monomials e1 e2 #'+ '+)) (defun subtract-monomials (e1 e2) (compute-monomials e1 e2 #'- '-)) (defun compute-monomials (e1 e2 term op) (if (same-variable? e1 e2) (make-monomial (funcall term (coeff e1) (coeff e2)) (variablex e1) (exponent e1)) (list op e1 e2p))) (defun variablex (exp) (car (cdr exp))) (defun same-variable? (e1 e2) (eql (variablex e1) (variablex e2))) (defun make-monomial (coeff var exp) (list coeff var exp)) (defun coeff (exp) (car exp)) (defun exponent (exp) (car (cdr (cdr exp)))) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-27T07:50:33.670", "Id": "432035", "Score": "0", "body": "you might want to improve indentation. It's off in many places and makes the code difficult to read. Maybe your editor uses tab characters and you are copying the code with tabs? Don't use tabs then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-27T08:03:39.483", "Id": "432036", "Score": "0", "body": "are there any performance problems? Which ones?" } ]
[ { "body": "<p>Make sure your code is indented correctly here. It isn't.</p>\n\n<p>Then document your code at least with some minimum amount of explanations and structure.</p>\n\n<p>Common Lisp has ways to comment code:</p>\n\n<pre><code>;;;; program comment\n\n;;; section comment\n\n(defun bar ()\n\n \"This is a retrievable function documentation\nstring, which\ncan be spread over many lines.\"\n\n (let ((foo (random 100)))\n ;; indented code comment\n (+ foo 3) ; inline code comment\n ))\n\n#|\n Block comments\n|#\n</code></pre>\n\n<p>Then one can retrieve the function documentation with some IDE keystrokes/mechanisms and:</p>\n\n<pre><code>(documentation 'bar 'function)\n</code></pre>\n\n<p>Some hints:</p>\n\n<pre><code>(defun expression? (exp)\n (or (eql (car exp) '+)\n (eql (car exp) '*)\n (eql (car exp) '-)))\n\n(case exp\n ((+ * -) t)\n (otherwise nil))\n\n(member (car exp) '(+ * -))\n\n(defun first-expression (exp) (car (cdr exp)))\n\n(cadr exp)\n(second exp)\n\n(defun second-expression (exp) (car (cdr (cdr exp))))\n\n(caddr exp)\n(third exp)\n\n\n(defun make (e1 e2 op)\n (cond ((eql op '+)\n (make-addition e1 e2))\n ((eql op '-)\n (make-subtraction e1 e2))\n (t (make-product e1 e2))))\n\n(case op\n (+ ...)\n (- ...)\n (otherwise ...))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-27T08:03:48.947", "Id": "223047", "ParentId": "221642", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T12:16:18.770", "Id": "221642", "Score": "5", "Tags": [ "performance", "common-lisp", "symbolic-math" ], "Title": "Evaluator for adding and subtracting algebraic expressions" }
221642
<p>In the <span class="math-container">\$k\$</span>-shortest path problem, we are searching for (at most) <span class="math-container">\$k\$</span> distinct, shortest paths connecting two given terminal nodes. You can see the previous version <a href="https://codereview.stackexchange.com/questions/116292/k-shortest-path-algorithm-in-java">here</a>. This implementation, however, represents the intermediate paths in the open list as linked lists so that extending such a path by one node runs in <span class="math-container">\$\Theta(1)\$</span> time. My code is below:</p> <p><strong><code>net.coderodde.graph.kshortest.impl.FasterDefaultShortestPathFinder</code></strong></p> <pre><code>package net.coderodde.graph.kshortest.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.PriorityQueue; import java.util.Queue; import net.coderodde.graph.DirectedGraphNode; import net.coderodde.graph.DirectedGraphWeightFunction; import net.coderodde.graph.kshortest.AbstractKShortestPathFinder; import net.coderodde.graph.kshortest.Path; /** * This class implements a rather simple k-shortest path algorithm from * &lt;a href="https://en.wikipedia.org/wiki/K_shortest_path_routing#Algorithm"&gt; * Wikipedia * &lt;/a&gt;. This version improves * {@link net.coderodde.graph.kshortest.impl.DefaultKShortestPathFinder} via * using linked lists of nodes as the paths. * * @author Rodion "rodde" Efremov * @version 1.6 (Jun 4, 2019) */ public class FasterDefaultKShortestPathFinder extends AbstractKShortestPathFinder { @Override public List&lt;Path&gt; findShortestPaths(DirectedGraphNode source, DirectedGraphNode target, DirectedGraphWeightFunction weightFunction, int k) { Objects.requireNonNull(source, "The source node is null."); Objects.requireNonNull(target, "The target node is null."); Objects.requireNonNull(weightFunction, "The weight function is null."); checkK(k); List&lt;LinkedPathNode&gt; linkedPathTails = new ArrayList&lt;&gt;(k); Map&lt;DirectedGraphNode, Integer&gt; countMap = new HashMap&lt;&gt;(); Queue&lt;LinkedPathNode&gt; HEAP = new PriorityQueue&lt;&gt;(); HEAP.add(new LinkedPathNode(weightFunction, source)); while (!HEAP.isEmpty() &amp;&amp; countMap.getOrDefault(target, 0) &lt; k) { LinkedPathNode currentPath = HEAP.remove(); DirectedGraphNode endNode = currentPath.getTailNode(); countMap.put(endNode, countMap.getOrDefault(endNode, 0) + 1); if (endNode.equals(target)) { linkedPathTails.add(currentPath); } if (countMap.get(endNode) &lt;= k) { for (DirectedGraphNode child : endNode.children()) { HEAP.add(currentPath.append(child)); } } } return convertListOfLinkedPathsToPaths(linkedPathTails); } private static final List&lt;Path&gt; convertListOfLinkedPathsToPaths( List&lt;LinkedPathNode&gt; linkedPathTails) { List&lt;Path&gt; paths = new ArrayList&lt;&gt;(linkedPathTails.size()); for (LinkedPathNode linkedPathNode : linkedPathTails) { paths.add(linkedPathNode.toPath()); } return paths; } } </code></pre> <p><strong><code>net.coderodde.graph.kshortest.impl.LinkedPathNode</code></strong></p> <pre><code>package net.coderodde.graph.kshortest.impl; import java.util.ArrayList; import java.util.Collections; import java.util.List; import net.coderodde.graph.DirectedGraphWeightFunction; import java.util.Objects; import net.coderodde.graph.DirectedGraphNode; import net.coderodde.graph.kshortest.Path; /** * This class represents a path in a graph. The only difference between * {@link net.coderodde.graph.kshortest.Path} is that this class implements the * path as a linked list of graph nodes. This arrangement allows us to extend * any given path by one graph node in constant time. * * @author Rodion "rodde" Efremov * @version 1.6 (Jun 4, 2019) */ final class LinkedPathNode implements Comparable&lt;LinkedPathNode&gt; { private final DirectedGraphWeightFunction weightFunction; private final DirectedGraphNode node; private final LinkedPathNode previousLinkedPathNode; private double totalCost; public LinkedPathNode(DirectedGraphWeightFunction weightFunction, DirectedGraphNode node) { this.weightFunction = Objects.requireNonNull( weightFunction, "The input weight function is null."); this.node = Objects.requireNonNull(node, "The input node is null."); this.totalCost = 0.0; this.previousLinkedPathNode = null; } LinkedPathNode(LinkedPathNode path, DirectedGraphNode node) { this.weightFunction = path.weightFunction; this.node = node; this.previousLinkedPathNode = path; this.totalCost += weightFunction.get(previousLinkedPathNode.node, node); } LinkedPathNode append(DirectedGraphNode node) { return new LinkedPathNode(this, node); } LinkedPathNode getPreviousLinkedPathNode() { return this.previousLinkedPathNode; } DirectedGraphNode getTailNode() { return this.node; } Path toPath() { List&lt;DirectedGraphNode&gt; path = new ArrayList&lt;&gt;(); LinkedPathNode node = this; while (node != null) { path.add(node.node); node = node.previousLinkedPathNode; } Collections.&lt;DirectedGraphNode&gt;reverse(path); return new Path(path, this.weightFunction); } @Override public int compareTo(LinkedPathNode o) { return Double.compare(totalCost, o.totalCost); } } </code></pre> <p><strong>Critique request</strong></p> <p>I would love to hear comments about naming conventions, maintainability and readability, but please tell me anything that comes to mind.</p> <p><strong>Miscellany</strong></p> <p>See <a href="https://github.com/coderodde/KShortestPathAlgorithms/tree/03571b39803a8d6e4f54c84f92efb461960da2c4" rel="nofollow noreferrer">this project</a> for all the missing Java files.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T12:25:44.083", "Id": "221643", "Score": "2", "Tags": [ "java", "algorithm", "linked-list", "pathfinding" ], "Title": "Faster k-shortest path algorithm in Java" }
221643
<p>In this post, I have the demo driver that benchmarks two <span class="math-container">\$k\$</span>-shortest path algorithms. The entire GitHub project is <a href="https://github.com/coderodde/KShortestPathAlgorithms/tree/03571b39803a8d6e4f54c84f92efb461960da2c4" rel="nofollow noreferrer">here</a>.</p> <p><strong><code>net.coderodde.graph.kshortest.Demo</code></strong></p> <pre><code>package net.coderodde.graph.kshortest; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import net.coderodde.graph.DirectedGraphNode; import net.coderodde.graph.DirectedGraphWeightFunction; import net.coderodde.graph.kshortest.impl.DefaultKShortestPathFinder; import net.coderodde.graph.kshortest.impl.FasterDefaultKShortestPathFinder; public class Demo { private static final int WARMUP_ITERATIONS = 5; private static final int BENCHMARK_ITERATIONS = 20; private static final int GRAPH_NODES = 5_000; private static final int GRAPH_ARCS = 50_000; private static final double MAX_WEIGHT = 1000.0; private static final int K = 25; public static void main(String[] args) { demo1(); long seed = System.currentTimeMillis(); Random random = new Random(seed); List&lt;DirectedGraphNode&gt; graph = constructGraph(GRAPH_NODES, GRAPH_ARCS, random); DirectedGraphWeightFunction weightFunction = new DirectedGraphWeightFunction(); addArcWeights(graph, weightFunction, MAX_WEIGHT, random); System.out.println("=== Graph constructed! Warming up... ==="); warmup(random, graph, weightFunction, K); System.out.println("=== Warming up complete! Benchmarking... ==="); benchmark(random, graph, weightFunction, K); } private static final List&lt;DirectedGraphNode&gt; constructGraph(int graphNodes, int graphArcs, Random random){ List&lt;DirectedGraphNode&gt; graph = new ArrayList&lt;&gt;(graphNodes); for (int i = 0; i &lt; graphNodes; i++) { graph.add(new DirectedGraphNode(i)); } for (int i = 0; i &lt; graphArcs; i++) { DirectedGraphNode tail = choose(graph, random); DirectedGraphNode head = choose(graph, random); tail.addChild(head); } return graph; } private static final void addArcWeights(List&lt;DirectedGraphNode&gt; graph, DirectedGraphWeightFunction weightFunction, double maxWeight, Random random) { for (DirectedGraphNode tail : graph) { for (DirectedGraphNode head : tail.children()) { weightFunction.put(tail, head, random.nextDouble() * maxWeight); } } } private static void warmup(Random random, List&lt;DirectedGraphNode&gt; graph, DirectedGraphWeightFunction weightFunction, int k) { run(false, WARMUP_ITERATIONS, random, graph, weightFunction, k); } private static void benchmark(Random random, List&lt;DirectedGraphNode&gt; graph, DirectedGraphWeightFunction weightFunction, int k) { run(true, BENCHMARK_ITERATIONS, random, graph, weightFunction, k); } private static List&lt;DirectedGraphNode&gt; randomNodes(List&lt;DirectedGraphNode&gt; graph, Random random, int size) { List&lt;DirectedGraphNode&gt; nodes = new ArrayList&lt;&gt;(size); for (int i = 0; i &lt; size; i++) { nodes.add(choose(graph, random)); } return nodes; } private static void run(boolean print, int iterations, Random random, List&lt;DirectedGraphNode&gt; graph, DirectedGraphWeightFunction weightFunction, int k) { AbstractKShortestPathFinder finder1 = new DefaultKShortestPathFinder(); AbstractKShortestPathFinder finder2 = new FasterDefaultKShortestPathFinder(); List&lt;DirectedGraphNode&gt; sourceNodes = randomNodes(graph, random, iterations); List&lt;DirectedGraphNode&gt; targetNodes = randomNodes(graph, random, iterations); List&lt;List&lt;Path&gt;&gt; results1 = new ArrayList&lt;&gt;(iterations); List&lt;List&lt;Path&gt;&gt; results2 = new ArrayList&lt;&gt;(iterations); long nanoTotalDuration1 = 0L; long nanoTotalDuration2 = 0L; for (int iter = 0; iter &lt; iterations; iter++) { DirectedGraphNode sourceNode = sourceNodes.get(iter); DirectedGraphNode targetNode = targetNodes.get(iter); long startTime = System.nanoTime(); List&lt;Path&gt; result1 = finder1.findShortestPaths( sourceNode, targetNode, weightFunction, k); long endTime = System.nanoTime(); long nanoDuration = endTime - startTime; nanoTotalDuration1 += nanoDuration; if (print) { System.out.println(finder1.getClass().getSimpleName() + " in " + (long)(1e-6 * nanoDuration) + " milliseconds."); } nanoTotalDuration1 += nanoDuration; results1.add(result1); } for (int iter = 0; iter &lt; iterations; iter++) { DirectedGraphNode sourceNode = sourceNodes.get(iter); DirectedGraphNode targetNode = targetNodes.get(iter); long startTime = System.nanoTime(); List&lt;Path&gt; result2 = finder2.findShortestPaths( sourceNode, targetNode, weightFunction, k); long endTime = System.nanoTime(); long nanoDuration = endTime - startTime; nanoTotalDuration2 += nanoDuration; if (print) { System.out.println(finder2.getClass().getSimpleName() + " in " + (long)(1e-6 * nanoDuration) + " milliseconds."); } results2.add(result2); } if (print) { System.out.println( "Algorithms agree: " + results1.equals(results2)); System.out.println( finder1.getClass().getSimpleName() + " in\n" + (long)(1e-6 * nanoTotalDuration1) + " milliseconds."); System.out.println(finder2.getClass().getSimpleName() + " in\n" + (long)(1e-6 * nanoTotalDuration2) + " millieconds."); } } private static &lt;T&gt; T choose(List&lt;T&gt; list, Random random) { return list.get(random.nextInt(list.size())); } private static void demo1() { // 1 4 // / \ / \ // 0 3 6 // \ / \ / // 2 5 DirectedGraphNode a = new DirectedGraphNode(0); DirectedGraphNode b = new DirectedGraphNode(1); DirectedGraphNode c = new DirectedGraphNode(2); DirectedGraphNode d = new DirectedGraphNode(3); DirectedGraphNode e = new DirectedGraphNode(4); DirectedGraphNode f = new DirectedGraphNode(5); DirectedGraphNode g = new DirectedGraphNode(6); // The edges above the line 0 - 6 have weight of 1.0. // The edges below the line 0 - 6 have weight of 2.0 DirectedGraphWeightFunction weightFunction = new DirectedGraphWeightFunction(); a.addChild(b); weightFunction.put(a, b, 1); a.addChild(c); weightFunction.put(a, c, 2); b.addChild(d); weightFunction.put(b, d, 1); c.addChild(d); weightFunction.put(c, d, 2); d.addChild(e); weightFunction.put(d, e, 1); d.addChild(f); weightFunction.put(d, f, 2); e.addChild(g); weightFunction.put(e, g, 1); f.addChild(g); weightFunction.put(f, g, 2); List&lt;Path&gt; paths = new FasterDefaultKShortestPathFinder() .findShortestPaths(a, g, weightFunction, 5); for (Path path : paths) { System.out.println(Arrays.toString(path.getNodeList().toArray())); } } } </code></pre> <p>Typical output follows:</p> <pre class="lang-none prettyprint-override"><code>Algorithms agree: true DefaultKShortestPathFinder in 31517 milliseconds. FasterDefaultKShortestPathFinder in 1304 millieconds. </code></pre> <p>Please tell me anything that comes to mind.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T12:30:42.107", "Id": "221644", "Score": "1", "Tags": [ "java", "graph", "benchmarking" ], "Title": "Benchmarking k-shortest path algorithms in Java without JMH" }
221644
<p>I was intrigued by <a href="https://stackoverflow.com/q/56395005/4717755">this question</a> on SO and was able to come up with a reasonably efficient answer, but I'm interested in learning about further optimizations. You can certainly look at <a href="https://stackoverflow.com/a/56434762/4717755">my answer</a> to that original question for some explanations of how I've implemented certain logic, but I'm happy to answer questions as well.</p> <pre class="lang-vb prettyprint-override"><code>Option Explicit Public Sub ShowFilePaths() Dim rootFolder As String rootFolder = SelectFolder Dim pathArray As Variant pathArray = GetAllFiles(rootFolder) Dim folderGroups As Object Set folderGroups = BuildFolderDictionary(pathArray) '--- when debugging, this block just clears the worksheet to make it ' easier to rerun and test the code On Error Resume Next Do Sheet1.UsedRange.rows.Ungroup Loop While Err.Number = 0 Sheet1.UsedRange.Clear Err.Clear On Error GoTo 0 '--- copy the array to the worksheet Const START_ROW As Long = 6 Dim pathRange As Range Set pathRange = Sheet1.Range("A" &amp; START_ROW).Resize(UBound(pathArray) + 1, 1) pathRange.Value = pathArray '------ now apply the indention levels to each line on the sheet ' and group the same rows Dim rowGroup As Variant Dim level As Long For Each rowGroup In folderGroups Dim theseRows As String theseRows = folderGroups(rowGroup) With pathRange.rows(theseRows) level = Len(rowGroup) - Len(Replace(rowGroup, "\", vbNullString)) - 1 .IndentLevel = level If level &lt; 8 Then .Group End If End With Next rowGroup End Sub Private Function SelectFolder() As String '--- returns the user-selected folder as a string Dim objShell As Object Dim objFolder As Object Set objShell = CreateObject("Shell.Application") Set objFolder = objShell.BrowseForFolder(0, "Select Folder", 0, 17) If Not objFolder Is Nothing Then SelectFolder = objFolder.self.Path End If End Function Private Function GetAllFiles(ByVal rootPath As String, _ Optional ByVal onlyFolders As Boolean = False) As Variant '--- returns a sorted array of all filepaths in the given directory path Dim dirOptions As String If onlyFolders Then dirOptions = """ /a:d-h-s /b /s" Else dirOptions = """ /a:-h-s /b /s" End If Dim fOut() As String fOut = Split(CreateObject("WScript.Shell").exec("cmd /c dir """ &amp; _ rootPath &amp; _ dirOptions).StdOut.ReadAll, _ vbNewLine) QuickSort fOut, LBound(fOut), UBound(fOut) '--- the pathArray skips the first position from the fOut array ' because it's always blank Dim pathArray As Variant ReDim pathArray(1 To UBound(fOut), 1 To 1) Dim i As Long For i = 1 To UBound(fOut) pathArray(i, 1) = fOut(i) Next i GetAllFiles = pathArray End Function Private Function BuildFolderDictionary(ByRef paths As Variant) As Object Dim folders As Object Set folders = CreateObject("Scripting.Dictionary") '--- scan all paths and create a dictionary of each folder and subfolder ' noting which items (rows) map into each dictionary Dim i As Long For i = LBound(paths) To UBound(paths) Dim folder As String Dim pos1 As Long If Not IsEmpty(paths(i, 1)) Then pos1 = InStrRev(paths(i, 1), "\") 'find the last folder separator folder = Left$(paths(i, 1), pos1) If Not folders.Exists(folder) Then '--- new (sub)folder, create a new entry folders.Add folder, CStr(i) &amp; ":" &amp; CStr(i) Else '--- extisting (sub)folder, add to the row range Dim rows As String rows = folders(folder) rows = Left$(rows, InStr(1, rows, ":")) rows = rows &amp; CStr(i) folders(folder) = rows End If End If Next i Set BuildFolderDictionary = folders End Function Private Sub QuickSort(ByRef Field() As String, ByVal LB As Long, ByVal UB As Long) '--- from https://stackoverflow.com/a/152333/4717755 Dim P1 As Long, P2 As Long, Ref As String, TEMP As String P1 = LB P2 = UB Ref = Field((P1 + P2) / 2) Do Do While (Field(P1) &lt; Ref) P1 = P1 + 1 Loop Do While (Field(P2) &gt; Ref) P2 = P2 - 1 Loop If P1 &lt;= P2 Then TEMP = Field(P1) Field(P1) = Field(P2) Field(P2) = TEMP P1 = P1 + 1 P2 = P2 - 1 End If Loop Until (P1 &gt; P2) If LB &lt; P2 Then Call QuickSort(Field, LB, P2) If P1 &lt; UB Then Call QuickSort(Field, P1, UB) End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T18:43:57.130", "Id": "429085", "Score": "0", "body": "You are correct about the Quicksort and that fixed my other issue. Nice answer." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T13:46:56.087", "Id": "221649", "Score": "3", "Tags": [ "performance", "vba" ], "Title": "Show File/Folder Hierachy as Grouped with Indentation" }
221649
<p>I'm looking into using my loop to combine and narrow down this piece of code into maybe a switch statement or other methods, how would I be able to achieve that? This is what I have so far which has worked for me but I also have other <code>items[i].ApplicationType</code> such as 'OneDrive', 'Teams', etc..</p> <pre><code>for(i = 0; i &lt; items.length; i++) { if(items[i].ComputerType == 'Windows' &amp;&amp; items[i].RequestType == 'Single User' &amp;&amp; items[i].ApplicationType == 'OneDrive') { ODwindows += 1; } else if(items[i].ComputerType == 'Windows' &amp;&amp; items[i].RequestType == 'Single User' &amp;&amp; items[i].ApplicationType == 'Teams') { Teamswindows += 1; } else if(items[i].ComputerType == 'Mac' &amp;&amp; items[i].RequestType == 'Single User' &amp;&amp; items[i].ApplicationType == 'OneDrive') { ODmac += 1; } else if(items[i].ComputerType == 'Mac' &amp;&amp; items[i].RequestType == 'Single User' &amp;&amp; items[i].ApplicationType == 'Teams') { Teamsmac += 1; } else if(items[i].ComputerType == 'Both' &amp;&amp; items[i].RequestType == 'Team' &amp;&amp; items[i].ApplicationType == 'OneDrive') { ODboth += 1; } else if(items[i].ComputerType == 'Both' &amp;&amp; items[i].RequestType == 'Team' &amp;&amp; items[i].ApplicationType == 'Teams') { Teamsboth += 1; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T14:42:25.887", "Id": "428728", "Score": "3", "body": "Please provide more context: what are the inputs, what do you do with the outputs, and what does this code accomplish? See [ask]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:22:38.180", "Id": "428731", "Score": "0", "body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T14:26:01.157", "Id": "221652", "Score": "1", "Tags": [ "javascript", "jquery", "html" ], "Title": "Combine multiple if statements with multiple properties" }
221652
<p>I implemented the LSDD changepoint detection method decribed in [1] in Julia, to see if I could make it faster than the existing python implementation [2], which is based on a grid search that looks for the optimal parameters. </p> <p>I obtain the desired results but despite my best efforts, my grid search version of it takes about the same time to compute as the python one, which is still way too long for real applications. I also tried using the Optimize package which only makes things worse (2 or 3 times slower).</p> <p>Here is the grid search that I implemented :</p> <pre><code>using Random using LinearAlgebra """ computes the square distance netween elements of X and C. returns squared_dist. squared_dist[ij] = ||X[:, i] - C[:, j]||^2 """ function squared_distance(X::Array{Float64,1},C::Array{Float64,1}) sqd = zeros(length(X),length(C)) for i in 1:length(X) for j in 1:length(C) sqd[i,j] = X[i]^2 + C[j]^2 - 2*X[i]*C[j] end end return sqd end # """ # Multidimensional equivalent of squared_distance. # """ # function squared_distance(X::Array{Float64,2},C::Array{Float64,2}) # sqd = zeros(size(X)[2],size(C)[2]) # for i in 1:size(X)[2] # for j in 1:size(C)[2] # sqd[i,j] = sum(X.^2)[i,:] + sum(C.^2)[i,:] -2*sum(X[i,:].*C[j,:]) # end # end # return sqd # end function lsdd(x::Array{Float64,1},y::Array{Float64,1}; folds = 5, sigma_list = nothing , lambda_list = nothing) lx,ly = length(x), length(y) b = min(lx+ly,300) C = shuffle(vcat(x,y))[1:b] CC_dist2 = squared_distance(C,C) xC_dist2, yC_dist2 = squared_distance(x,C), squared_distance(y,C) Tx,Ty = length(x) - div(lx,folds), length(y) - div(ly,folds) #Define the training and testing data sets cv_split1, cv_split2 = floor.(collect(1:lx)*folds/lx), floor.(collect(1:ly)*folds/ly) cv_index1, cv_index2 = shuffle(cv_split1), shuffle(cv_split2) tr_idx1,tr_idx2 = [findall(x-&gt;x!=i,cv_index1) for i in 1:folds], [findall(x-&gt;x!=i,cv_index2) for i in 1:folds] te_idx1,te_idx2 = [findall(x-&gt;x==i,cv_index1) for i in 1:folds], [findall(x-&gt;x==i,cv_index2) for i in 1:folds] xTr_dist, yTr_dist = [xC_dist2[i,:] for i in tr_idx1], [yC_dist2[i,:] for i in tr_idx2] xTe_dist, yTe_dist = [xC_dist2[i,:] for i in te_idx1], [yC_dist2[i,:] for i in te_idx2] if sigma_list == nothing sigma_list = [0.25, 0.5, 0.75, 1, 1.2, 1.5, 2, 2.5, 2.2, 3, 5] end if lambda_list == nothing lambda_list = [1.00000000e-03, 3.16227766e-03, 1.00000000e-02, 3.16227766e-02, 1.00000000e-01, 3.16227766e-01, 1.00000000e+00, 3.16227766e+00, 1.00000000e+01] end #memory prealocation score_cv = zeros(length(sigma_list),length(lambda_list)) H = zeros(b,b) hx_tr, hy_tr = [zeros(b,1) for i in 1:folds], [zeros(b,1) for i in 1:folds] hx_te, hy_te = [zeros(1,b) for i in 1:folds], [zeros(1,b) for i in 1:folds] #h_tr,h_te = zeros(b,1), zeros(1,b) theta = zeros(b) for (sigma_idx,sigma) in enumerate(sigma_list) #the expression of H is different for higher dimension #H = sqrt((sigma^2)*pi)*exp.(-CC_dist2/(4*sigma^2)) set_H(H,CC_dist2,sigma,b) #check if the sum is performed along the right dimension set_htr(hx_tr,xTr_dist,sigma,Tx), set_htr(hy_tr,yTr_dist,sigma,Ty) set_hte(hx_te,xTe_dist,sigma,lx-Tx), set_hte(hy_te,yTe_dist,sigma,ly-Ty) for i in 1:folds h_tr = hx_tr[i] - hy_tr[i] h_te = hx_te[i] - hy_te[i] #set_h(h_tr,hx_tr[i],hy_tr[i],b) #set_h(h_te,hx_te[i],hy_te[i],b) for (lambda_idx,lambda) in enumerate(lambda_list) set_theta(theta,H,lambda,h_tr,b) score_cv[sigma_idx,lambda_idx] += dot(theta,H*theta) - 2*dot(theta,h_te) end end end #retrieve the value of the optimal parameters sigma_chosen = sigma_list[findmin(score_cv)[2][2]] lambda_chosen = lambda_list[findmin(score_cv)[2][2]] #calculating the new "optimal" solution H = sqrt((sigma_chosen^2)*pi)*exp.(-CC_dist2/(4*sigma_chosen^2)) H_lambda = H + lambda_chosen*Matrix{Float64}(I, b, b) h = (1/lx)*sum(exp.(-xC_dist2/(2*sigma_chosen^2)),dims = 1) - (1/ly)*sum(exp.(-yC_dist2/(2*sigma_chosen^2)),dims = 1) theta_final = H_lambda\transpose(h) f = transpose(theta_final).*sum(exp.(-vcat(xC_dist2,yC_dist2)/(2*sigma_chosen^2)),dims = 1) L2 = 2*dot(theta_final,h) - dot(theta_final,H*theta_final) return L2 end function set_H(H::Array{Float64,2},dist::Array{Float64,2},sigma::Float64,b::Int64) for i in 1:b for j in 1:b H[i,j] = sqrt((sigma^2)*pi)*exp(-dist[i,j]/(4*sigma^2)) end end end function set_theta(theta::Array{Float64,1},H::Array{Float64,2},lambda::Float64,h::Array{Float64,2},b::Int64) Hl = (H + lambda*Matrix{Float64}(I, b, b)) LAPACK.posv!('L', Hl, h) theta = h end function set_htr(h::Array{Array{Float64,2},1},dists::Array{Array{Float64,2},1},sigma::Float64,T::Int64) for (CVidx,dist) in enumerate(dists) for (idx,value) in enumerate((1/T)*sum(exp.(-dist/(2*sigma^2)),dims = 1)) #h[CVidx][idx] = value h[CVidx][idx] = value end end end function set_hte(h::Array{Array{Float64,2},1},dists::Array{Array{Float64,2},1},sigma::Float64,T::Int64) for (CVidx,dist) in enumerate(dists) for (idx,value) in enumerate((1/T)*sum(exp.(-dist/(2*sigma^2)),dims = 1)) h[CVidx][idx] = value end end end function set_h(h,h1,h2,b) for i in 1:b h[i] = h1[i] - h2[i] end end function getdiff(ts; window = 150) diff = [] for i in 1:(length(ts)-2*window) pd1 = [ts[i+k] for k in 1:window] pd2 = [ts[i+window+k] for k in 1:window] push!(diff,lsdd(pd1,pd2)[1]) end return diff end a,b = rand(500),1.5*rand(500) @time print(lsdd(a,b)) </code></pre> <p>The <code>set_H</code>, <code>set_h</code> and <code>set_theta</code> functions are there because I read somewhere that modifying prealocated memory in place with a function was faster, but it did not make a great difference.<br> To test it, I use two random distributions as input data : </p> <pre><code>x,y = rand(500),1.5*rand(500) lsdd(x,y) #returns a value around 0.3 </code></pre> <p>Now here is the version of the code where I try to use Optimizer :</p> <pre><code>function Theta(sigma::Float64,lambda::Float64,x::Array{Float64,1},y::Array{Float64,1},folds::Int8) lx,ly = length(x), length(y) b = min(lx+ly,300) C = shuffle(vcat(x,y))[1:b] CC_dist2 = squared_distance(C,C) xC_dist2, yC_dist2 = squared_distance(x,C), squared_distance(y,C) #the subsets are not be mutually exclusive ! Tx,Ty = length(x) - div(lx,folds), length(y) - div(ly,folds) shuffled_x, shuffled_y = [shuffle(1:lx) for i in 1:folds], [shuffle(1:ly) for i in 1:folds] cv_index1, cv_index2 = floor.(collect(1:lx)*folds/lx)[shuffle(1:lx)], floor.(collect(1:ly)*folds/ly)[shuffle(1:ly)] tr_idx1,tr_idx2 = [i[1:Tx] for i in shuffled_x], [i[1:Ty] for i in shuffled_y] te_idx1,te_idx2 = [i[Tx:end] for i in shuffled_x], [i[Ty:end] for i in shuffled_y] xTr_dist, yTr_dist = [xC_dist2[i,:] for i in tr_idx1], [yC_dist2[i,:] for i in tr_idx2] xTe_dist, yTe_dist = [xC_dist2[i,:] for i in te_idx1], [yC_dist2[i,:] for i in te_idx2] score_cv = 0 Id = Matrix{Float64}(I, b, b) H = sqrt((sigma^2)*pi)*exp.(-CC_dist2/(4*sigma^2)) hx_tr, hy_tr = [transpose((1/Tx)*sum(exp.(-dist/(2*sigma^2)),dims = 1)) for dist in xTr_dist], [transpose((1/Ty)*sum(exp.(-dist/(2*sigma^2)),dims = 1)) for dist in yTr_dist] hx_te, hy_te = [(lx-Tx)*sum(exp.(-dist/(2*sigma^2)),dims = 1) for dist in xTe_dist], [(ly-Ty)*sum(exp.(-dist/(2*sigma^2)),dims = 1) for dist in yTe_dist] for i in 1:folds h_tr, h_te = hx_tr[i] - hy_tr[i], hx_te[i] - hy_te[i] #theta = (H + lambda * Id)\h_tr theta = copy(h_tr) Hl = (H + lambda*Matrix{Float64}(I, b, b)) LAPACK.posv!('L', Hl, theta) score_cv += dot(theta,H*theta) - 2*dot(theta,h_te) end return score_cv,(CC_dist2,xC_dist2,yC_dist2) end function cost(params::Array{Float64,1},x::Array{Float64,1},y::Array{Float64,1},folds::Int8) s,l = params[1],params[2] return Theta(s,l,x,y,folds)[1] end """ Performs the optinization """ function lsdd3(x::Array{Float64,1},y::Array{Float64,1}; folds = 4) start = [1,0.1] b = min(length(x)+length(y),300) lx,ly = length(x),length(y) #result = optimize(params -&gt; cost(params,x,y,folds),fill(0.0,2),fill(50.0,2),start, Fminbox(LBFGS(linesearch=LineSearches.BackTracking())); autodiff = :forward) result = optimize(params -&gt; cost(params,x,y,folds),start, BFGS(),Optim.Options(f_calls_limit = 5, iterations = 5)) #bboptimize(rosenbrock2d; SearchRange = [(-5.0, 5.0), (-2.0, 2.0)]) #result = optimize(cost,[0,0],[Inf,Inf],start, Fminbox(AcceleratedGradientDescent())) sigma_chosen,lambda_chosen = Optim.minimizer(result) CC_dist2, xC_dist2, yC_dist2 = Theta(sigma_chosen,lambda_chosen,x,y,folds)[2] H = sqrt((sigma_chosen^2)*pi)*exp.(-CC_dist2/(4*sigma_chosen^2)) h = (1/lx)*sum(exp.(-xC_dist2/(2*sigma_chosen^2)),dims = 1) - (1/ly)*sum(exp.(-yC_dist2/(2*sigma_chosen^2)),dims = 1) theta_final = (H + lambda_chosen*Matrix{Float64}(I, b, b))\transpose(h) f = transpose(theta_final).*sum(exp.(-vcat(xC_dist2,yC_dist2)/(2*sigma_chosen^2)),dims = 1) L2 = 2*dot(theta_final,h) - dot(theta_final,H*theta_final) return L2 end </code></pre> <p>No matter, which kind of option I use in the optimizer, I always end up with something too slow. Maybe the grid search is the best option, but I don't know how to make it faster... Does anyone have an idea how I could proceed further ?</p> <p><strong>Remark</strong> : I already posted this question on stackexchange, where I was pointed out that it might make more sense to post it here.</p> <p>[1] : <a href="http://www.mcduplessis.com/wp-content/uploads/2016/05/Journal-IEICE-2014-CLSDD-1.pdf" rel="nofollow noreferrer">http://www.mcduplessis.com/wp-content/uploads/2016/05/Journal-IEICE-2014-CLSDD-1.pdf</a><br> [2] : <a href="http://www.ms.k.u-tokyo.ac.jp/software.html" rel="nofollow noreferrer">http://www.ms.k.u-tokyo.ac.jp/software.html</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:27:28.060", "Id": "428734", "Score": "0", "body": "This code doesn't run. The types on the `set_h*` functions are all incorrectly typed. Can you fix this please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T16:04:27.293", "Id": "428740", "Score": "0", "body": "@OscarSmith It runs on my computer ... Which version of julia do you have ? Or maybe this is due to the fact that I forgot to include the packages to import in my post. I corrected that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T16:09:30.787", "Id": "428741", "Score": "0", "body": "I'm on Julia 1.1.1 and get `ERROR: LoadError: MethodError: no method matching set_H(::Array{Float64,2}, ::Array{Float64,2}, ::Float64, ::Int64)\nClosest candidates are:\n set_H(::Array{Float64,2}, ::Array{Float64,2}, ::Float64, !Matched::Int16)`\n``" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:38:28.707", "Id": "428866", "Score": "0", "body": "@OscarSmith Ok that's weird ... I wasn't excpecting to see Int64s, anyways I change the int16 to int64, does it work now ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T17:37:24.283", "Id": "428916", "Score": "0", "body": "It still errors. Please make sure your code actually runs correctly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T12:19:39.413", "Id": "429020", "Score": "0", "body": "@OscarSmith What is your error ? It runs perfectly well on my computer (I just copied and pasted the provided code in a new file to be sure). ```a,b = rand(300), 2*rand(300)``` and ```lsdd(a,b)``` returns something around 0.5." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T15:12:56.450", "Id": "429042", "Score": "0", "body": "`ERROR: LoadError: MethodError: no method matching set_htr(::Array{Array{Float64,2},1}, ::Array{Array{Float64,2},1}, ::Float64, ::Int64)\nClosest candidates are:\n set_htr(!Matched::Array{Float64,1}, !Matched::Array{Float64,2}, ::Float64, ::Int64) at /home/oscardssmith/Documents/Code/2dIsing.jl:86`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T08:05:00.933", "Id": "429664", "Score": "0", "body": "Hmm .. I don't really know what was going on, but I modified a few type indications in the functions an updated my post. It passes the tests on travis so it should definitely work on your machine this time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-11T15:38:27.150", "Id": "429729", "Score": "0", "body": "Works now. Thanks" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T14:32:03.563", "Id": "221655", "Score": "6", "Tags": [ "performance", "julia" ], "Title": "How to speed up simple linear algebra optimization probelm in Julia?" }
221655
<p>This was a small project I did the other day because I wanted to explore a solution to hot-reload some files in another project. </p> <p>My requirements were:</p> <ul> <li>Act in it's own thread</li> <li>Be able to watch specific file extensions</li> <li>Work on Windows</li> </ul> <p>So since I knew my application would only run on windows I decided to use WinApi.</p> <p>I am mostly concerned about modern C++ stuff and particularly in handling the thread but if there are any other glaring issues obviously any help is appreciated. I know the FileAction class enum might be a little strange but it just makes the switch statement prettier, not sure if it's frowned upon. </p> <p>Last note before code is the reason I deleted the copy constructors is because std::thread is not copyable (afaik) but it can be moved so it didn't make sense to allow a copy of the DirectoryWatcherWin class if I couldn't copy all of it's members - hope that's correct.. </p> <p><strong>DirectoryWatcherWin.h</strong></p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;atomic&gt; #include &lt;thread&gt; #include &lt;string&gt; #include &lt;vector&gt; namespace mikand { enum class FileAction { CREATED = FILE_ACTION_ADDED, REMOVED = FILE_ACTION_REMOVED, MODIFIED = FILE_ACTION_MODIFIED }; class DirectoryWatcherWin { public: using DWWCallback = std::function&lt;void(std::string, FileAction)&gt;; private: HANDLE m_DirectoryHandle; std::atomic&lt;bool&gt; m_Running; std::thread m_Thread; std::string m_DirectoryToWatch; std::vector&lt;std::string&gt; m_Extensions; DWWCallback m_Callback; public: DirectoryWatcherWin(const std::string&amp; directoryToWatch, DWWCallback callback); DirectoryWatcherWin(const std::string&amp; directoryToWatch, const std::vector&lt;std::string&gt;&amp; extensionsToWatch, DWWCallback callback); DirectoryWatcherWin(const DirectoryWatcherWin&amp; other) = delete; DirectoryWatcherWin&amp; operator=(const DirectoryWatcherWin&amp; other) = delete; DirectoryWatcherWin(DirectoryWatcherWin&amp;&amp; other) = default; DirectoryWatcherWin&amp; operator=(DirectoryWatcherWin&amp;&amp; other) = default; ~DirectoryWatcherWin(); void start(); void stop(); private: void watch(); }; } </code></pre> <p><strong>DirectoryWatcherWin.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include "pch.h" #include "DirectoryWatcherWin.h" #include "StringUtil.h" namespace mikand { DirectoryWatcherWin::DirectoryWatcherWin(const std::string&amp; directoryToWatch, DWWCallback callback) : m_DirectoryToWatch(directoryToWatch), m_Callback(callback) { } DirectoryWatcherWin::DirectoryWatcherWin(const std::string&amp; directoryToWatch, const std::vector&lt;std::string&gt;&amp; extensionsToWatch, DWWCallback callback) : m_DirectoryToWatch(directoryToWatch), m_Extensions(extensionsToWatch), m_Callback(callback) { } DirectoryWatcherWin::~DirectoryWatcherWin() { if (m_Thread.joinable()) { stop(); } } void DirectoryWatcherWin::start() { std::wstring dirWStr = std::wstring(m_DirectoryToWatch.begin(), m_DirectoryToWatch.end()); m_DirectoryHandle = CreateFile(dirWStr.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); m_Running = true; m_Thread = std::thread(&amp;DirectoryWatcherWin::watch, this); } void DirectoryWatcherWin::stop() { m_Running = false; CancelIoEx(m_DirectoryHandle, 0); m_Thread.join(); CloseHandle(m_DirectoryHandle); } void DirectoryWatcherWin::watch() { while (m_Running.load()) { std::vector&lt;BYTE&gt; byteBuffer(4096); DWORD bytesReturned; OVERLAPPED overlapped = { 0 }; overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); ReadDirectoryChangesW(m_DirectoryHandle, &amp;byteBuffer[0], byteBuffer.size(), TRUE, FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_FILE_NAME, &amp;bytesReturned, &amp;overlapped, NULL); GetOverlappedResult(m_DirectoryHandle, &amp;overlapped, &amp;bytesReturned, TRUE); FILE_NOTIFY_INFORMATION *fni = (FILE_NOTIFY_INFORMATION*)(&amp;byteBuffer[0]); do { std::string filenameStr = StringUtil::wcharToString(fni-&gt;FileName, fni-&gt;FileNameLength); if (m_Extensions.size() &gt; 0) { for (auto&amp; extension : m_Extensions) { if (StringUtil::endsWith(filenameStr, extension)) { m_Callback(filenameStr, FileAction(fni-&gt;Action)); break; } } } else { m_Callback(filenameStr, FileAction(fni-&gt;Action)); } fni = (FILE_NOTIFY_INFORMATION*)((BYTE*)(fni) + fni-&gt;NextEntryOffset); } while (fni-&gt;NextEntryOffset != 0); } } } </code></pre> <p><strong>StringUtil.h</strong></p> <pre class="lang-cpp prettyprint-override"><code>namespace mikand { class StringUtil { public: inline static bool endsWith(const std::string&amp; str, const std::string&amp; suffix) { return (str.length() &gt;= suffix.length()) &amp;&amp; (str.compare(str.length() - suffix.length(), suffix.length(), suffix) == 0); } inline static bool startsWith(const std::string&amp; str, const std::string&amp; prefix) { return (str.length() &gt;= prefix.length()) &amp;&amp; (str.compare(0, prefix.size(), prefix) == 0); } inline static std::string wcharToString(wchar_t* in, unsigned long length) { if (length &lt; 1) { return std::string(); } std::wstring_convert&lt;std::codecvt_utf8&lt;wchar_t&gt;, wchar_t&gt; converter; std::wstring tempWstr(in, length); std::string s = converter.to_bytes(tempWstr); int i = s.length() - 1; while (s.at(i) == '\0') { s.pop_back(); i--; } return s; } // UNUSED METHODS OMITTED }; } </code></pre> <p><strong>pch.h</strong></p> <pre class="lang-cpp prettyprint-override"><code>#ifndef PCH_H #define PCH_H #include &lt;windows.h&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;array&gt; #include &lt;locale&gt; #include &lt;codecvt&gt; #include &lt;iostream&gt; #endif </code></pre> <p><strong>main.cpp</strong></p> <pre class="lang-cpp prettyprint-override"><code>#include "pch.h" #include "DirectoryWatcherWin.h" using namespace mikand; void printFilename(std::string filename, FileAction action) { switch (action) { case FileAction::CREATED: std::cout &lt;&lt; "Created: " &lt;&lt; filename &lt;&lt; std::endl; break; case FileAction::REMOVED: std::cout &lt;&lt; "Removed: " &lt;&lt; filename &lt;&lt; std::endl; break; case FileAction::MODIFIED: std::cout &lt;&lt; "Modified: " &lt;&lt; filename &lt;&lt; std::endl; break; default: break; } } int main() { DirectoryWatcherWin::DWWCallback callback = printFilename; DirectoryWatcherWin watcher("C:\\temp", std::vector&lt;std::string&gt;{".txt"}, callback); watcher.start(); std::string waitForPress; std::getline(std::cin, waitForPress); watcher.stop(); system("pause"); } </code></pre>
[]
[ { "body": "<p><strong>Style</strong></p>\n\n<ul>\n<li><p>Subjective but don't indent on namespaces.</p></li>\n<li><p>I would group the ctors and operators together instead of grouping them by their status (default/delete).</p></li>\n<li><p>Your ctor is a bit hard to read. Consider formatting it differently. E.g.:</p>\n\n<pre><code>DirectoryWatcherWin::DirectoryWatcherWin(\n const std::string&amp; directoryToWatch, \n const std::vector&lt;std::string&gt;&amp; extensionsToWatch, \n DWWCallback callback)\n : m_DirectoryToWatch(directoryToWatch)\n , m_Extensions(extensionsToWatch)\n , m_Callback(callback)\n{} \n</code></pre>\n\n<p>This way the parameters are visually separated from the member init list and you don't break any line length recommendations either. </p></li>\n</ul>\n\n<hr>\n\n<p><strong>Code</strong> </p>\n\n<ul>\n<li><p>We need to talk about your interface.<br>\nGenerally you should start with <code>public</code> and <code>private</code> should come last. Also do not use those keywords more than once per class definition.<br>\nI would probably either ditch the <code>DWWCallback</code> declaration, or move it into the namespace, seeing as there is probably no use-case where people use your namespace but not the <code>DWWCallback</code>.</p></li>\n<li><p><a href=\"https://softwareengineering.stackexchange.com/questions/59880/avoid-postfix-increment-operator\">Prefer prefix over postfix</a>.</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">Prefer using <code>\\n</code> over <code>std::endl</code></a>.</p></li>\n<li><p>Don't <code>using namespace</code>. Prefixing your code with the namespace is really not too much to ask.</p></li>\n<li><blockquote>\n<pre><code>for (auto&amp; extension : m_Extensions)\n</code></pre>\n</blockquote>\n\n<p>Consider using <code>const</code> in loops like this if you don't intend to modify the loop variable in the body.</p></li>\n<li><p>If you have strings that you don't modify consider using <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\">string_view</a> as it <a href=\"https://stackoverflow.com/questions/40127965/how-exactly-stdstring-view-is-faster-than-const-stdstring\">can be faster</a>.</p></li>\n<li><p>When you want to initialize a struct and all its members consider using <code>foostruct = {};</code>\nSee <a href=\"https://stackoverflow.com/questions/1069621/are-members-of-a-c-struct-initialized-to-0-by-default\">this</a> for more info.</p></li>\n<li><blockquote>\n<pre><code>std::wstring dirWStr = std::wstring(m_DirectoryToWatch.begin(), m_DirectoryToWatch.end());\n</code></pre>\n</blockquote>\n\n<p>I don't quite follow the idea behind this. Can you not pass this directly as something else like maybe <code>mystring_view.data()</code>? If it has to be a <code>wstr</code> why not keep it as such in the class as well?</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T20:33:25.617", "Id": "429106", "Score": "3", "body": "The \"pch.h\" header is a Microsoft thing, replacing \"stdafx.h\". Not shown here, but included in the project, is a \"pch.cpp\" file whose sole purpose in life is to generate the precompiled header that will be read in by all the other source files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T06:19:22.777", "Id": "429146", "Score": "0", "body": "@1201ProgramAlarm I see, thanks for the clarification." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-08T19:14:06.477", "Id": "429395", "Score": "0", "body": "Thanks for the answer! First point, I've just always structured it as public variables, private variables, then public functions, private functions but I see your point. The \"using namespace\" was just in the sample to save some typing. More interesting I think though is the last point: the reason is it has to be a wstring for WinAPI to be happy but to save other people from using wstring I provided an std::string interface instead. The conversion has to happen somewhere and I thought doing it on the \"inside\" would be a bit neater." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T20:07:51.467", "Id": "221806", "ParentId": "221656", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T14:35:14.873", "Id": "221656", "Score": "7", "Tags": [ "c++", "multithreading", "windows" ], "Title": "C++ Windows Directory Watcher" }
221656
<p>I wanted to test my performance optimizing skills, and so wanted to find how fast I could get the first <span class="math-container">\$n\$</span> prime numbers. I limited myself to only the standard library, as I'm sure <code>numpy</code> or another library written in C has a prime generator <em>way</em> faster than Python ever will be - and offloading to a library doesn't really improve my ability to improve performance.</p> <p>I've implemented both the Sieve of Eratosthenes and the Sieve of Sundaram. The SoE was based off my answer <a href="https://codereview.stackexchange.com/a/213422">here</a>, and the SoS was based off <a href="https://en.wikipedia.org/wiki/Sieve_of_Sundaram#Algorithm" rel="noreferrer">Wikipedias definition</a>. These are available at the end of the answer.</p> <p>I improved performance by:</p> <ul> <li><p>SoE: Vectorizing the creation of primes.</p> <pre><code>primes[base*2:limit:base] = [False]*(ceil(limit / base) - 2) </code></pre></li> <li><p>SoE: Change the start of the slice from <span class="math-container">\$2b\$</span> to <span class="math-container">\$b^2\$</span>. <sup><a href="https://codereview.stackexchange.com/q/213418#comment412884_213422">[1]</a></sup></p> <pre><code>primes[base*base:limit:base] = [False]*((((limit - base*base) - 1) // base) + 1) </code></pre></li> <li><p>SoE: Simplify the calculations - addition seems to be faster than multiplication.</p> <pre><code>primes[base * base::base] = [False] * ((limit - 1) // base - base + 1) </code></pre></li> <li><p>SoE: Use <code>itertools.compress</code>, rather than a comprehension.</p></li> <li><p>SoS: Vectorize the inner loop.</p> <pre><code>start = 1 + 3*j step = 1 + 3*j primes[start::step] = [False] * ceil((n - start) / step) </code></pre></li> <li><p>SoS: Vectorize the creation of values that only have one value in the sequence. </p> <p>When <span class="math-container">\$\frac{n - \text{start}}{\text{stop}} = \frac{n - (1 + 3j)}{1 + 2j} \le 1\$</span> is equivalent to <span class="math-container">\$n \le 2 + 5j\$</span> we know we can stop at <span class="math-container">\$j = \frac{n - 2}{5}\$</span>.</p> <pre><code>multi_stop = (n - 2) // 5 for j in range(1, multi_stop): start = 1 + 3*j step = 1 + 2*j primes[start::step] = [False] * ceil((n - start) / step) if multi_stop &gt;= 1: single_start = multi_stop * 3 + 1 primes[single_start::3] = [False] * ceil((n - single_start) / 3) </code></pre></li> <li>SoS: It doesn't seem like you need the <code>if</code> created above, and so you can just save wasted cycles.</li> </ul> <p>I tried defining <code>false = [False]*limit</code> and slice it, but found it to be slower than creating new lists in the loop.</p> <p>This got the following prime sieves:</p> <pre><code>from math import ceil from itertools import compress def sieve_eratosthenes(limit): if limit &lt;= 1: return [] primes = [True] * limit for base in range(2, int(limit**0.5 + 1)): if primes[base]: primes[base * base::base] = [False] * ((limit - 1) // base - base + 1) primes[0] = primes[1] = False return list(compress(range(limit), primes)) def sieve_sundaram(limit): if limit &lt;= 1: return [] n = (limit - 1) // 2 primes = [True] * n for j in range(1, (n - 2) // 5): start = 1 + 3*j step = 1 + 2*j primes[start::step] = [False] * ceil((n - start) / step) return [2] + [2*i + 1 for i, p in enumerate(primes) if p][1:] </code></pre> <p>Both are faster than the both the original functions.</p> <p><a href="https://i.stack.imgur.com/9ZBY2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9ZBY2.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/NKjo9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NKjo9.png" alt="enter image description here"></a></p> <p>Code to generate graphs:</p> <pre><code>from math import ceil from itertools import compress import numpy as np import matplotlib.pyplot as plt from graphtimer import Plotter, MultiTimer def sieve_eratosthenes_orig(limit): if limit &lt;= 1: return [] primes = [True] * limit for base in range(2, int(limit**0.5 + 1)): if primes[base]: for composite in range(base * 2, limit, base): primes[composite] = False return [num for num, is_prime in enumerate(primes) if is_prime][2:] def sieve_eratosthenes(limit): if limit &lt;= 1: return [] primes = [True] * limit for base in range(2, int(limit**0.5 + 1)): if primes[base]: primes[base * base::base] = [False] * ((limit - 1) // base - base + 1) primes[0] = primes[1] = False return list(compress(range(limit), primes)) def sieve_sundaram_orig(limit): if limit &lt;= 1: return [] n = (limit - 1) // 2 primes = [True] * n for j in range(1, n): for i in range(1, j + 1): value = i + j + 2*i*j if value &lt; n: primes[value] = False return [2] + [2*i + 1 for i, p in enumerate(primes) if p][1:] def sieve_sundaram(limit): if limit &lt;= 1: return [] n = (limit - 1) // 2 primes = [True] * n for j in range(1, (n - 2) // 5): start = 1 + 3*j step = 1 + 2*j primes[start::step] = [False] * ceil((n - start) / step) return [2] + [2*i + 1 for i, p in enumerate(primes) if p][1:] def sieve_test(limit): if limit &lt;= 1: return [] n = (limit - 1) // 2 primes = [True] * n multi_stop = (n - 2) // 5 for j in range(1, multi_stop): start = 1 + 3*j step = 1 + 2*j primes[start::step] = [False] * ceil((n - start) / step) return [2] + [2*i + 1 for i, p in enumerate(primes) if p][1:] def test(): for exp in range(6): limit = 10 ** exp assert sieve_test(limit) == sieve_eratosthenes(limit) def main(): fig, axs = plt.subplots() axs.set_yscale('log') axs.set_xscale('log') ( Plotter(MultiTimer([ sieve_eratosthenes_orig, sieve_eratosthenes, sieve_sundaram, sieve_sundaram_orig, # sieve_test, ])) .repeat(5, 5, np.logspace(0.35, 2), args_conv=int) .min() .plot(axs, x_label='limit') ) fig.show() if __name__ == '__main__': test() main() </code></pre> <p>To use the above code snippet you need to install numpy, matplotlib and graphtimer. All should be available via pypi.</p> <p>Can they be made faster, or is a different sieve faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:24:03.043", "Id": "428732", "Score": "0", "body": "Did you try the [Sieve of Atkin](https://en.wikipedia.org/wiki/Sieve_of_Atkin)? Something tells me it's faster than the Sieve of Erathosthenes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:26:47.640", "Id": "428733", "Score": "0", "body": "@Justin No, I didn't. I'm not too sure about it being faster than SoE in _Python_. But I'd be happy to be proven wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:30:00.347", "Id": "428735", "Score": "0", "body": "Here, I might have just found something - https://programmingpraxis.com/2010/02/19/sieve-of-atkin-improved/. Does this help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:39:32.377", "Id": "428737", "Score": "0", "body": "@Justin Since it was written for Python 2 it may be unfair for it to be performance tested in Python 3. However with `xrange = range` and ensuring no IndexErrors I get the following [graph](https://i.stack.imgur.com/C2ckb.png). Which makes it faster than SoS at 1000 and always slower than SoE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T14:01:39.933", "Id": "430387", "Score": "0", "body": "Does this help - https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n?" } ]
[ { "body": "<blockquote>\n<pre><code>def sieve_eratosthenes(limit):\n if limit &lt;= 1:\n return []\n\n primes = [True] * limit\n for base in range(2, int(limit**0.5 + 1)):\n if primes[base]:\n primes[base * base::base] = [False] * ((limit - 1) // base - base + 1)\n\n primes[0] = primes[1] = False\n return list(compress(range(limit), primes))\n</code></pre>\n</blockquote>\n\n<p>No attempt at all to use a wheel? I get roughly a 25% speedup just by special-casing the prime 2 with:</p>\n\n<pre><code>def sieve_eratosthenes_wheel(limit):\n if limit &lt;= 1:\n return []\n\n primes = [True] * limit\n if limit &gt; 4:\n primes[4::2] = [False] * ((limit - 1) // 2 - 2 + 1)\n\n for base in range(3, int(limit**0.5 + 1), 2):\n if primes[base]:\n # We require off + (len-1)*step &lt; limit &lt;= off + len*step\n # So len = ceil((limit - off) / step)\n primes[base*base::2*base] = [False] * ((limit - base*base + 2*base - 1) // (2*base))\n\n primes[0] = primes[1] = False\n return list(compress(range(limit), primes))\n</code></pre>\n\n<p>Using primes 2 and 3 it's possible to do two range updates with step sizes of <code>6*base</code>, but it gets more complicated to calculate the initial offsets, which depend on <code>base % 6</code>:</p>\n\n<pre><code>def sieve_eratosthenes_wheel3(limit):\n if limit &lt;= 1:\n return []\n\n primes = [True] * limit\n def mark_composite(off, step):\n # We require off + (len-1)*step &lt; limit &lt;= off + len*step\n # So len = ceil((limit - off) / step)\n primes[off::step] = [False] * ((limit - off + step - 1) // step)\n\n mark_composite(4, 2)\n mark_composite(9, 6)\n base = 5\n max_base = int(limit**0.5)\n while base &lt;= max_base:\n # base == 5 (mod 6)\n if primes[base]:\n mark_composite(base*base, 6*base)\n mark_composite(base*(base+2), 6*base)\n base += 2\n # base == 1 (mod 6)\n if primes[base]:\n mark_composite(base*base, 6*base)\n mark_composite(base*(base+4), 6*base)\n base += 4\n\n primes[0] = primes[1] = False\n return list(compress(range(limit), primes))\n</code></pre>\n\n<p>For <code>limit</code> 50 million, taking <code>sieve_eratosthenes</code> as the baseline of 100 time units, I measure <code>sieve_eratosthenes_wheel</code> at about 73 time units and <code>sieve_eratosthenes_wheel3</code> at about 63 time units.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-28T16:43:34.590", "Id": "441610", "Score": "0", "body": "Could you explain what \"a wheel\" is? I know car wheels, but this meaning is definitely new to me :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-28T17:42:54.300", "Id": "441624", "Score": "0", "body": "@Peilonrayz https://en.wikipedia.org/wiki/Wheel_factorization" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-28T16:38:32.717", "Id": "227023", "ParentId": "221659", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:02:30.573", "Id": "221659", "Score": "6", "Tags": [ "python", "performance", "python-3.x", "reinventing-the-wheel", "primes" ], "Title": "Fast prime generator" }
221659
<p>This is a task taken from <a href="https://leetcode.com/problems/merge-intervals/" rel="nofollow noreferrer">Leetcode</a> -</p> <blockquote> <p><em>Given a collection of intervals, merge all overlapping intervals.</em></p> <p><strong>Example 1:</strong></p> <pre><code>Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] /** Explanation: Since intervals `[1,3]` and `[2,6]` overlap, merge them into `[1,6]`. */ </code></pre> <p><strong>Example 2:</strong></p> <pre><code>Input: [[1,4],[4,5]] Output: [[1,5]] /** Explanation: Intervals `[1,4]` and `[4,5]` are considered overlapping. */ </code></pre> </blockquote> <p><strong>My imperative solution</strong> -</p> <pre><code> /** * @param {number[][]} intervals * @return {number[][]} */ var merge = function(intervals) { const sortedIntervals = intervals.sort((a,b) =&gt; a[0] - b[0]); const newIntervals = []; for (let i = 0; i &lt; intervals.length; i++) { if (!newIntervals.length || newIntervals[newIntervals.length - 1][1] &lt; sortedIntervals[i][0]) { newIntervals.push(sortedIntervals[i]); } else { newIntervals[newIntervals.length - 1][1] = Math.max(newIntervals[newIntervals.length - 1][1], sortedIntervals[i][1]); } } return newIntervals; }; </code></pre> <p><strong>My functional solution</strong> -</p> <pre><code>/** * @param {number[][]} intervals * @return {number[][]} */ function merge(intervals) { const mergeInterval = (ac, x) =&gt; (!ac.length || ac[ac.length - 1][1] &lt; x[0] ? ac.push(x) : ac[ac.length - 1][1] = Math.max(ac[ac.length - 1][1], x[1]), ac); return intervals .sort((a,b) =&gt; a[0] - b[0]) .reduce(mergeInterval, []); }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-01T18:07:53.350", "Id": "447669", "Score": "0", "body": "While sorting intervals on first value suggests itself, I'm wondering if discarding/merging intervals during sort make a notable difference, and in what direction. (Obviously, it doesn't change a thing if no intervals get merged.)" } ]
[ { "body": "<p>The code is mostly readable and clear:</p>\n\n<ul>\n<li>the variable names are descriptive (for the most part - <code>x</code> is a little unclear)</li>\n<li>there is good use of <code>const</code> and <code>let</code> instead of <code>var</code></li>\n</ul>\n\n<p>Some of the lines are a little lengthy - the longest line appears to be 117 characters long (excluding indentation):</p>\n\n<blockquote>\n<pre><code>newIntervals[newIntervals.length - 1][1] = Math.max(newIntervals[newIntervals.length - 1][1], sortedIntervals[i][1]);\n</code></pre>\n</blockquote>\n\n<p>I considered suggesting that a <code>for...of</code> loop be used to replace the <code>for</code> loop in the imperative solution after seeing the suggestion to use <code>arr.entries()</code> in <a href=\"https://codereview.stackexchange.com/a/229870/120114\">this answer</a> which would allow the use of a variable like <code>interval</code> instead of <code>sortedIntervals[i]</code>, though when comparing in FF and chrome with <a href=\"https://jsperf.com/sorting-intervals\" rel=\"nofollow noreferrer\">this jsPerf test</a> it seems that would be slower and thus less optimal, perhaps because each iteration would have an added function call.</p>\n\n<p>When <code>intervals.sort()</code> is called the array is sorted in-place so <code>intervals</code> could be used instead of <code>sortedIntervals</code>, however it does seem that using <code>sortedIntervals</code>. That would reduce the storage by <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-01T17:57:22.457", "Id": "229989", "ParentId": "221661", "Score": "4" } } ]
{ "AcceptedAnswerId": "229989", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T15:15:39.357", "Id": "221661", "Score": "8", "Tags": [ "javascript", "algorithm", "programming-challenge", "functional-programming", "ecmascript-6" ], "Title": "Merge Intervals in JavaScript" }
221661
<p>I'm working with product codes, so a user can only scan these type of product codes into a textarea element.</p> <p>I don't know if my code is written the best way possible, or has good performance.</p> <p>I'm using a whitelist solution for preventing bad entries.</p> <p>It saves into file all product codes after 3 seconds of last keyup.</p> <p>Is it good to use javascript and jQuery mixed?</p> <p>And is it the correct way to use a php query to fetch product code and product code ending?</p> <p>Why is &quot;use strict&quot; mode useless in my code?</p> <pre><code>&quot;use strict&quot;; toFile.focus(); var timeoutId; toFile.addEventListener(&quot;keyup&quot;, event =&gt; { clearTimeout(timeoutId); timeoutId = setTimeout(function() { const data = toFile.value.split(&quot;\n&quot;); const result = data.unique(); info.textContent = result.length !== data.length ? &quot;Duplicate removed&quot; : &quot;&quot;; toFile.value = result.join('\n'); }, 100); timeoutId = setTimeout(function() { onInput(document.getElementById('toFile')); }, 3000); }); if (!Array.prototype.unique) { Object.defineProperty(Array.prototype, &quot;unique&quot;, { configurable: false, // these 3 properties default to false so not needed enumerable: false, // But have added them just to show their availability. writable: false, value: function() { const existing = {}; return this.filter(a =&gt; existing[a] = !existing[a] ? true : false); } }); } else { throw new Error(&quot;Array.prototype.unique already defined.&quot;); } const regexNounFilters = [&lt;?php $data = $pdo-&gt;query(&quot;SELECT PRODUCT_CODE AS code, ENDING AS ec FROM test&quot;)-&gt;fetchAll(PDO::FETCH_OBJ); foreach ($data as $key) { $separator = ($key != end($data)) ? &quot;, &quot; : ''; $std = &quot;/^(&quot; . $key-&gt;code . &quot;)([a-zA-Z0-9]{&quot; . $key-&gt;ec . &quot;})$/&quot;; echo $std.$separator; } ?&gt;]; // example: const regexNounFilters = [/^(AAAB)([a-zA-Z0-9]{7})$/, /^(BBBBBC)([a-zA-Z0-9]{9})$/]; const extractNouns = string =&gt; string .split('\n') .filter(line =&gt; regexNounFilters.some(re =&gt; line.trim().toUpperCase().match(re) ) ); function onInput(target) { target.value = extractNouns(target.value).join('\n'); } function saveToFile() { console.log('Saving to the db'); toFile = $('#toFile').val().replace(/\n\r?/g, '&lt;br /&gt;'); $.ajax({ url: &quot;test2.php&quot;, type: &quot;POST&quot;, data: {toFile:toFile}, // serializes the form's elements. beforeSend: function(xhr) { // Let them know we are saving $('#status').html('Saving...'); }, success: function(toFile) { // You can get data returned from your ajax call here. ex. jqObj.find('.returned-data').html() // Now show them we saved and when we did var d = new Date(); $('#status').html('Saved! Last: ' + d.toLocaleTimeString()); }, }); } $('.form').submit(function(e) { saveToFile(); e.preventDefault(); }); </code></pre>
[]
[ { "body": "<h2>Responses to your questions</h2>\n<blockquote>\n<h3><em>Is it good to use javascript and jQuery mix?</em></h3>\n</blockquote>\n<p>If you are going to include the jQuery library, you might as well use it whenever possible. That may mean converting expressions like</p>\n<pre><code>document.getElementById('toFile')\n</code></pre>\n<p>to</p>\n<pre><code>$('#toFile')\n</code></pre>\n<p>and</p>\n<pre><code>target.value = extractNouns(target.value).join('\\n');\n</code></pre>\n<p>to</p>\n<pre><code>target.val(extractNouns(target.val()).join('\\n');\n</code></pre>\n<p>However, there are some people who believe jQuery isn't as relevant in today's web. For more information, check out <a href=\"http://youmightnotneedjquery.com/\" rel=\"nofollow noreferrer\">youmightnotneedjquery.com/</a>, which offers alternatives to many of the utilities jQuery offers, like the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\" rel=\"nofollow noreferrer\">Fetch API</a> for AJAX requests.</p>\n<blockquote>\n<h3><em>And is it correct way use php query to fetch product code and product code ending?</em></h3>\n</blockquote>\n<p>It is difficult to tell what &quot;<em>correct way</em>&quot; means. Do you mean is it acceptable to use PHP to generate Javascript code inline? If so, there are many factors, like who would be reading your code (including your future self), etc. Refer to answers to <a href=\"https://softwareengineering.stackexchange.com/q/126671/244085\"><em>Is it considered bad practice to have PHP in your JavaScript</em></a>.</p>\n<p>The product codes and endings timeoutId used to generate <code>regexNounFilters</code> could be output using <a href=\"https://php.net/implode\" rel=\"nofollow noreferrer\"><code>implode()</code></a> and the values stored in <code>$std</code> inside the <code>foreach</code> could be returned in a callback passed to <a href=\"https://php.net/array_map\" rel=\"nofollow noreferrer\"><code>array_map()</code></a> -</p>\n<p>So instead of:</p>\n<blockquote>\n<pre><code>foreach ($data as $key) {\n</code></pre>\n</blockquote>\n<pre><code> $separator = ($key != end($data)) ? &quot;, &quot; : '';\n $std = &quot;/^(&quot; . $key-&gt;code . &quot;)([a-zA-Z0-9]{&quot; . $key-&gt;ec . &quot;})$/&quot;;\n echo $std.$separator;\n}\n</code></pre>\n<p>Something like this could be used:</p>\n<pre><code>echo implode(&quot;, &quot;, array_map(function($key) {\n return &quot;/^(&quot; . $key-&gt;code . &quot;)([a-zA-Z0-9]{&quot; . $key-&gt;ec . &quot;})$/&quot;;\n}, $data);\n</code></pre>\n<p>##Other review feedback</p>\n<h3><code>var</code> keyword</h3>\n<p>Because EcmaScript-6 features like arrow functions are used, the ES-6 keywords for variable declarations - i.e. <code>let</code> and <code>const</code> can be used instead of <code>var</code>. Due to the peculiar implications of <code>var</code> (e.g. hoisting) some recommend avoiding the <code>var</code> keyword in modern JS.</p>\n<h3>Global variable reference</h3>\n<p>At the start of the JavaScript code I see this:</p>\n<blockquote>\n<pre><code>toFile.focus();\n</code></pre>\n</blockquote>\n<p>where is <code>toFile</code> defined? is it just utilizing that element using the <em>id</em> attribute? If so, this is basically a global variable reference, which can lead to trouble/confusion in the future as the code grows. Refer to answers to <a href=\"https://stackoverflow.com/q/3434278/1575353\"><em>Do DOM tree elements with ids become global variables?</em></a>. It would be wise to utilize <code>document.getElementById('toFile')</code>, as is done in the second callback in the <em>keyup</em> event handler.</p>\n<h3>Timer Assignment over-writing</h3>\n<p>In the <em>keyup</em> event listener on <code>toFile</code>, <code>timeoutId</code> is assigned to two separate timers,</p>\n<blockquote>\n<pre><code>timeoutId = setTimeout(function() {\n</code></pre>\n</blockquote>\n<pre><code> const data = toFile.value.split(&quot;\\n&quot;);\n const result = data.unique();\n info.textContent = result.length !== data.length ? &quot;Duplicate removed&quot; : &quot;&quot;;\n toFile.value = result.join('\\n');\n}, 100);\n</code></pre>\n<blockquote>\n<pre><code>timeoutId = setTimeout(function() {\n</code></pre>\n</blockquote>\n<pre><code> onInput(document.getElementById('toFile'));\n}, 3000);\n</code></pre>\n<p>Should the first assignment be preserved? Because the second one overwrites it, there is not any way the first can be cleared via <code>clearTimeout()</code>. If the first should be clearable, use a different name for those two timer ids.</p>\n<h3>DOM Queries</h3>\n<p>The DOM queries could be optimized by saving references in variables -\nfor example, <code>$('#status')</code> appears in the <code>beforeSend</code> and <code>success</code> handlers of the AJAX call.</p>\n<blockquote>\n<pre><code>beforeSend: function(xhr) {\n</code></pre>\n</blockquote>\n<pre><code> // Let them know we are saving\n $('#status').html('Saving...');\n},\n</code></pre>\n<p>A reference could be stored to the DOM element before the call to <code>$.ajax()</code> - e.g.</p>\n<pre><code>const successContainer = $('#status') \n</code></pre>\n<p>Then the <code>beforeSend</code> callback could be simplified to a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Partially_applied_functions\" rel=\"nofollow noreferrer\">function partial</a>:</p>\n<pre><code>beforeSend: successContainer.html.bind(successContainer, &quot;Saving...&quot;),\n</code></pre>\n<p>And the success callback can also utilize that variable:</p>\n<pre><code>success: function(toFile) {\n // You can get data returned from your ajax call here. ex. jqObj.find('.returned-data').html()\n // Now show them we saved and when we did\n var d = new Date();\n statusContainer.html('Saved! Last: ' + d.toLocaleTimeString());\n},\n</code></pre>\n<p>A function partial could also be used to simplify the second timer:</p>\n<pre><code>timeoutId = setTimeout(onInput.bind(null, document.getElementById('toFile')), 3000);\n</code></pre>\n<h3>Selector for <code>&lt;form&gt;</code> element</h3>\n<p>You didn't include the HTML so I am not sure which element(s) this targets:</p>\n<blockquote>\n<pre><code>$('.form').submit(function(e) {\n</code></pre>\n</blockquote>\n<p>But I would guess it is a <code>&lt;form&gt;</code> tag with attribute <code>class=&quot;form&quot;</code>. If that is the case, the class attribute isn't necessary, even for CSS. The form element(s) could be selected with the tag name:</p>\n<pre><code>$('form').submit(function(e) {\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T23:30:19.680", "Id": "222555", "ParentId": "221666", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T16:28:05.967", "Id": "221666", "Score": "4", "Tags": [ "javascript", "php", "jquery", "ecmascript-6", "event-handling" ], "Title": "Whitelist for textarea and save input to file" }
221666
<p>I am trying to implement a parent <code>WebContent</code> class and child classes to grab HTTP responses from the actual website entities. There are highlevel codes below and I am wondering what are people's perspectives in terms of the neatest way to implement this in a OOP manner.</p> <pre><code>import requests from onelogin.api.client import OneLoginClient class WebContent(object): def __init__(self, client_id, client_secret, login, password, sub_domain, app_id, app_url): self.client_id = client_id self.client_secret = client_secret self.app_id = app_id self.app_url = app_url self.login = login self.password = password self.sub_domain = sub_domain def _login(self): client = OneLoginClient(self.client_id, self.client_secret) saml = client.get_saml_assertion(self.login, self.password, self.app_id, self.sub_domain) saml_data = saml.saml_response session = requests.Session() saml_payload = {'SAMLResponse': saml_data} session.post("{}/sso/response".format(self.app_url), saml_payload) return session def get_content(self, endpoint, time_out=30): if endpoint: session = self._login() result = session.get(endpoint, timeout=time_out) session.close() return result.content class WebMarketingContent(WebContent): def get_endpoint(self, entity_id): base_url = "{app_url}/{entity_id}?{query_params}" params = '&amp;entity_id={}'.format(entity_id) return base_url.format(app_url=self.app_url, query_params=params) class WebEducationContent(WebContent): def get_endpoint(self, entity_id): base_url = "{app_url}/category/adhoc_element/{entity_id}?{query_params}" params = '&amp;entity_id={}'.format(entity_id) return base_url.format(app_url=self.app_url, query_params=params) if __name__ == '__main__': web_marketing_content = WebMarketingContent('client_id', 'client_secret', 'email', 'password', 'sub_domain', 'app_id', 'app_url') endpoint = web_marketing_content.get_endpoint(123) result = web_marketing_content.get_content(endpoint) </code></pre>
[]
[ { "body": "<p>Some suggestions:</p>\n\n<ol>\n<li><code>if __name__ == '__main__':</code> is usually followed by a call to a <code>main</code> method. The <code>main</code> method then parses arguments using for example <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> to inject all the things which should not be hardcoded in the application - definitely passwords, but in your case probably all of the parameters to <code>WebMarketingContent</code>. This makes the code reusable and scriptable.</li>\n<li><code>WebEducationContent</code> is not used anywhere, so it should be removed.</li>\n<li>Take advantage of static analysis and formatting using <code>black</code>, <code>flake8</code> and <code>mypy</code> with a strict configuration to improve the overall quality.</li>\n<li>You shouldn't need to get the endpoint before getting the content. <code>web_marketing_content.get_content(123)</code> should itself work out the endpoint and request it.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:58:07.793", "Id": "221706", "ParentId": "221667", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T16:29:15.843", "Id": "221667", "Score": "1", "Tags": [ "python", "object-oriented", "web-scraping", "http", "authentication" ], "Title": "Python classes to grab HTTP response from website entities" }
221667
<p>This is a <a href="https://leetcode.com/problems/escape-a-large-maze/" rel="nofollow noreferrer">Leetcode problem</a> -</p> <blockquote> <p><em>In a 1 million by 1 million grid, the coordinates of each grid square are <code>(x, y)</code> with <span class="math-container">\$0\$</span> <span class="math-container">\$&lt;=\$</span> <code>x</code><span class="math-container">\$,\$</span> <code>y</code> <span class="math-container">\$&lt;\$</span> <span class="math-container">\$10^6\$</span>.</em></p> <p><em>We start at the <code>source</code> square and want to reach the <code>target</code> square. Each move, we can walk to a 4-directionally adjacent square in the grid that isn't in the given list of <code>blocked</code> squares.</em></p> <p><em>Return <code>True</code> if and only if it is possible to reach the target square through a sequence of moves.</em></p> <p><strong><em>Example 1 -</em></strong></p> <pre><code>Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2] Output: False # Explanation: # The target square is inaccessible starting from the source square because we can't walk outside the grid. </code></pre> <p><strong><em>Example 2 -</em></strong></p> <pre><code>Input: blocked = [], source = [0,0], target = [999999,999999] Output: True # Explanation: # Because there are no blocked cells, it's possible to reach the target square. </code></pre> <p><strong><em>Note -</em></strong></p> <ul> <li><em><code>0 &lt;= blocked.length &lt;= 200</code></em></li> <li><em><code>blocked[i].length == 2</code></em></li> <li><em><code>0 &lt;= blocked[i][j] &lt;</code> <span class="math-container">\$10^6\$</span></em></li> <li><em><code>source.length == target.length == 2</code></em></li> <li><em><code>0 &lt;= source[i][j], target[i][j] &lt;</code> <span class="math-container">\$10^6\$</span></em></li> <li><em><code>source != target</code></em></li> </ul> </blockquote> <p>Here is my solution to this challenge -</p> <pre><code>from collections import deque # Bidirectional BFS def is_escape_possible(blocked: List[List[int]], source: List[int], target: List[int]) -&gt; bool: if len(blocked) &lt; 2: return True n = 10 ** 6 block_set = set(map(tuple, blocked)) #initialize two deque bfs_que_s = deque([tuple(source)]) bfs_que_t = deque([tuple(target)]) # visited sets for the two points visited_s = set([tuple(source)]) visited_t = set([tuple(target)]) # wave set means the outline of BFS wave_s = set([tuple(source)]) wave_t = set([tuple(target)]) # BFS into the next layer, if the current queue is empty, return False, which means this point is sealed by blocks def bfs_next(bfs_que, visited, wave): size = len(bfs_que) if not size: return False wave.clear() for _ in range(size): c_r, c_c = bfs_que.popleft() for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]: n_r = c_r + dx n_c = c_c + dy if 0 &lt;= n_r &lt; n and 0 &lt;= n_c &lt; n and (n_r, n_c) not in block_set and (n_r, n_c) not in visited: bfs_que.append((n_r, n_c)) visited.add((n_r, n_c)) wave.add((n_r, n_c)) return True # mark the points have escaped or not escape_s = False escape_t = False # when waves share some same values, they met in the search, return True while not wave_s &amp; wave_t: if not escape_s: if not bfs_next(bfs_que_s, visited_s, wave_s): return False # when wave's length &gt; blocks' length, the point must have escaped the blocks if len(wave_s) &gt; len(blocked): escape_s = True if not escape_t: if not bfs_next(bfs_que_t, visited_t, wave_t): return False if len(wave_t) &gt; len(blocked): escape_t = True #both of the points are escaped if escape_s and escape_t: return True return True </code></pre> <p><strong>Here is my idea of the challenge -</strong></p> <p><em>If we conduct two independent searches to find out whether either of the two points is blocked or not, we may search for many duplicated and unnecessary points in the case that two points can reach each other. So we can start BFS from both directions simultaneously, one layer frontward and one layer backward; when they meet, we can return <code>True</code>.</em></p> <p>Here is my Leetcode result -</p> <blockquote> <p><a href="https://i.stack.imgur.com/ZeVmN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZeVmN.png" alt="enter image description here"></a></p> </blockquote> <p>So, I would like to know whether I could make this program shorter and more efficient.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T19:18:11.260", "Id": "428751", "Score": "0", "body": "The biggest speed up will come from realizing there is a better algorithm for this problem, which will give orders of magnitude improvement in speed. Optimizing this algorithm will provide only minor gains. But since this is a programming challenge, on a code review site, not an algorithm review site, I’ll leave it to the OP to enjoy the euphoria that comes with the discovery of the correct algorithm." } ]
[ { "body": "<p>There are few redundancies, both time and memory wise.</p>\n\n<ul>\n<li><p>You don't need to maintain an entire <code>visited</code> set. It is only necessary for a general graph. For the grid, the wave computed at the previous iteration serves equally good.</p></li>\n<li><p>Upon completion of <code>bfs_next</code>, both <code>wave</code> and <code>bfs_que</code> contain the same set of points. You don't need to update <code>wave</code> in the loop. Do <code>wave = set(bfs_que)</code> once, after the loop terminates. Since <code>set</code> is a built-in primitive, this should run faster.</p></li>\n<li><p>I am not sure that <code>dequeue</code> is a right tool. The <code>for _ in range(size)</code> loop effectively drains it every time, and there is no need to store the new wavefront in the same structure with the old one. Consider using two lists instead.</p></li>\n</ul>\n\n<p>Also, for the clarity of the algorithm, I'd seriously consider reworking <code>bfs_next</code> into a generator, <code>yield</code>ing the next wavefront.</p>\n\n<hr>\n\n<p>All that said, I am not convinced that <code>len(wave) &gt; len(blocked)</code> means escape. In fact, correct me if I am wrong, when 9 blockers cut off the corner</p>\n\n<pre><code> |*\n | *\n | *\n | 3*\n | 323*\n |32123*\n |210123*\n |32123 *\n | 323 *\n +----------\n</code></pre>\n\n<p>the length of the third wavefront is 10. However, there is no escape.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T18:06:49.227", "Id": "221675", "ParentId": "221668", "Score": "2" } }, { "body": "<p>Without leaking the better algorithm, I'll highlight one area where this code can be dramatically improved.</p>\n\n<p>You are ignoring a pair of important facts:</p>\n\n<ul>\n<li>0 &lt;= <code>len(blocked)</code> &lt;= 200</li>\n<li>0 &lt;= <code>blocked[i][j]</code> &lt; <span class=\"math-container\">\\$10^6\\$</span></li>\n</ul>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Pigeonhole_principle\" rel=\"nofollow noreferrer\">Pigeonhole principle</a>: if you have more holes than pigeons, some holes will be empty. On your grid, you have at least 999800 rows that will be empty, and at least 999800 columns that will be empty. Using a BFS wave that traverses the grid space can result in taking a lot of steps which can be optimized away.</p>\n\n<pre><code>x_min = min(block[0] for block in blocked)\nx_max = max(block[0] for block in blocked)\ny_min = min(block[1] for block in blocked)\ny_max = max(block[1] for block in blocked)\n</code></pre>\n\n<p>The above will quickly determine the bounds of all blocked cells.</p>\n\n<pre><code> :\n 0\n x_min : x_max\n 0|0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0|0\n -+-------------------------------------------+-\n 0|0 1 0 1 0 0 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0|0 y_min\n 0|1 0 1 0 1 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0|0\n... 0 ... 0|0 0 1 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 1 1 1 0|0 ... 0 ...\n 0|0 0 1 0 1 0 0 1 0 1 0 1 0 0 0 0 0 1 0 0 0 1|0\n 0|0 0 0 1 0 1 1 0 0 1 1 0 0 0 0 0 0 0 1 0 1 0|0\n 0|0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0|0 y_min\n -+-------------------------------------------+-\n 0|0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0|0\n :\n 0\n :\n</code></pre>\n\n<p>If your starting point is to the left of <code>x_min</code>, or above <code>y_min</code>, or to the right of <code>x_max</code>, or below <code>y_max</code>, <strong>and</strong> your target point is to the left of <code>x_min</code>, or above <code>y_min</code>, or to the right of <code>x_max</code>, or below <code>y_max</code> <strong>then</strong> the path cannot be blocked. Fast succeed for the trivial cases, verses the wave propagation which might have to create a wavefront from one side of the grid to the other.</p>\n\n<p>But wait! It is possible for <code>[0,0]</code> and <code>[999999,999999]</code> to both be in <code>blocked</code> which makes the bounding box <code>[[x_min, y_min], [x_max, y_max]]</code> encompass the entire grid.</p>\n\n<p>Again, by the pigeon hole principle, with only 200 blocked grid spots, if <code>x_max - x_min + 1 &gt; 200</code>, there will be a column in between those limits which is completely unblocked. Similarly, if <code>y_max - y_min + 1 &gt; 200</code>, there will be a row in between those limits which is completely unblocked. Either one will allow you to subdivide the grid into two (or more) bounding boxes whose sides are less than 200 cells in length. In the above figure, you could divide the region into two sub regions: one 12 cells wide and the other 5 cells wide. After partitioning, the left region becomes 12x5 and the right region is 5x4. If the starting point and the target point are both outside of all bounding boxes, then the path cannot be blocked.</p>\n\n<p>If either, or both, of the path end points are within a <code>blocked</code> bounding box, you can use your BFS wavefront to attempt to escape the bounding box. If both end points can escape, the path is not blocked. If both path end points are within the same bounding box, then if the wavefronts meet, then the path is not blocked. In any case, your BFS wavefront algorithm need only operate in at most a 200x200 grid area, not the entire <span class=\"math-container\">\\$10^6 x 10^6\\$</span> problem grid.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T00:27:47.417", "Id": "221686", "ParentId": "221668", "Score": "2" } } ]
{ "AcceptedAnswerId": "221686", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T16:44:06.013", "Id": "221668", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "breadth-first-search" ], "Title": "(Leetcode) Escape a large maze" }
221668
<p>I'm working with a large enterprise SQL Server database with dozens of tables that are used mainly as lookups to populate dropdown lists, etc. These tables all follow the convention of having (table)Name as the string value of the item. For example the <code>State</code> table has a <code>StateName</code> column with values like California, Florida, etc.</p> <p>There is an old method used to load data for a dropdown that uses raw SQL, it looks like this:</p> <pre><code>public async Task&lt;IEnumerable&lt;string&gt;&gt; GetLookupOptions(string table) { List&lt;string&gt; values = new List&lt;string&gt;(); using (var command = _context.Database.GetDbConnection().CreateCommand()) { command.CommandText = $"SELECT {table}Name FROM {table} WHERE IsApproved = 1"; _context.Database.OpenConnection(); using (var result = await command.ExecuteReaderAsync()) { do { while (result.Read()) { values.Add(result.GetString(0)); } } while (result.NextResult()); } } return values; } </code></pre> <p>This isn't testable using <code>InMemoryDatabase</code> and only works against an actual database connection. I have rewritten it using Reflection and Expressions to query the <code>DbContext.DbSet&lt;T&gt;</code> based on the table name provided, like this:</p> <pre><code>public IEnumerable&lt;string&gt; GetLookupOptions(string table) { // Get the Type for State and then replace its name with whatever entity this is querying. // This is hacky but it's used so the AssemblyQualifiedName will always have correct // version info. Type t = typeof(State); t = Type.GetType(t.AssemblyQualifiedName.Replace("State", table)); // Get lambda used to filter &lt;table&gt; where IsApproved is true. object whereLamda = this.GetType() .GetMethod(nameof(CreateWhereExpression), BindingFlags.NonPublic | BindingFlags.Instance) .MakeGenericMethod(t) .Invoke(this, new object[0]); // Get lambda used to select &lt;table&gt;Name from &lt;table&gt;. object selectLamda = this.GetType() .GetMethod(nameof(CreateSelectExpression), BindingFlags.NonPublic | BindingFlags.Instance) .MakeGenericMethod(t) .Invoke(this, new object[] { table }); // Get the DbSet&lt;T&gt; for the &lt;table&gt;. object set = _context.GetType() .GetMethod("Set") .MakeGenericMethod(t) .Invoke(_context, new object [0]); IEnumerable&lt;MethodInfo&gt; whereMethods = typeof(Enumerable) .GetMethods().Where(m =&gt; m.Name == nameof(Enumerable.Where)); // Apply Where() method to DbSet. object filteredApproved = whereMethods .ElementAt(0) .MakeGenericMethod(t) .Invoke(set, new object[] { set, whereLamda }); IEnumerable&lt;MethodInfo&gt; selectMethods = typeof(Enumerable) .GetMethods().Where(m =&gt; m.Name == nameof(Enumerable.Select)); // Apply Select() method to filtered query. object r = selectMethods .ElementAt(0) .MakeGenericMethod(t, typeof(string)) .Invoke(filteredApproved, new object[] { filteredApproved, selectLamda }); return r as IEnumerable&lt;string&gt;; } private Func&lt;T, string&gt; CreateSelectExpression&lt;T&gt;(string tableName) { var param = Expression.Parameter(typeof(T)); var expr = Expression.Property(param, $"{tableName}Name"); return Expression.Lambda&lt;Func&lt;T, string&gt;&gt;(expr, param).Compile(); } private Func&lt;T, bool&gt; CreateWhereExpression&lt;T&gt;() { var param = Expression.Parameter(typeof(T)); var expr = Expression.Equal( Expression.Property(param, "IsApproved"), Expression.Constant(true)); return Expression.Lambda&lt;Func&lt;T, bool&gt;&gt;(expr, param).Compile(); } </code></pre> <p>My concerns are:</p> <ul> <li>Getting the correct <code>Where</code> and <code>Select</code> methods from Reflection, I don't like relying on <code>ElementAt()</code>. Both methods have overloads with 2 parameters.</li> <li>Any and all other problems. Have I created a monster?</li> </ul>
[]
[ { "body": "<p>I'm going to start off by saying I didn't test this code. There might be some issues but I didn't setup EF and an In Memory Provider. </p>\n\n<p>First I would load all the types right away and cache them and do some filtering to make sure they have the two properties we care about. </p>\n\n<p>You didn't save what your class name is so I'm going with DropDownLookUp</p>\n\n<pre><code>public class DropDownLookUp\n{\n\n private DbContext _context;\n\n private readonly static IDictionary&lt;string, Type&gt; Mappings;\n private readonly static MethodInfo WhereMethod;\n private readonly static MethodInfo SelectMethod;\n\n static DropDownLookUp()\n {\n // Load up all the types and cache them making sure they have the properties we need\n Mappings = typeof(State).Assembly.GetLoadableTypes()\n .Where(x =&gt; x.GetProperty(\"IsApproved\")?.PropertyType == typeof(bool) &amp;&amp;\n x.GetProperty(x.Name + \"Name\")?.PropertyType == typeof(string))\n .ToDictionary(x =&gt; x.Name, x =&gt; x);\n\n Func&lt;IQueryable&lt;object&gt;, Expression&lt;Func&lt;object, bool&gt;&gt;, IQueryable&lt;object&gt;&gt; whereMethod = Queryable.Where;\n WhereMethod = whereMethod.Method.GetGenericMethodDefinition();\n\n Func&lt;IQueryable&lt;object&gt;, Expression&lt;Func&lt;object, object&gt;&gt;, IQueryable&lt;object&gt;&gt; selectMethod = Queryable.Select;\n SelectMethod = selectMethod.Method.GetGenericMethodDefinition();\n }\n</code></pre>\n\n<p>We do a one time load of the LoadableTypes and have a type safe way to grab the method infos for the Queryable Select and Where clauses. </p>\n\n<p>Type load I got from StackOverFlow it's like this</p>\n\n<pre><code>public static class AssemblyExtensions\n{\n public static IEnumerable&lt;Type&gt; GetLoadableTypes(this Assembly assembly)\n {\n if (assembly == null)\n {\n throw new ArgumentNullException(\"assembly\");\n }\n try\n {\n return assembly.GetTypes().Where(x =&gt; x.IsPublic);\n }\n catch (ReflectionTypeLoadException e)\n {\n\n return e.Types.Where(t =&gt; t != null &amp;&amp; t.IsPublic);\n }\n }\n}\n</code></pre>\n\n<p>Now we don't want to drop down into IEnumerable until we have to. We want to stay in ExpressionTrees and build up an IQueryable. </p>\n\n<pre><code>private Expression CreateSelectExpression(Expression source)\n{\n var param = Expression.Parameter(source.Type);\n var project = Expression.Property(param, $\"{source.Type.Name}Name\");\n var selector = Expression.Lambda(typeof(Func&lt;,&gt;).MakeGenericType(source.Type, typeof(string)), project, param);\n return Expression.Call(SelectMethod.MakeGenericMethod(source.Type, typeof(string)), source, selector);\n}\n\nprivate Expression CreateWhereExpression(Expression source)\n{\n var param = Expression.Parameter(source.Type);\n var filter = Expression.Equal(\n Expression.Property(param, \"IsApproved\"),\n Expression.Constant(true));\n\n var whereClause = Expression.Lambda(typeof(Func&lt;,&gt;).MakeGenericType(source.Type, typeof(bool)), filter, param);\n return Expression.Call(WhereMethod.MakeGenericMethod(source.Type), source, whereClause);\n}\n</code></pre>\n\n<p>These methods now call the Queryable.Select and Queryable.Where. If you want you could cache these methods per Type but I find building Expressions isn't that taxing, where compiling them is, but it's worth testing to see if you want to add some cache to these methods. </p>\n\n<p>For the main method we can just check the Mappings and if not found either return empty enumerable or throw. We can still use the reflection on Set. If you really wanted you could build an expression tree to give you back the IQueryable when passing in a type. I would base that on if you have performance issues or not. </p>\n\n<pre><code>public async Task&lt;IEnumerable&lt;string&gt;&gt; GetLookupOptions(string table)\n{\n Type type;\n if (!Mappings.TryGetValue(table, out type))\n {\n // Or you can throw your choice\n return Enumerable.Empty&lt;string&gt;();\n }\n\n // Get the DbSet&lt;T&gt; for the &lt;table&gt;.\n IQueryable set = (IQueryable)_context.GetType()\n .GetMethod(\"Set\")\n .MakeGenericMethod(type)\n .Invoke(_context, new object[0]);\n\n var query = set.Provider.CreateQuery&lt;string&gt;(CreateSelectExpression(CreateWhereExpression(set.Expression)));\n return await query.ToListAsync().ConfigureAwait(false);\n}\n</code></pre>\n\n<p>We can use the IQueryable Provider to create a new Query based on the expressions we build - which should execute the where and select up on the server and we can now use the ToListAsync to make the method async again. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T19:15:35.460", "Id": "428931", "Score": "0", "body": "`whereMethod = Queryable.Where;` was a key. `Queryable.Where.Method` wouldn't work so I was caught up there before reading your answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T23:34:13.003", "Id": "428961", "Score": "0", "body": "If something not working let me know and I can take a look tomorrow. Was busy and though something pointing in right direction would help out" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T16:01:49.067", "Id": "429047", "Score": "1", "body": "No it's working fine, it was what I needed to ensure I have the correct method overloads." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T16:56:12.187", "Id": "429060", "Score": "0", "body": "Cool. One of the few times code works without testing it :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T22:57:29.780", "Id": "221684", "ParentId": "221673", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T17:57:47.090", "Id": "221673", "Score": "2", "Tags": [ "c#", "comparative-review", "linq", "reflection", "expression-trees" ], "Title": "Populating dropdown lists, using SQL vs. using expression trees and reflection" }
221673
<p>Got caught up with this morning's <a href="https://codereview.stackexchange.com/q/221627/507">C++ question</a>.<br> So I thought I would have a go.</p> <p>SO here is my attempt at printing the first 1001 primes.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;cmath&gt; bool isPrime(std::size_t num, std::vector&lt;std::size_t&gt; const&amp; primes) { std::size_t max = std::sqrt(num); for(auto const&amp; prime: primes) { if (prime &gt; max) { return true; } if (num % prime == 0) { return false; } } return true; } std::size_t sieve(std::size_t size, std::vector&lt;std::size_t&gt;&amp; results) { // primeCandidates holds 0/1 for each potential prime candidate. // The index represents the potential prime (index * 2 + 1) // This allows us to ignore all factors of 2 // max is one past the highest prime candidate we can test for and store in primeCandidates std::size_t const max = size * 2 + 1; std::vector&lt;std::size_t&gt; primeCandidates(size, 1); // Add some default well know primes. results.push_back(2); results.push_back(3); // We will use the technique of incrementing by 2 then 4 then 2 then 4 // This means skip all factors of 2 and 3 automatically. std::size_t inc = 2; std::size_t loop = 5; for(; loop &lt; max; loop += inc, inc = 6 - inc) { std::size_t index = loop/2; // If we find a candidate that is valid then add it to results. if (primeCandidates[index]) { results.push_back(loop); // Now strain out all factors of the prime we just found. for(; index &lt; primeCandidates.size(); index += loop) { primeCandidates[index] = 0; } } } return loop; } int main() { std::size_t constexpr primeRequired = 1001; std::size_t constexpr siveStartSize = 1000; std::vector&lt;std::size_t&gt; result; result.reserve(primeRequired); // Use the Sieve of Eratosthenes to get a basic set of primes. std::size_t next = sieve(siveStartSize, result); // Want to re-use the 2/4/2/4 increment pattern // So work out the correct start point and increment value. std::size_t inc = next % 6 == 5 ? 2 : 4; // We now use brute force checking each number against all the primes // that we have already found. for(; result.size() &lt;= primeRequired; next += inc, inc = 6 - inc) { if (isPrime(next, result)) { result.emplace_back(next); } } // Print out the primes we have found for(auto val: result) { std::cout &lt;&lt; val &lt;&lt; " "; } std::cout &lt;&lt; "\n"; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T19:38:16.543", "Id": "428755", "Score": "0", "body": "Missing `<cstddef>` for `std::size_t`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T20:16:59.790", "Id": "428764", "Score": "0", "body": "Yeah ... now that's a mixture of the sieve and brute force. From the [first sentence here](https://codereview.stackexchange.com/a/221664/36647) I thought it's possible to implement solely with the sieve part." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T20:22:55.530", "Id": "428767", "Score": "0", "body": "@ThomasWeller The \"Sieve of Eratosthenes\" can be implemented in many ways. I just took a simplistic approach here. There is a way of estimating the number of primes lower than a particular value. See [Prime Counting](https://en.wikipedia.org/wiki/Prime-counting_function) but there is also the factor of how much space your computer has. So for the sieve you don't want to allocate more space than your computer has and you don't want to overestimate (too much) how many primes there are below the value you want. This usually means a guess that is low and then brute forcing the rest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T20:34:47.837", "Id": "428769", "Score": "0", "body": "You can make a good guess by for the size of the array by solving `x/ln(x) = <No of Primes>` X= <Size of Array>. But is that the optimal size of the array? At some point you are doing a lot of work maintaining the \"potential candidates\" when it could be simpler to brute force? (not sure about that)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-13T14:30:18.643", "Id": "430018", "Score": "0", "body": "How is the performance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-14T18:28:14.200", "Id": "430190", "Score": "0", "body": "@pacmaninbw: With: https://codereview.stackexchange.com/q/221795/507 against brute force (but only checking against primes). For: `1001` primes: 0.015s against 0.017s. For `1000001` primes: 3.657s against killed the processes after 90 seconds." } ]
[ { "body": "<p>First of all: great code. I'd love to read code like this in our implementations. For me that's a nice mixture of useful comments when needed with self-explaining code.</p>\n\n<p>I also like the modern way of writing using <code>constexpr</code> instead of <code>#define</code>, which I still see a lot.</p>\n\n<p>I'm not a C++ pro, rather coming from the C# side, so I notice the following:</p>\n\n<ul>\n<li><p><code>std::size_t</code> is IMHO thought for the <code>sizeof</code>. You use it almost everywhere. I'd prefer to read <code>int</code>, <code>long</code> or even <code>using ll = long long;</code>. Using <code>size_t</code> for me adds semantic: this is of type <code>size</code>, so I e.g. use it as the end condition for a loop, use it for memory allocation or similar. That's not the case in the prime program.</p></li>\n<li><p><code>isPrime()</code> takes a number and a list of primes, but it's not documented what needs to be in that list in order to make the function work. I could potentially call it with a large number but an empty list.</p></li>\n<li><p>I dislike crippled <code>for</code> loops. Even worse with two statements in the increment part. What's wrong with a while loop? </p>\n\n<pre><code>while(result.size() &lt;= primeRequired) {\n if (isPrime(next, result)) {\n result.emplace_back(next);\n } \n next += inc;\n inc = 6 - inc;\n} \n</code></pre></li>\n<li><p>typo: <code>primeRequired</code> should IMHO be <code>primesRequired</code>, because you don't want to go up to a number but up to a count.</p></li>\n<li><p>you could split the main method in two methods, one for calculating (testable by unit tests) and one for printing</p></li>\n</ul>\n\n<p>Just a though: instead of using math for doing the <code>inc</code> magic, would C++ support something like</p>\n\n<pre><code>int nextinc() {\n while(true) {\n yield 2;\n yield 4;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T20:42:02.880", "Id": "428770", "Score": "1", "body": "`int nextInc() {static inc = 4; inc = 6 - inc; return inc;}`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T20:47:58.437", "Id": "428772", "Score": "2", "body": "Can't argue with any of that. :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T04:01:00.363", "Id": "428797", "Score": "1", "body": "`size_t` is preferable to a signed type, since there's nothing here that needs negative numbers. It will also (generally) be a size that is easy/natural for the CPU to access and use. And I much prefer the `for` loop to the `while`. Fewer problems when you later add a `continue`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T06:09:23.250", "Id": "428806", "Score": "0", "body": "In response to the question about yield, C++ 20 has `co_yield` although it requires \"a little\" more code to work in practice" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:07:12.420", "Id": "428817", "Score": "0", "body": "@1201ProgramAlarm: There is still `unsigned int` if you want positive numbers only." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T20:38:31.347", "Id": "221681", "ParentId": "221678", "Score": "7" } }, { "body": "<p>When you find a prime number, say 7, you begin crossing out all odd multiples of 7 from the <code>primeCandidates</code> vector. You do this by incrementing <code>index += loop</code>, where <code>loop</code> is the prime number, and but <code>primeCandidates</code> only holds odd candidates, so the step size in natural numbers would be <code>2*loop</code>.</p>\n\n<p>The issue is you start by removing <code>7</code> from <code>primeCandidates</code>, then <code>21</code>, then <code>35</code>. At this point in the sieve, you've already eliminated multiples of <code>3</code> and <code>5</code>, so marking off <code>3*7=21</code> and <code>5*7=35</code> is just busy work. And marking off <code>1*7=7</code> is just pointless. What you should be doing is starting to eliminate at <code>7*7=49</code>. It saves only three eliminations during the <code>7</code> loop, but the saving get more substantial as the prime gets larger. For instance, when you get to <code>199</code>, you wouldn't eliminate <code>1*199</code>, <code>3*199</code>, <code>5*199</code>, <code>7*199</code>, ... <code>191*199</code>, <code>193*199</code>, <code>195*199</code>, <code>197*199</code>. You would just start at <code>199*199</code> and go up from there.</p>\n\n<p>Code change:</p>\n\n<pre><code>// Now strain out all factors of the prime we just found, starting with prime^2\nindex = loop * loop / 2\n</code></pre>\n\n<hr>\n\n<p><code>std::vector&lt;std::size_t&gt;</code> is overkill for <code>primeCandidates</code>. You only ever store <code>1</code> or <code>0</code>, so allocating 4 or 8 bytes for each candidate is wasting memory.</p>\n\n<p><code>std::vector&lt;char&gt;</code> would reduce the memory load to 1 byte per candidate.</p>\n\n<p><a href=\"http://www.cplusplus.com/reference/bitset/bitset/\" rel=\"noreferrer\"><code>std::bitset&lt;N&gt;</code></a> will reduce this to 1 bit per candidate. Alternately, the vector specialization <a href=\"http://www.cplusplus.com/reference/vector/vector-bool/\" rel=\"noreferrer\"><code>std::vector&lt;bool&gt;</code></a> will also give 1 bit per candidate, with a non-compile-time fixed number of bits.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T16:08:22.053", "Id": "428908", "Score": "0", "body": "Because the `primeCandidates` only holds odd values incrementing by 7 is actually equivalent of incrementing by 14 each time. Since we start at 7 then increment by 14 each time we always hit every odd value (there is no point in hitting the even ones). Note we get the index first by starting at `index = 7/2` then add 2*7 to the index each loop through. That is actually a nice optimization that fell out of writting this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T16:10:14.120", "Id": "428909", "Score": "0", "body": "Nice optimization to start at `loop * loop` in the sieve" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T17:03:41.443", "Id": "428913", "Score": "0", "body": "@MartinYork My first paragraph wasn’t a review comment on the code; it was just an acknowledgement that I grokked that `primeCandidates` held just the odd candidates, so you can increment by 7 to eliminate just the odd multiples of 7 (which occur every 14 natural numbers). Perhaps I need to reword it. The second paragraph starts “The issue is...”, which is what I was pointing out in the review." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T01:07:04.593", "Id": "221691", "ParentId": "221678", "Score": "12" } }, { "body": "<h1>Commenting</h1>\n<p>You could improve the functions with some introductory comments. In particular, the <code>isPrime()</code> predicate has an extra argument compared with the conceptual version - we should be clear what that's for (i.e. it's an ordered set of all primes up to <code>√num</code>). Similarly, <code>sieve()</code>'s <code>results</code> argument is assumed to be empty, but that's not clearly communicated. For a program this small, that's probably a very minor consideration, but still a good habit to be in.</p>\n<h1>Presentation</h1>\n<p>Choose one brace style and stick with it. Here, we have a mix of open brace styles:</p>\n<pre><code> if (prime &gt; max) {\n return true;\n } \n if (num % prime == 0)\n { \n return false;\n } \n</code></pre>\n<p>I'm also not very keen on the trailing whitespace, though that's easily fixed.</p>\n<p>Some spellings are, let's say, <em>unconventional</em>: <code>siveStartSize</code> really ought to be spelt <em><code>sieveStartSize</code></em>, and <code>well know primes</code> probably means <em><code>well-known primes</code></em>. I think that <code>ignore all factors of 2</code> actually meant all <em>multiples</em> of 2; the same substitution is present in <code>skip all factors of 2 and 3</code>.</p>\n<h1>Storage</h1>\n<p>Is there a good reason why <code>primeCandidates</code> stores <code>std::size_t</code> values holding either 0 or 1? <code>std::vector&lt;char&gt;</code> works just as well for me.</p>\n<p>Following this, I'd consider replacing</p>\n<blockquote>\n<pre><code>results.push_back(2);\nresults.push_back(3);\n</code></pre>\n</blockquote>\n<p>with</p>\n<pre><code>results = {2, 3};\n</code></pre>\n<p>so we don't have to assume that <code>results</code> is initially empty.</p>\n<h1>Structure</h1>\n<p>It seems strange that half of the work is in <code>main()</code>, where we re-compute the value of <code>inc</code> we had inside <code>sieve</code> in order to continue with the second half of the algorithm. I'd be inclined to keep that loop in <code>sieve()</code>, separated by a comment. Then <code>main()</code> simply do its job of choosing parameters, calling the function and printing results.</p>\n<h1>Flexibility</h1>\n<p>Why are <code>primeRequired</code> and <code>siveStartSize</code> constants? A useful program allows the user to obtain their choice of result.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T09:11:24.493", "Id": "221709", "ParentId": "221678", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T19:21:41.803", "Id": "221678", "Score": "14", "Tags": [ "c++", "primes", "sieve-of-eratosthenes" ], "Title": "Prime Sieve and brute force" }
221678
<p>I've been trying to practice more Python recently so I decided to try and make different simple text-based game programs. I'd hope anybody could help me see how to make the code neater or more efficient in any aspect.</p> <pre><code>import random words = [] guessed_letters = [] word_guess = [] joined_word = None def fill_list(): f = open('words.txt', 'r') for line in f: if len(line.strip()) &gt; 3: words.append(line.strip()) f.close() def reset(secret): for letter in secret: word_guess.append('_') def random_word(word_list): chosen = random.choice(word_list) return chosen def guess_letter(): while True: letter = input('Guess a letter a-z: ').lower().strip() if len(letter) != 1: print('Enter a single character only') elif not letter.isalpha(): print('Enter only alphabetical characters') elif letter in guessed_letters: print('Already guessed {}'.format(letter)) else: return letter def print_opening(): print('Welcome to Hangman!\n' 'Try to guess a random word one letter at a time\n' 'Good luck and have fun!\n') def play_again(): again = input().lower() if again.lower().startswith('y'): return True return False def play(): fill_list() tries = 5 while True: print_opening() secret_word = random_word(words) reset(secret_word) while tries != 0 and '_' in word_guess: print('You have {} tries left'.format(tries)) joined_word = ''.join(word_guess) print(joined_word) player_guess = guess_letter() for index, letter in enumerate(secret_word): if player_guess == letter: word_guess[index] = player_guess guessed_letters.append(player_guess) if player_guess not in secret_word: print('Wrong!') tries -= 1 if '_' not in word_guess: print('You win!\n{} was the word!\n'.format(secret_word)) else: print('You lose!\nThe word was {}'.format(secret_word)) print('Would you like to play another game? y/n') if play_again(): word_guess.clear() tries = 5 else: print('Thanks for playing!') break if __name__ == '__main__': play() </code></pre>
[]
[ { "body": "<p>One thing I would do is wrap this up in a hangman class. That way you could just toss away the hangman instance for a new one if the user ever decided to play again rather than resting all global variables. It would also decouple the handling of user input from the actual game. If the game size would grow this would make catching bugs a lot easier. </p>\n\n<p>But lets focus on some smaller things that are easier to change </p>\n\n<pre><code>chosen = random.choice(word_list)\nreturn chosen\n</code></pre>\n\n<p>Here your variable has no purpose, I would do</p>\n\n<pre><code>return random.choice(word_list)\n</code></pre>\n\n<p>Similar kind of story here </p>\n\n<pre><code>if again.lower().startswith('y'):\n return True\n return False\n</code></pre>\n\n<p>to </p>\n\n<pre><code>return again.lower().startswith('y')\n</code></pre>\n\n<p>Next is avoid magic constants at all costs, for example </p>\n\n<pre><code>if len(line.strip()) &gt; 3:\n</code></pre>\n\n<p>What is 3? Why is 3 important here? You should replace this with a global ALL_CAPS variable to represent what 3 is. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T02:03:20.187", "Id": "221693", "ParentId": "221683", "Score": "2" } }, { "body": "<p>Try to avoid global variables. For example <code>words</code> doesn't need to be a global. Instead, return a list of words from <code>fill_list()</code>, directly in the <code>play()</code> method:</p>\n\n<pre><code>def fill_list():\n words = []\n f = open('words.txt', 'r')\n for line in f:\n if len(line.strip()) &gt; 3:\n words.append(line.strip())\n f.close()\n return words\n\n...\n\ndef play():\n words = fill_list()\n ...\n</code></pre>\n\n<hr>\n\n<p>Use a resource manager (aka a <code>with</code> statement) for opening closable resources. That takes the burden of calling <code>.close()</code> off of you, and ensures the resource is properly closed even when exceptions occur:</p>\n\n<pre><code>def fill_list():\n words = []\n with open('words.txt', 'r') as f:\n for line in f:\n if len(line.strip()) &gt; 3:\n words.append(line.strip())\n return words\n</code></pre>\n\n<hr>\n\n<p>Avoid repeating the same calculations. You <code>strip</code> the <code>line</code> to check its length, then you <code>strip</code> the <code>line</code> again to <code>append</code> it to <code>words</code>. Save the stripped line in a variable.</p>\n\n<pre><code>def fill_list():\n words = []\n with open('words.txt', 'r') as f:\n for line in f:\n stripped = line.strip()\n if len(stripped) &gt; 3:\n words.append(stripped)\n return words\n</code></pre>\n\n<hr>\n\n<p>Use list comprehension.</p>\n\n<pre><code>def reset(secret):\n word_guess = ['_' for letter in secret]\n</code></pre>\n\n<p>Or without the global variable:</p>\n\n<pre><code>def reset(secret):\n return ['_' for letter in secret]\n\n...\n\ndef play():\n ...\n word_guess = reset(secret_word)\n ...\n</code></pre>\n\n<hr>\n\n<p>f-strings (<code>f''</code>) are a new feature as of Python 3.6. You can use them to avoid <code>.format()</code> statements by embedding variables directly in the strings. Eg)</p>\n\n<pre><code> print('Already guessed {}'.format(letter))\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code> print(f'Already guessed {letter}')\n</code></pre>\n\n<hr>\n\n<p>Don't repeat yourself. You have <code>tries = 5</code> at the top of <code>play()</code> and the bottom if the user elects to play again. If you moved <code>tries = 5</code> inside the <code>while True:</code> loop, at the top of the loop, you'd just need it once.</p>\n\n<p>Similarly for <code>word_guess.clear()</code>, you should move it to the beginning of the loop ... except it can be removed entirely because of the <code>word_guess = reset(secret_word)</code> change above.</p>\n\n<hr>\n\n<h2>Bugs</h2>\n\n<p>If <code>words.txt</code> contains uppercase characters, hyphens, apostrophe's, etc., the user will not be able to guess the word. You should:</p>\n\n<ul>\n<li>normalize the <code>secret_word</code> by calling <code>.lower()</code> on it.</li>\n<li><p>replace only letters with the underscore, leave hyphens, apostrophes, spaces alone.</p>\n\n<pre><code>def reset(secret):\n return ['_' if letter.isalpha() else letter for letter in secret]\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T02:05:54.700", "Id": "221694", "ParentId": "221683", "Score": "2" } } ]
{ "AcceptedAnswerId": "221694", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T22:11:18.630", "Id": "221683", "Score": "3", "Tags": [ "python", "python-3.x", "hangman" ], "Title": "My Hangman game in Python" }
221683
<p>I decided to try and write a <a href="https://en.wikipedia.org/wiki/Brainfuck" rel="nofollow noreferrer">Brainfuck</a> interpreter in C as an exercise. This could have been written in one file, but I decided to split it up into a State "class" and an some interpreter methods.</p> <p>An example test-run with a <a href="http://www.hevanet.com/cristofd/brainfuck/rot13.b" rel="nofollow noreferrer">ROT13 implementation in Brainfuck</a>:</p> <pre><code>const char* source_buffer = // Code in above link. Read from file in my test. interpret_with_std_io(source_buffer); // In the console Hello World! Uryyb Jbeyq! </code></pre> <p>I'd like suggestions on anything, but specifically:</p> <ul> <li><p>I'm fairly new to C. I'd like to know if I'm still making any newbie mistakes.</p></li> <li><p>A few parts of my interpreter/state separation feel clumsy. 99% of the state code requires no knowledge of the source code. <code>[</code> unfortunately has the potential to jump forwards, so unless I pre-compute all the possible jumps, I need access to the source so I can search for its matching <code>]</code>. I originally had the two <code>hande_loop_</code> functions in the state code, then moved it to the interpreter, then back to the state. As a consequences though, my interpreter function <code>dispatch_command</code> now requires access to the source, solely for <code>[</code>.</p></li> <li><p>I needed a variable-sized stack to store the jump points, and decided on a linked list. It seems perfect here. Am I handling it OK?</p></li> <li><p>The mismatched-brace handling logic is frustrating. The <code>handle_loop_</code> functions return <code>false</code> when they detect a mismatched brace. I need to manually feed this result all the way back to the main <code>interpret_with_state</code> function, just so I know whether an error happened. Exceptions would be perfect here, but obviously they aren't an option. Is there a better way of handling this?</p></li> </ul> <p>It's broken up into 3 files: <code>helpers.c</code> (for safe allocation helpers), <code>state.c</code> and <code>interpreter.c</code>.</p> <hr> <hr> <p>Helpers</p> <pre><code>#ifndef HELPERS_H #define HELPERS_H #include &lt;stdlib.h&gt; // Prints an error message to stderr if ptr is NULL // Message is in the form "Could not allocate space for %s.". void ensure_allocation(const void* ptr, const char* allocation_reason); // Attempts to allocate the requested amount of memory and asserts the validity of the // returned pointer using ensure_allocation before returning void* terminating_malloc(size_t bytes, const char* allocation_reason); #endif </code></pre> <hr> <pre><code>#include &lt;stdio.h&gt; #include "helpers.h" void ensure_allocation(const void* ptr, const char* allocation_reason) { if (!ptr) { fprintf(stderr, "Could not allocate space for %s.", allocation_reason); exit(EXIT_FAILURE); } } void* terminating_malloc(size_t bytes, const char* allocation_reason) { void* const ptr = malloc(bytes); ensure_allocation(ptr, allocation_reason); return ptr; } </code></pre> <hr> <hr> <p>State</p> <pre><code>#ifndef STATE_H #define STATE_H #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #define STANDARD_CELL_BUFFER_LENGTH 30000 typedef unsigned char Cell_Type; typedef struct Jump_Node { size_t jump_position; struct Jump_Node* next; } Jump_Node; typedef struct { size_t instruction_pointer; size_t cell_pointer; Cell_Type* cell_buffer; size_t buffer_length; Jump_Node* jump_nodes_head; } State; void init_state(State*, size_t buffer_length); // Initializes it with a buffer with the length of STANDARD_CELL_BUFFER_LENGTH void init_standard_state(State*); void advance_instruction_pointer(State*); void increment_current_cell(State*); // + void decrement_current_cell(State*); // - // bool returns indicate whether or not the new cell pointer is "inbounds" bool move_cell_pointer_left(State*); // &lt; bool move_cell_pointer_right(State*); // &gt; Cell_Type get_current_cell(State*); // . void set_current_cell(State*, Cell_Type new_cell_contents); // , // Return false and have no effect if a matching brace isn't found, and it was required for operation // Return true otherwise bool handle_loop_start(State*, const char* source); // [ bool handle_loop_end(State*); // ] // Frees the cell_buffer and the jump nodes; not the State pointer void free_state(const State*); #endif </code></pre> <hr> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include "helpers.h" #include "state.h" // ----- Jump Nodes ----- static void init_jump_node(Jump_Node* node, size_t position, Jump_Node* next_node) { node-&gt;jump_position = position; node-&gt;next = next_node; } static void free_jump_nodes(const Jump_Node* head) { const Jump_Node* current = head; while (current) { Jump_Node* next = current-&gt;next; free((Jump_Node*)current); current = next; } } // ----- State ----- void init_state(State* state, size_t buffer_length) { size_t const buffer_size = sizeof(Cell_Type) * buffer_length; Cell_Type* const cell_buffer = terminating_malloc(buffer_size, "cell buffer"); memset(cell_buffer, 0, buffer_size); state-&gt;instruction_pointer = 0; state-&gt;cell_pointer = 0; state-&gt;cell_buffer = cell_buffer; state-&gt;buffer_length = buffer_length; state-&gt;jump_nodes_head = NULL; } void init_standard_state(State* state) { init_state(state, STANDARD_CELL_BUFFER_LENGTH); } void advance_instruction_pointer(State* state) { state-&gt;instruction_pointer++; } static void add_to_current_cell(State* state, Cell_Type n_to_add) { size_t const cell_ptr = state-&gt;cell_pointer; state-&gt;cell_buffer[cell_ptr] += n_to_add; } void increment_current_cell(State* state) { add_to_current_cell(state, 1); } void decrement_current_cell(State* state) { add_to_current_cell(state, -1); } static bool move_cell_pointer_by(State* state, int move_by) { state-&gt;cell_pointer += move_by; size_t const c_ptr = state-&gt;cell_pointer; return c_ptr &gt; 0 &amp;&amp; c_ptr &lt; state-&gt;buffer_length; } bool move_cell_pointer_left(State* state) { return move_cell_pointer_by(state, -1); } bool move_cell_pointer_right(State* state) { return move_cell_pointer_by(state, 1); } Cell_Type get_current_cell(State* state) { const size_t cell_ptr = state-&gt;cell_pointer; return state-&gt;cell_buffer[cell_ptr]; } static bool current_cell_is_zero(State* state) { return get_current_cell(state) == 0; } void set_current_cell(State* state, Cell_Type new_cell_contents) { const size_t cell_ptr = state-&gt;cell_pointer; state-&gt;cell_buffer[cell_ptr] = new_cell_contents; } // Returns the index in the source of the brace matching the opening brace at the given position. // Returns -1 if a matching brace isn't found. static int matching_brace_position(size_t opening_brace_position, const char* source) { int depth = 1; for (int i = opening_brace_position + 1; ; i++) { const char command = source[i]; if (command == '\0') { return -1; } else if (command == '[') { depth += 1; } else if (command == ']') { depth -= 1; if (depth == 0) { return i; } } } } bool handle_loop_start(State* state, const char* source) { if (current_cell_is_zero(state)) { // Skip the loop const int pos = matching_brace_position(state-&gt;instruction_pointer, source); if (pos == -1) { return false; } else { state-&gt;instruction_pointer = pos; } } else { // Set a jump back point Jump_Node* const node = terminating_malloc(sizeof(Jump_Node), "jump node"); init_jump_node(node, state-&gt;instruction_pointer, state-&gt;jump_nodes_head); state-&gt;jump_nodes_head = node; } return true; } bool handle_loop_end(State* state) { const Jump_Node* const popped_jump = state-&gt;jump_nodes_head; if (popped_jump) { if (current_cell_is_zero(state)) { state-&gt;jump_nodes_head = popped_jump-&gt;next; free((Jump_Node*)popped_jump); } else { size_t const recorded_position = popped_jump-&gt;jump_position; state-&gt;instruction_pointer = recorded_position; } return true; } else { return false; } } void free_state(const State* state) { free(state-&gt;cell_buffer); free_jump_nodes(state-&gt;jump_nodes_head); } static void dbg_set_cell(State* state, size_t cell_ptr, Cell_Type contents) { state-&gt;cell_buffer[cell_ptr] = contents; } </code></pre> <hr> <hr> <p>Interpreter</p> <pre><code>#ifndef INTERPRETER_H #define INTERPRETER_H #include &lt;stdio.h&gt; // Interpret the supplied code either using the standard io streams, or the supplied ones. void interpret(const char* code, FILE* in_stream, FILE* out_stream); void interpret_with_std_io(const char* code); #endif </code></pre> <hr> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;limits.h&gt; #include "state.h" #include "interpreter.h" #include "helpers.h" // Returns a wrapped cell_pointer in the range 0 &lt;= cell_pointer &lt; buffer_size // Requires that cell_pointer isn't more than buffer_size out of bounds. static size_t wrap_cell_pointer(int signed_cell_pointer, size_t buffer_size) { int const scp = signed_cell_pointer; if (scp &lt; 0) { return buffer_size + scp; } else if (scp &gt;= (int)buffer_size) { return scp - buffer_size; } else { return scp; } } static void wrap_state_cell_pointer(State* state) { state-&gt;cell_pointer = wrap_cell_pointer(state-&gt;cell_pointer, state-&gt;buffer_length); } // Gets input from the supplied stream // Returns a falsey null character if the input was out of range // RELIES ON UCHAR_MAX!!! If Cell_Type is altered from an unsigned char, // this must be changed accordingly! static Cell_Type read_input_from_stream(FILE* in_stream) { int const input = getc(in_stream); return (input &gt; UCHAR_MAX || input &lt; 0) ? '\0' : input; } // This must also be changed if Cell_Type is changed! static void print_to_stream(FILE* out_stream, Cell_Type output) { fprintf(out_stream, "%c", output); fflush(out_stream); } static bool dispatch_command(State* state, char command, const char* source, FILE* in_stream, FILE* out_stream) { switch (command) { case '+': increment_current_cell(state); break; case '-': decrement_current_cell(state); break; case '&lt;': move_cell_pointer_left(state); wrap_state_cell_pointer(state); break; case '&gt;': move_cell_pointer_right(state); wrap_state_cell_pointer(state); break; case '[': { const bool matching = handle_loop_start(state, source); if (!matching) { puts("Unmatched [ found.\n"); return false; } break; } case ']': { bool const matching = handle_loop_end(state); if (!matching) { puts("Unmatched ] found.\n"); return false; } break; } case ',': { Cell_Type const input = read_input_from_stream(in_stream); if (input) { set_current_cell(state, input); } break; } case '.': { Cell_Type const output = get_current_cell(state); print_to_stream(out_stream, output); break; } } return true; } static void interpret_with_state(State* state, const char* source, FILE* in_stream, FILE* out_stream) { while (true) { char const command = source[state-&gt;instruction_pointer]; if (command == '\0') { break; } else { bool const evald_ok = dispatch_command(state, command, source, in_stream, out_stream); if (!evald_ok) { return; } advance_instruction_pointer(state); } } } void interpret(const char* code, FILE* in_stream, FILE* out_stream) { State state; init_standard_state(&amp;state); interpret_with_state(&amp;state, code, in_stream, out_stream); free_state(&amp;state); } void interpret_with_std_io(const char* code) { interpret(code, stdin, stdout); } </code></pre>
[]
[ { "body": "<ul>\n<li><p><code>matching_brace_position</code> does not <code>return -1</code> as advertised (<code>if the matching brace is not found</code>). If the matching brace is indeed not found, it returns nothing (in fact, it would access <code>source</code> out of bound). This is UB.</p></li>\n<li><p><strike><code>handle_loop_end</code> assumes a well-formed BF program. With an ill-formed one (having a stray <code>]</code>) it would try to <code>free</code> something which wasn't previously allocated.</strike></p>\n\n<p>As a side note, the cast <code>(Jump_Node*)popped_jump</code> is not necessary, and could even be harmful.</p>\n\n<p>As another side note, the final <code>else</code> is not necessary. Just <code>return false</code>.</p></li>\n<li><p>As the interpreter runs, the list of jump nodes is created and destroyed over and over again. I strongly recommend to create it once (rejecting the ill-formed programs in the process). BF is notoriously easy to compile after all.</p>\n\n<p>BTW, compiling (into a byte code at least) is an answer to your last bullet. If you insist on strictly interpreting, consider <code>setjmp/longjmp</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T03:29:03.960", "Id": "428796", "Score": "0", "body": "@Carcigenicate For the first it is even worse. The loop is not naturally terminated, and may access `source` beyond the bound. For the second, you are right." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T00:58:58.293", "Id": "221690", "ParentId": "221685", "Score": "3" } } ]
{ "AcceptedAnswerId": "221690", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T00:01:47.980", "Id": "221685", "Score": "3", "Tags": [ "c", "interpreter", "brainfuck", "c99" ], "Title": "Verbose Brainfuck Interpreter in C" }
221685
<p>I have created this generic calendar class which I call a TimePeriodGrouping. It can contain a series of interlocking time periods (i.e. years, months, days, hours...). When time is added to one of them, it recalculates to match the proper period. Also, since seconds start at 0 and months start at 1, it also accounts for that. Another feature is the function "getcount" which should transform the 24 hour times into AMPM style times.</p> <p>The difference between this and a normal calendar is that I want it to be generic. In some video games, there are only 4 months in a year and only 12 hours in a day.</p> <p>It seems to work fine in my test cases at the bottom. I implement a normal calendar down to the seconds.</p> <p>The reason I post this here is that it seems to work, but it feels very messy and insecure and I don't know what to do to make this more assured. I've added lots of asserts. But I feel like I haven't covered my bases very well.</p> <pre><code>#include &lt;vector&gt; #include &lt;string&gt; #include &lt;cassert&gt; #include &lt;iostream&gt; bool incRange(int low, int high, int x) { return (low &lt;= x) &amp;&amp; (x &lt;= high); } // this can be used to create a calendar! class TimePeriodGrouping { struct Period { std::string name; std::vector&lt;int&gt; period; int count; int indexBase; int getcount(int AMPMDividend) { int ret = count; ret %= 12; if (ret == 0) { ret = 12; } return ret; } }; /////////////////// interface public: std::vector&lt;Period&gt; periods; void newperiod_back(std::string a_name, std::vector&lt;int&gt; a_period, int a_count, int a_indexBase) { // assert the next highest has only one period assert((periods.back().period.size() == 1)); // assert that the amount of periods are equal to the size of the period of the next highest period, or 1. assert((a_period.size() == periods.back().period.size()) || (a_period.size() == 1)); // its all good. so add it to the back. periods.emplace_back(TimePeriodGrouping::Period{ a_name, a_period, a_count, a_indexBase }); // make sure the count is not lower than the index base.... periods.back().count += periods.back().indexBase; } void add(int i, int addend) { assert(incRange(0, periods.size()-1, i)); // test index periods[i].count += addend; recalculate(i); } void recalculate(int index) // only have to calculate from index to greatest { for (size_t i = index; i &gt; 0; i--) // Must go from least period and end on the greatest period. Don't run the greatest period. { int periodSize{ 0 }; if (periods[i].period.size() &gt; 1) // if the period has more than one period i.e. it is like days which are dependant on which month it is for their period. { periodSize = periods[i].period[i - 1]; // get the amount of days in that month ( [i-1] cause accessing next higher tier of periods) } else { periodSize = periods[i].period.front(); // only has one period, so just use the front. } // so at 24 hours, because we are at base index of 0. it should roll over to an extra day and 0 hours. // calculate if count is over periodSize. if (periods[i].count &gt;= periodSize + periods[i].indexBase) { int carry = periods[i].count / periodSize; // calculate carry periods[i].count = periods[i].count % periodSize; // mutate periods[i - 1].count += carry; // carry to next higher period } } } // Default construct with a base period. TimePeriodGrouping(std::string a_name, int a_count, int a_indexBase) { periods.emplace_back(TimePeriodGrouping::Period{ a_name, {0}, a_count, a_indexBase }); } }; ////////////////////////////////// TESTING void test_TimePeriodGrouping() { std::cout &lt;&lt; "running: " &lt;&lt; __func__ &lt;&lt; "\n"; TimePeriodGrouping tpg{ "Year", 2000, 1 }; tpg.newperiod_back( "Month", { 12 }, 0, 1 ); tpg.newperiod_back( "Day", { 30 }, 0, 1 ); tpg.newperiod_back( "Hours", { 24 }, 0, 0 ); tpg.newperiod_back("Minutes", { 60 }, 0, 0); for (auto&amp; p : tpg.periods) { std::cout &lt;&lt; p.name &lt;&lt; " " &lt;&lt; p.count &lt;&lt; " - "; } std::cout &lt;&lt; '\n'; tpg.add(0, 19); tpg.add(1, 6); tpg.add(2, 4); tpg.add(3, 13); tpg.add(4, 54); for (auto&amp; p : tpg.periods) { std::cout &lt;&lt; p.name &lt;&lt; " " &lt;&lt; p.count &lt;&lt; " - "; } std::cout &lt;&lt; '\n'; tpg.add(0, 0); tpg.add(1, 5); tpg.add(2, 25); tpg.add(3, 10); tpg.add(4, 5); for (auto&amp; p : tpg.periods) { std::cout &lt;&lt; p.name &lt;&lt; " " &lt;&lt; p.count &lt;&lt; " - "; } std::cout &lt;&lt; '\n'; tpg.add(4, 1); for (auto&amp; p : tpg.periods) { std::cout &lt;&lt; p.name &lt;&lt; " " &lt;&lt; p.count &lt;&lt; " - "; } std::cout &lt;&lt; '\n'; } int main() { test_TimePeriodGrouping(); } </code></pre>
[]
[ { "body": "<p><a href=\"https://cppdepend.com/blog/?p=79\" rel=\"nofollow noreferrer\">Wrap your code into a namespace</a></p>\n\n<hr>\n\n<blockquote>\n<pre><code>// this can be used to create a calendar! \nclass TimePeriodGrouping\n</code></pre>\n</blockquote>\n\n<p>Why not name the class something like CustomCalendar to indicate that it is a calendar but not a conventional one? </p>\n\n<hr>\n\n<p>Order your interface from public to private.</p>\n\n<hr>\n\n<p>Naming your member variable <code>period</code> when your surrounding struct is named <code>Period</code> seems like a poor choice. <code>count</code> and <code>name</code> are more bad naming choices. What does this count? What does it name? I'm not sure about <code>indexBase</code> either. Things get even worse later on with things like <code>a_name</code>.<br>\nIn short, work on your naming.</p>\n\n<hr>\n\n<p>Your comments are more confusing than helping. E.g.</p>\n\n<blockquote>\n<pre><code>// if the period has more than one period\n</code></pre>\n</blockquote>\n\n<p>which in part simply stems from your poor naming choices.</p>\n\n<hr>\n\n<p><code>AMPMDividend</code> is unused.</p>\n\n<hr>\n\n<p><code>getcount</code> does not do what its name implies. It either returns <code>count</code> mod 12 or 12 (which is a magic number and should be made into a named constant). From your question it becomes clear it's actually supposed to convert between 24h and AM/PM style. Again, <em>naming</em>.</p>\n\n<hr>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/questions/59880/avoid-postfix-increment-operator\">Prefer prefix over postfix</a></p>\n\n<hr>\n\n<p>Missing <code>&lt;cstddef&gt;</code> and <code>std::</code> for <code>size_t</code>.</p>\n\n<hr>\n\n<p>When looping with a ranged for loop add <code>const</code> unless you plan to modify the loop variable in the body.</p>\n\n<hr>\n\n<p>Something like this would profit from having unit tests. Maybe even do <a href=\"https://en.wikipedia.org/wiki/Test-driven_development\" rel=\"nofollow noreferrer\">TDD</a> where you develop the tests first and then write code to pass those tests.</p>\n\n<hr>\n\n<p>You never clearly state a use case. You briefly mention video games but never make clear if this is intended for one (yours or video game developers in general).</p>\n\n<hr>\n\n<p>It would also be nice if you could create a functional calendar from the constructor instead of having to repeatedly call functions.</p>\n\n<hr>\n\n<blockquote>\n <p>[...]it feels very messy and insecure[...]</p>\n</blockquote>\n\n<p>This is a good summary of the code. </p>\n\n<p>Date related code, much like crypto, is <a href=\"https://www.youtube.com/watch?v=-5wpm-gesOY\" rel=\"nofollow noreferrer\">notoriously hard to get right</a>. Maybe you should take a look at existing solutions (like <em>Boost</em>) and see if you can modify them to suit your use case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T20:40:16.290", "Id": "221883", "ParentId": "221689", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T00:51:16.033", "Id": "221689", "Score": "4", "Tags": [ "c++", "object-oriented", "datetime" ], "Title": "Generic calendar which can hold Mayan, Babylonian, Fantasy, Gregorian calendars" }
221689
<p><strong>How is the logic, efficiency and can it be improved?</strong></p> <p>This is a snippet from my <code>.bashrc</code> file, I just wrote it.</p> <p>The code is supposed to do this:</p> <p>Backup my <code>.bash_history</code> file if it is 1000 lines or less from the defined size of <code>HISTSIZE=100000</code> and <code>HISTFILESIZE=100000</code> lines, then backup the file.</p> <ol> <li>Check if <code>.bash_history</code> is 99000 lines or more. </li> <li>Check if <code>~/.bash_history.old</code> exists if it doesn't use that filename.</li> <li>Increment <code>i</code> one digit larger than is already used by filenames.(filename-4.old)</li> <li>Check if there are more than 20 files already backed up and warn if it is.</li> <li>Set the new filename into a variable.</li> <li>Check if the last file with a digit in it's filename is older than the original.</li> <li><code>cp</code> the file to <code>new_name</code></li> </ol> <h2>Here is the code:</h2> <pre><code># Count the number of lines in `/.bash_history and check if it's equal or more than a thousand if (( $(wc -l &lt; ~/.bash_history) &gt;= 99000 )) then name=~/.bash_history # Here is the suffix of the new files and the ones I check for old=.old # -e FILE ==&gt; True if FILE exists. if [[ ! -e ~/.bash_history.old ]] then printf "%s\n" "##################################################" ".bash_history will be cleared soon, backing up....!" "##################################################" # Here I copy $name which is ~/.bash_history and create backup file cp $name ~/.bash_history.old else # i is the increment in the filenames to be checked and created i=0 # $name$old is ~/.bash_history.old if [[ -e $name$old ]] then # Here I count how many copies there are with digits in the filename while [[ -e "$name-$i$old" ]] do let i++ done fi # if there are 20 files already backed up then I need to archive them somewhere else if [[ "$i" -ge 20 ]] then printf "%s\n" "********************************************************" "You need to arhive your history files they are mounting up!!!" "**************************************************************" fi new_name=$name-$i$old minus=$(( i - 1 )) if [ $name -nt "$name-$minus$old" ] then printf "%s\n" "##################################################" ".bash_history will be cleared soon, backing up....!" "##################################################" cp ~/.bash_history "$new_name" fi fi fi </code></pre> <p>This is the result from <code>shellcheck.net</code>:</p> <pre><code>Line 16: let i++ ^-- SC2219: Instead of 'let expr', prefer (( expr )) . </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T06:50:08.657", "Id": "428812", "Score": "0", "body": "This question is off-topic because you don't know whether it works. We are happy to review working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T06:51:18.953", "Id": "428813", "Score": "0", "body": "@dfhwze \"how well it works\" != \"whether it works\". \"The code is supposed to do this\" is debatable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T06:53:34.460", "Id": "428814", "Score": "1", "body": "@l0b0 \"Does my code work and can it be improved?\" and \"The code is supposed to do this:\" tend to make me think \"how well it works\" is out of the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:01:25.950", "Id": "428815", "Score": "2", "body": "That's probably something OP can help us with…?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T23:04:11.753", "Id": "429304", "Score": "0", "body": "@Heslacher I cleaned the question and added comments to the code....... Is it any better like this then or what?" } ]
[ { "body": "<p>First, <code>logrotate</code> is a tool built to do exactly this sort of thing. I would recommend using that to achieve the effectively the same extremely reliably and with lots of configuration options. That said, some suggestions on the code as written:</p>\n\n<ul>\n<li>ShellCheck is great; I would recommend following its recommendation to use <code>(( i++ ))</code>.</li>\n<li><code>wc -l</code> counts the number of <em>lines,</em> not bytes or kilobytes, which seems to be what you want.</li>\n<li><code>old</code>, <code>minus</code> and <code>i</code> are not helpful names; I have to read and understand all the code in the context in order to understand what they mean.</li>\n<li>It looks like you only ever replace the <em>last</em> of the 20 files once you have 20 backups.</li>\n<li>You have five instances of <code>~/.bash_history</code>, even though one of them is the value of a variable. I would pull that variable out and reuse it everywhere.</li>\n<li><a href=\"https://mywiki.wooledge.org/Quotes\" rel=\"nofollow noreferrer\">Use More Quotes™</a> - it's good for you and the code.</li>\n<li>Rather than a special unnumbered backup file (~/.bash_history.old), why not just start numbering the backups immediately? That way you can get rid of at least two checks for whether that file exists (<code>[[ ! -e ~/.bash_history.old ]]</code> and its inverse, <code>[[ -e $name$old ]]</code>).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T06:45:24.780", "Id": "221701", "ParentId": "221692", "Score": "3" } } ]
{ "AcceptedAnswerId": "221701", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T01:21:16.923", "Id": "221692", "Score": "1", "Tags": [ "beginner", "bash", "linux", "sh", "posix" ], "Title": "Bash Code to backup the history file in Linux" }
221692
<p>I'm making my <code>WebApi</code> project.</p> <p>My logic is, the controller didn't see data. It only triggers a service that returns objects to it. My simple method from <code>TaskService</code> looks like this:</p> <pre><code>public Task TakeTaskByUser(int taskId, string userId) { var task = this.GetItem(taskId); if (task != null) { if (task.ApplicationUserId != null) { throw new TaskTakenByAnotherUserException(); } task.ApplicationUserId = userId; task.StartTime = DateTime.Now; this.context.Entry(task).State = EntityState.Modified; this.context.SaveChanges(); return task; } return null; } </code></pre> <p>As you can see, in this method I try to find <code>Task</code> and attach Foreign Key to <code>User</code> by his <code>UserId</code>. If <code>Task</code> is already taken by another user, I throw a custom exception.</p> <p>In my controller, <code>Action</code> looks like this:</p> <pre><code>[HttpPut("{taskId}/{userId}")] [Authorize(Roles = "Developer, Manager")] public IActionResult TakeTaskByUser([FromRoute] int taskId, [FromRoute] string userId) { try { var task = this.taskService.TakeTaskByUser(taskId, userId.ToString()); if (task != null) { return this.Ok(task); } return this.NotFound(); } catch (TaskTakenByAnotherUserException) { return this.ValidationProblem(); } } </code></pre> <p>Is using a <code>try-catch</code> block in a controller good practice? Is using any exceptions in <code>WebApi</code> good, or I should use the method posted in <a href="https://www.exceptionnotfound.net/the-asp-net-web-api-exception-handling-pipeline-a-guided-tour/" rel="nofollow noreferrer">this article</a> (I like <strong>Level 1</strong>, seems easy and fun)? </p> <p>How do I deal with errors that <strong>I know</strong> that can appear when someone sends a request?</p>
[]
[ { "body": "<p>Exceptions are pretty costly so as a general rule of thumb <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions\" rel=\"nofollow noreferrer\">they should be avoided</a>. Especially when we talk about REST endpoint where response time is crucial.</p>\n\n<p>Also, to my taste you're messing up <a href=\"https://en.wikipedia.org/wiki/Command%E2%80%93query_separation\" rel=\"nofollow noreferrer\">command-query separation principle</a> in your code. I would have rewritten it roughly like this</p>\n\n<pre><code>[HttpPut(\"{taskId}/{userId}\")]\n[Authorize(Roles = \"Developer, Manager\")]\npublic IActionResult TakeTaskByUser([FromRoute] int taskId, [FromRoute] string userId)\n{\n var task = this.taskService.GetTask(taskId);\n if (task == null)\n return this.NotFound();\n var taskValidationResult = this.taskValidator.Validate(task);\n if (!taskValidationResult.IsSuccess)\n {\n //handle validation failure\n }\n\n task = this.taskService.TakeTaskByUser(task, userId);\n\n return this.Ok(task);\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T10:21:17.467", "Id": "428853", "Score": "0", "body": "I like that method to avoid exceptions. I will try it, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:59:59.603", "Id": "428873", "Score": "0", "body": "@Bohdan Stupak how would you handle validation failures? Ignore silently, wrap as some kind of response or perhaps throw an exception ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T12:51:31.257", "Id": "428879", "Score": "0", "body": "I would return some kind of response to be consistent with `return this.NotFound()` couple lines above. I've omitted the code because the mapping of validation result to response code might be verbose and irrelevant for the case." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T08:36:45.187", "Id": "221708", "ParentId": "221697", "Score": "3" } } ]
{ "AcceptedAnswerId": "221708", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T06:13:54.230", "Id": "221697", "Score": "2", "Tags": [ "c#", "error-handling", "asp.net-web-api" ], "Title": "Exception, errors handling, best practice in WebApi Core" }
221697
<p>We use the architecture shown in the code below to initialize the DB context for our MVC 5 project using entity framework 6</p> <p>We have the following questions related to it:</p> <ol> <li><p>Is it safe to initialize the Context in the constructor and use it throughout the class?</p></li> <li><p>What are the disadvantages of the given approach?</p></li> </ol> <p>Constructor:</p> <pre><code>public class HomeController : Controller { public DBEntities Context { get; set; } public HomeController() { Context = new DBEntities(); } ... } </code></pre> <p>We have a single point of entry to the controller using the <code>Perform</code> method <em>(This method is invoked from the client using ajax)</em>:</p> <pre><code>[HttpPost] public async Task&lt;ContentResult&gt; Perform(string operation, string entity, FormCollection form = null) { var json = string.Empty; var returnTuple = new Tuple&lt;string, int, string&gt;(string.Empty, (int)HttpStatusCode.InternalServerError, "Default return value"); switch (operation) { case "GET": switch (entity) { case ("ALLSCHOOLS"): returnTuple = await GetSchools(form); break; ... } break; case "POST": switch (entity) { case "SCHOOL": returnTuple = await SaveSchool(form); break; ... } break; } ... if (!string.IsNullOrEmpty(returnTuple.Item1)) { json = returnTuple.Item1; Response.StatusCode = (int)HttpStatusCode.OK; } else { Response.StatusCode = returnTuple.Item2; Response.StatusDescription = returnTuple.Item3; } return Content(json, "application/json"); } </code></pre> <p><code>GetSchools</code> method:</p> <pre><code>private async Task&lt;Tuple&lt;string, int, string&gt;&gt; GetSchools(FormCollection form) { var json = string.Empty; var statusCode = int.MinValue; var statusDescription = string.Empty; var academicYear = Convert.ToInt32(form["academicyear"]); var schoolsObj = await Context.schools.Where(s =&gt; s.AcademicYear == academicYear).ToListAsync(); //Context is initialized in constructor shown above json = JsonConvert.SerializeObject(new { EntityObject = schoolsObj, Message = string.Empty, Formatting.None }, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); return Tuple.Create(json, statusCode, statusDescription); } </code></pre> <p><code>SaveSchool</code> method:</p> <pre><code>private async Task&lt;Tuple&lt;string, int, string&gt;&gt; SaveSchool(FormCollection form) { var json = string.Empty; var statusCode = int.MinValue; var statusDescription = string.Empty; var schoolObj = new school(); var message = string.Empty; if (TryUpdateModel(schoolObj, form)) { Context.schools.Add(schoolObj); var saveChanges = await Context.SaveChangesAsync(); if (saveChanges == 0) { json = string.Empty; statusCode = (int)HttpStatusCode.InternalServerError; statusDescription = "Unable to save the data. Please try again later."; return Tuple.Create(json, statusCode, statusDescription); } else { json = JsonConvert.SerializeObject(new { EntityObject = schoolObj, Message = "Data saved successfully." }, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); } } else { message = ModelStateValidationErrors(); //ModelStateValidationErrors() returns all modelstate errors statusCode = (int)HttpStatusCode.BadRequest; statusDescription = "Please check the error(s) below and resubmit the form.&lt;br/&gt;" + message; } return Tuple.Create(json, statusCode, statusDescription); } </code></pre>
[]
[ { "body": "<p>It is safe to use the context the way you are using it. However, I don't think you will be able to write unit test. This isn't bad in itself. It does become an issue when your business logic is middle tier. Also why aren't you all using the rest standard instead of your perform method? Rest leaverages http to make your api more clear and interoperable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T17:05:33.213", "Id": "221869", "ParentId": "221700", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T06:29:56.493", "Id": "221700", "Score": "4", "Tags": [ "c#", "entity-framework", "asp.net-mvc" ], "Title": "Initializing entity framework context in constructor" }
221700
<p>I've been trying to solve this problem for some while and the solution I have come up with exceeds the lime limit by 1-3 ms and 2 out of 10 tests get a memory issue error. Why is that? This is the code for my solution:</p> <pre><code>#include &lt;fstream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; using namespace std; ifstream in("planificare.in"); ofstream out("planificare.out"); struct show { int start, finish, used = 0; }; bool end_time (show lhs, show rhs) { if (lhs.finish == rhs.finish) return lhs.start &lt; rhs.start; return lhs.finish &lt; rhs.finish; } int main() { int participants, tv_chan; vector&lt;show&gt; prog; in &gt;&gt; participants &gt;&gt; tv_chan; for (int i = 1; i &lt;= participants; i++) { show a; in &gt;&gt; a.start &gt;&gt; a.finish; prog.push_back(a); } sort(prog.begin(), prog.end(), end_time); int maxActivities = 0; int unused = 0; for (int i = 1; i &lt;= tv_chan; i++) { while (prog[unused].used) unused++; int lastFinish = prog[unused].finish; prog[unused].used = 1; maxActivities ++; for (int j = 0; j &lt; prog.size(); j++) { if (prog[j].start &gt;= lastFinish &amp;&amp; prog[j].used == 0) { maxActivities++; lastFinish = prog[j].finish; prog[j].used = 1; } } } out &lt;&lt; maxActivities; } </code></pre> <h2><a href="https://infoarena.ro/problema/planificare" rel="nofollow noreferrer">Planificare - InfoArena</a></h2> <blockquote> <p><em>Talent Day</em> is coming soon at the Blomkvist TV channel and the CEO Mike needs you to make the program grid. <span class="math-container">\$N\$</span> participants have enrolled to expose their talents, each communicating the amount of time it needs. Mike's TV Chain consists of <span class="math-container">\$K\$</span> stations, (Blomkvist 1, Blomkvist 2, ... Blomkvist K) that transmit independently of each other. Due to the fact that all <span class="math-container">\$K\$</span> stations are all just as popular as the other, the participants are indifferent to which they will appear. </p> <p>Knowing that at any given moment any station will broadcast a single show, determining the maximum number of shows that can be televised. </p> <h2>Input data</h2> <p>The input file <code>planificare.in</code> will contain on the first line <span class="math-container">\$2\$</span> natural numbers: <span class="math-container">\$N\$</span> and <span class="math-container">\$K\$</span>. On each of the following <span class="math-container">\$N\$</span> lines there will be 2 values, the starting time and the end time, representing the time interval during which the participant performs its activity. </p> <h2>Output data</h2> <p>The output file <code>planificare.out</code> will contain the number requested by Mike on the first line. </p> <h2>Restrictions and clarifications</h2> <p><span class="math-container">\$1 \le N \le 100,000\$</span></p> <p><span class="math-container">\$1 \le K \le 100,000\$</span></p> <p><span class="math-container">\$1 \le \text{start}_i \le \text{stop}_i \le 1,000,000,000\$</span></p> <h2>Time limit: 0.2 seconds</h2> <p>For <strong>30%</strong> of the tests, <span class="math-container">\$N\$</span> ≤ 2000 and for another <strong>10%</strong> of the tests, <span class="math-container">\$K\$</span> = 1. At each channel, a show can start at the same time that the previous one is over.</p> <h2>Example</h2> <p><strong><em><code>planificare.in</code></em></strong></p> <pre><code>2 1 1 4 4 8 </code></pre> <p><strong><em><code>planificare.out</code></em></strong></p> <pre><code>2 </code></pre> </blockquote>
[]
[ { "body": "<p>The problem is that you are erasing elements from <code>prog</code> and then without bounds checking access it with <code>prog[j]</code>. That is sure to fall over.</p>\n\n<p>Your <code>end_time</code> function is commonly known as <code>operator&lt;</code> So you should use the appropriate name.</p>\n\n<p>There is no comment on the significance of <code>1</code> and why a program should not be reordered when it starts at <code>1</code>. It seems that different programs with starting time <code>1</code> should still have an ordering.</p>\n\n<p>You are inconsistent in your loops. Once goes from <code>1</code> to <code>&lt;= participants</code> the other goes from <code>0</code> to <code>&lt; participants</code>. The latter is the commonly used one.</p>\n\n<p>The first loop seems to sort for start time? You can achieve the same if you create a proper <code>operator&lt;</code>.</p>\n\n<p><code>using namespace std;</code> is bad practice. There is no benefit to it other that you do not really know what is standard and what not, which is actually bad. Also it isprone to name clashes. Use what you need and not everything <code>C++</code> has in the box</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T19:06:28.180", "Id": "428927", "Score": "0", "body": "Thanks! This was helpful! However, I use `namespace std` for conveniency, as I don't need to remove it in this current program - no functions created by me interfere with `std` ones. Inconsistency in the loops comes from the fact that I was taught to go from `1` to `<= limit` and that's what I've used for 3-4 years since I'm into programming and changing that habit can be hard and useless, if the loop I'm used to works fine. When it doesn't, I know I can go from `0` to `< limit`. One question remains unanswered, however. Why the *time limit exceeded error* ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T19:07:19.663", "Id": "428928", "Score": "0", "body": "Also, the first loop takes the activities that start at moment `1` and puts them in the first positions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T19:30:14.850", "Id": "428935", "Score": "0", "body": "And I used the `bool end_time` function for conveniece, again, as I don't need to overload an operator necesarily." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T07:35:47.700", "Id": "428985", "Score": "1", "body": "@antoniu200 Unfortunately you are factually wrong. First, there is no `operator<` defined. Until spaceship comes you have to write them manually. Second, you are sorting the array twice with respect to different proerties of your struct. You can sort it just once by using a better comparison function. Third there is no convinience won using `end_time`. `operator<` is not really longer and you wouldnt have to pass it to std::sort. Finally, `using namespace std;` is always bad. For such a tiny example fine, but in bigger project it will bite you. Why learn bad stuff?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T15:11:01.070", "Id": "221726", "ParentId": "221702", "Score": "5" } }, { "body": "<p>After consulting with a friend, I ended up with this code:</p>\n\n<pre><code>#include &lt;fstream&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;set&gt;\n\nusing namespace std;\n\nifstream in(\"planificare.in\");\nofstream out(\"planificare.out\");\n\nint main() {\n int participants, tv_chan;\n vector&lt;pair&lt;int, int&gt; &gt; prog;\n in &gt;&gt; participants &gt;&gt; tv_chan;\n for (int i = 1; i &lt;= participants; i++) {\n int s, f;\n in &gt;&gt; s &gt;&gt; f;\n prog.push_back(make_pair(f, s));\n }\n\n sort(prog.begin(), prog.end());\n\n int maxActivities = 0;\n multiset&lt;int&gt; actFinish;\n for (int i = 1; i &lt;= tv_chan; i++) {\n actFinish.insert(0);\n }\n\n for (int i = 0; i &lt; participants; i++) {\n\n multiset&lt;int&gt;::iterator it = actFinish.lower_bound(prog[i].second);\n if (it == actFinish.end()) it--;\n if (*it &gt; prog[i].second &amp;&amp; it != actFinish.begin()) it--;\n\n if (*it &lt;= prog[i].second) {\n maxActivities++;\n actFinish.erase(it);\n actFinish.insert(prog[i].first);\n }\n }\n out &lt;&lt; maxActivities;\n}\n</code></pre>\n\n<p><code>Multiset</code> is for storing more of the same elements, <code>lower_bound</code> returns the <code>iterator</code> to the first element in my <code>multiset</code> that is <em>greater or equal</em> than the specified <code>begin_time</code>.</p>\n\n<p>The first <code>if</code> is to reduce the <code>iterator</code>, if it's more than the number of elements in my <code>multiset</code> and the second one is to reduce the <code>iterator</code>, if the number in the <code>mutliset</code> represented by <code>it</code> is greater than the specified <code>begin_time</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T17:45:07.380", "Id": "222538", "ParentId": "221702", "Score": "1" } } ]
{ "AcceptedAnswerId": "222538", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:01:47.400", "Id": "221702", "Score": "6", "Tags": [ "c++", "performance", "programming-challenge", "time-limit-exceeded", "memory-optimization" ], "Title": "Program for activity selection exceeds time limit" }
221702
<p>This is a <a href="https://leetcode.com/problems/dungeon-game/" rel="noreferrer">Leetcode problem</a> -</p> <blockquote> <p><em>The demons had captured the princess (<strong>P</strong>) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (<strong>K</strong>) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess.</em></p> <p><em>The knight has an initial health point represented by a positive integer. If at any point his health point drops to <code>0</code> or below, he dies immediately.</em></p> <p><em>Some of the rooms are guarded by demons, so the knight loses health (<strong>negative</strong> integers) upon entering these rooms; other rooms are either empty (<code>0</code>'s) or contain magic orbs that increase the knight's health (<strong>positive</strong> integers).</em></p> <p><em>In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.</em></p> <p><strong><em>Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.</em></strong></p> <p><em>For example, given the dungeon below, the initial health of the knight must be at least <strong>7</strong> if he follows the optimal path - <code>RIGHT -&gt; RIGHT -&gt; DOWN -&gt; DOWN</code>.</em></p> <p><a href="https://i.stack.imgur.com/ceUqb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ceUqb.png" alt="Leetcode"></a></p> <p><strong><em>Note -</em></strong></p> <ul> <li><em>The knight's health has no upper bound.</em></li> <li><em>Any room can contain threats or power-ups, even the first room the knight enters and the bottom-right room where the princess is imprisoned.</em></li> </ul> </blockquote> <p>Here is my solution to this challenge -</p> <pre><code># Uses dynamic programming def calculate_minimum_HP(dungeon): """ :type dungeon: List[List[int]] :rtype: int """ if not dungeon or not dungeon[0]: return 0 row, col = len(dungeon), len(dungeon[0]) dp = [[0] * col for _ in range(row)] dp[-1][-1] = max(1, 1 - dungeon[-1][-1]) for i in range(row - 2, -1, -1): dp[i][-1] = max(1, dp[i+1][-1] - dungeon[i][-1]) for j in range(col - 2, -1, -1): dp[-1][j] = max(1, dp[-1][j + 1] - dungeon[-1][j]) for i in range(row - 2, -1, -1): for j in range(col - 2, -1, -1): dp[i][j] = min(max(1, dp[i][j + 1] - dungeon[i][j]), max(1, dp[i + 1][j] - dungeon[i][j])) return dp[0][0] </code></pre> <p>Here is my Leetcode result -</p> <blockquote> <p><a href="https://i.stack.imgur.com/hXADm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hXADm.png" alt="Leetcode"></a></p> </blockquote> <p>So, I would like to know whether I could make my program faster and more efficient.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:16:32.123", "Id": "428882", "Score": "0", "body": "Leetcode timings are weird. I'll submit the exact same source code twice and go from faster than 10% to 90%. I wouldn't be too concerned with the timing. Is there anything stopping you from reusing the given list for memoization? In practice this would be a bad idea but for leetcode it would help" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:19:45.020", "Id": "428883", "Score": "0", "body": "@MitchelPaulin - Well, if the timing was really my concern, then what would be a good (and reliable) way of timing my program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:20:50.803", "Id": "428884", "Score": "0", "body": "There is no good way to time a program. Ideally you would run it on a clean OS with no other processes but this isn't realistic (hardware differences, dameons, what compiler flags you're using all change things). That is why we have big-Oh because in practice timing is unreliable" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:22:48.570", "Id": "428885", "Score": "0", "body": "@MitchelPaulin - So which methods of timing would you suggest for my program? What about Python's `timeit` function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:23:44.120", "Id": "428887", "Score": "0", "body": "I think you're missing my point, system time is an unreliable metric and should not be used for the \"goodness\" of a leetcode solution. If you want to time it an python library would be fine" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:25:51.340", "Id": "428888", "Score": "0", "body": "@MitchelPaulin - Oh.. well then I would just focus on performance and not time... Thanks for pointing this out! I've learned something new." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:58:29.600", "Id": "428891", "Score": "0", "body": "The cProfile library says use \"`timeit` for reasonably accurate results\". @MitchelPaulin is being a bit of a pessimistic pedant. The problem leetcode has is the service may be in high demand and so because other users are running code too, you get a worse score. I find plotting a graph to show trends to be better than going off absolute values - \"50ms\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T14:00:46.447", "Id": "428892", "Score": "0", "body": "@Peilonrayz - I see. Maybe you could suggest how I could plot a graph for my program?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T14:06:48.193", "Id": "428894", "Score": "0", "body": "@Peilonrayz I don't see how I am being pessimistic, pedant maybe. Regardless I have no doubts that timeit is a wonderfully accurate tool for measuring system time. My point was using system time as your metric for judging how good your leetcode solution is is not a good idea" } ]
[ { "body": "<h2>Potential Drawbacks of Results</h2>\n\n<p>As highlighted by <a href=\"https://codereview.stackexchange.com/users/172231/mitchel-paulin\">@Mitchel Paulin</a> LeetCode's performance test aren't reliable. I wrote my own answer and got a range of timings from 44ms in >96.53% bracket, but the same code got 56ms in the >46.94% bracket. This means it's also testing the performance of other things whilst testing my code.</p>\n\n<p>This can happen on your machine too. If you're executing a high performance operation whilst trying to time your code your results are going to be useless. But this doesn't mean that you have to have a 'performance testing machine' with nothing running on it to get fairly accurate results. Currently with two web browsers with ~950 tabs open, an IDE, two different notepad software, Spotify and an email client on Windows. I normally get accurate results.</p>\n\n<p>There are times when you see abnormal results in the graphs. I've noticed that sometimes when Spotify changes song you can see additional error bars. But these can just be ignored. The occasional time the entire graph is just useless; but these are rare, easily identifiable and just requires running the timers again.</p>\n\n<h2>How to time performance</h2>\n\n<p>The simplest way is to just use <code>timeit</code>, however it's hard to see trends with this. Instead I created and use <a href=\"https://pypi.org/project/graphtimer/\" rel=\"noreferrer\"><code>graphtimer</code></a> to create graphs. The benefit to graphs is they're visual and easier to understand then a bunch of numbers.</p>\n\n<p>Normally programming challenges give you a couple of integers to test against. So setting up timers for, say, a prime sieve is easier than what we have here. And so before we start checking the performance of your code we need to create a function that converts a single number to the arguments we want. I'll provide the function I used to do this. As for this it's fairly complex. I set the entire size of the dungeon to the passed size, and then randomly created the dungeon from this.</p>\n\n<p>After this when testing you need to test each change one at a time. This is because you may make two changes where one of the changes improves performance, but the other reduces performance. This can lead to you not getting maximum performance as you've thrown away an idea that improves performance.</p>\n\n<p>I don't like the way you're building <code>range</code>. And so have some ideas to change it:</p>\n\n<ol>\n<li>Change to use <code>reversed(range(row -1))</code>.</li>\n<li>Near the beginning of the function create a variable that holds the rages.</li>\n<li>Same as (2) but cast the <code>range</code> to a <code>list</code>.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/XpV7f.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/XpV7f.png\" alt=\"enter image description here\"></a></p>\n\n<p>This shows:</p>\n\n<ul>\n<li>Precomputing the range and not casting is the fastest.</li>\n<li>Using <code>reverse</code> is slower than your code.</li>\n<li>Precomputing the range and casting is slower for less than three items, but then becomes faster.</li>\n</ul>\n\n<h2>Code Review</h2>\n\n<ol>\n<li>Change mutations to be in-place. Don't make <code>dp</code>.</li>\n<li>Remove the guard statement.</li>\n</ol>\n\n\n\n<ul>\n<li>In my solution I used <code>min</code> rather than <code>max</code> causing my final line to be slower. So don't swap these.</li>\n<li>Change formatting of your <code>min</code>, and your list indexing so it's easier to read them.</li>\n</ul>\n\n<p>All this gets:</p>\n\n<pre><code>def solution_justin_no_guard(dungeon):\n dungeon[-1][-1] = max(1, 1 - dungeon[-1][-1])\n\n row, col = len(dungeon), len(dungeon[0])\n rows = range(row - 2, -1, -1)\n cols = range(col - 2, -1, -1)\n\n for i in rows:\n dungeon[i][-1] = max(1, dungeon[i + 1][-1] - dungeon[i][-1])\n\n for j in cols:\n dungeon[-1][j] = max(1, dungeon[-1][j + 1] - dungeon[-1][j])\n\n for i in rows:\n for j in cols:\n dungeon[i][j] = min(\n max(1, dungeon[i][j + 1] - dungeon[i][j]),\n max(1, dungeon[i + 1][j] - dungeon[i][j])\n )\n\n return dungeon[0][0]\n</code></pre>\n\n<h2>Graphs</h2>\n\n<p><a href=\"https://i.stack.imgur.com/3hPub.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3hPub.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/WwOD1.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/WwOD1.png\" alt=\"enter image description here\"></a></p>\n\n<p>You need to install numpy, matplotlib and graphtimer from pypi to be able to run the following. Produces the above three graphs.</p>\n\n<pre><code>import random\nimport copy\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom graphtimer import Plotter, MultiTimer\n\n\ndef solution_justin(dungeon):\n if not dungeon or not dungeon[0]:\n return 0\n row, col = len(dungeon), len(dungeon[0])\n dp = [[0] * col for _ in range(row)]\n dp[-1][-1] = max(1, 1 - dungeon[-1][-1])\n\n for i in range(row - 2, -1, -1):\n dp[i][-1] = max(1, dp[i+1][-1] - dungeon[i][-1])\n\n for j in range(col - 2, -1, -1):\n dp[-1][j] = max(1, dp[-1][j + 1] - dungeon[-1][j])\n\n for i in range(row - 2, -1, -1):\n for j in range(col - 2, -1, -1):\n dp[i][j] = min(max(1, dp[i][j + 1] - dungeon[i][j]), max(1, dp[i + 1][j] - dungeon[i][j]))\n\n return dp[0][0]\n\n\ndef solution_justin_reverse(dungeon):\n if not dungeon or not dungeon[0]:\n return 0\n row, col = len(dungeon), len(dungeon[0])\n dp = [[0] * col for _ in range(row)]\n dp[-1][-1] = max(1, 1 - dungeon[-1][-1])\n\n for i in reversed(range(row - 1)):\n dp[i][-1] = max(1, dp[i+1][-1] - dungeon[i][-1])\n\n for j in reversed(range(col - 1)):\n dp[-1][j] = max(1, dp[-1][j + 1] - dungeon[-1][j])\n\n for i in reversed(range(row - 1)):\n for j in reversed(range(col - 1)):\n dp[i][j] = min(max(1, dp[i][j + 1] - dungeon[i][j]), max(1, dp[i + 1][j] - dungeon[i][j]))\n\n return dp[0][0]\n\n\ndef solution_justin_pre_computed(dungeon):\n if not dungeon or not dungeon[0]:\n return 0\n row, col = len(dungeon), len(dungeon[0])\n dp = [[0] * col for _ in range(row)]\n dp[-1][-1] = max(1, 1 - dungeon[-1][-1])\n\n rows = range(row - 2, -1, -1)\n cols = range(col - 2, -1, -1)\n\n for i in rows:\n dp[i][-1] = max(1, dp[i+1][-1] - dungeon[i][-1])\n\n for j in cols:\n dp[-1][j] = max(1, dp[-1][j + 1] - dungeon[-1][j])\n\n for i in rows:\n for j in cols:\n dp[i][j] = min(max(1, dp[i][j + 1] - dungeon[i][j]), max(1, dp[i + 1][j] - dungeon[i][j]))\n\n return dp[0][0]\n\n\ndef solution_justin_pre_computed_list(dungeon):\n if not dungeon or not dungeon[0]:\n return 0\n row, col = len(dungeon), len(dungeon[0])\n dp = [[0] * col for _ in range(row)]\n dp[-1][-1] = max(1, 1 - dungeon[-1][-1])\n\n rows = list(range(row - 2, -1, -1))\n cols = list(range(col - 2, -1, -1))\n\n for i in rows:\n dp[i][-1] = max(1, dp[i+1][-1] - dungeon[i][-1])\n\n for j in cols:\n dp[-1][j] = max(1, dp[-1][j + 1] - dungeon[-1][j])\n\n for i in rows:\n for j in cols:\n dp[i][j] = min(max(1, dp[i][j + 1] - dungeon[i][j]), max(1, dp[i + 1][j] - dungeon[i][j]))\n\n return dp[0][0]\n\n\ndef solution_justin_inplace(dungeon):\n if not dungeon or not dungeon[0]:\n return 0\n row, col = len(dungeon), len(dungeon[0])\n dungeon[-1][-1] = max(1, 1 - dungeon[-1][-1])\n\n rows = range(row - 2, -1, -1)\n cols = range(col - 2, -1, -1)\n\n for i in rows:\n dungeon[i][-1] = max(1, dungeon[i + 1][-1] - dungeon[i][-1])\n\n for j in cols:\n dungeon[-1][j] = max(1, dungeon[-1][j + 1] - dungeon[-1][j])\n\n for i in rows:\n for j in cols:\n dungeon[i][j] = min(\n max(1, dungeon[i][j + 1] - dungeon[i][j]),\n max(1, dungeon[i + 1][j] - dungeon[i][j])\n )\n\n return dungeon[0][0]\n\n\ndef solution_justin_no_guard(dungeon):\n dungeon[-1][-1] = max(1, 1 - dungeon[-1][-1])\n\n row, col = len(dungeon), len(dungeon[0])\n rows = range(row - 2, -1, -1)\n cols = range(col - 2, -1, -1)\n\n for i in rows:\n dungeon[i][-1] = max(1, dungeon[i + 1][-1] - dungeon[i][-1])\n\n for j in cols:\n dungeon[-1][j] = max(1, dungeon[-1][j + 1] - dungeon[-1][j])\n\n for i in rows:\n for j in cols:\n dungeon[i][j] = min(\n max(1, dungeon[i][j + 1] - dungeon[i][j]),\n max(1, dungeon[i + 1][j] - dungeon[i][j])\n )\n\n return dungeon[0][0]\n\n\ndef solution_peilonrayz(dungeon):\n dungeon[-1][-1] = min(dungeon[-1][-1], 0)\n row = len(dungeon)\n col = len(dungeon[0])\n rows = range(row - 2, -1, -1)\n cols = range(col - 2, -1, -1)\n\n for i in rows:\n dungeon[i][-1] = min(dungeon[i][-1] + dungeon[i + 1][-1], 0)\n\n for i in cols:\n dungeon[-1][i] = min(dungeon[-1][i] + dungeon[-1][i + 1], 0)\n\n for y in rows:\n for x in cols:\n dungeon[y][x] = max(\n min(dungeon[y][x] + dungeon[y + 1][x], 0),\n min(dungeon[y][x] + dungeon[y][x + 1], 0)\n )\n\n return abs(min(dungeon[0][0], 0)) + 1\n\n\nmemoize = {}\n\n\ndef create_arg(size, *, _i):\n size = int(size)\n key = size, _i\n if key in memoize:\n return copy.deepcopy(memoize[key])\n divisors = [\n (i, size // i)\n for i in range(1, int(size ** 0.5) + 1)\n if size % i == 0\n ]\n if len(divisors) &gt; 1:\n divisors = divisors[1:]\n y_size, x_size = random.choice(divisors)\n output = [[None] * x_size for _ in range(y_size)]\n for i in range(size):\n y, x = divmod(i, x_size)\n output[y][x] = random.randint(-100, 100)\n memoize[key] = output\n return output\n\n\ndef main():\n fig, axs = plt.subplots()\n axs.set_yscale('log')\n axs.set_xscale('log')\n (\n Plotter(MultiTimer([\n solution_justin,\n solution_justin_reverse,\n solution_justin_pre_computed,\n solution_justin_pre_computed_list,\n ]))\n .repeat(10, 1, np.logspace(0, 2), args_conv=create_arg)\n .min()\n .plot(axs, title='Comparison of Loop Changes', x_label='dungeon size')\n )\n fig.show()\n\n fig, axs = plt.subplots()\n axs.set_yscale('log')\n axs.set_xscale('log')\n (\n Plotter(MultiTimer([\n solution_justin_pre_computed,\n solution_justin_inplace,\n solution_justin_no_guard,\n solution_peilonrayz,\n ]))\n .repeat(10, 1, np.logspace(0, 2), args_conv=create_arg)\n .min()\n .plot(axs, title='Code Review Changes', x_label='dungeon size')\n )\n fig.show()\n\n fig, axs = plt.subplots()\n axs.set_yscale('log')\n axs.set_xscale('log')\n (\n Plotter(MultiTimer([\n solution_justin,\n solution_justin_no_guard,\n ]))\n .repeat(10, 1, np.logspace(0, 2), args_conv=create_arg)\n .min()\n .plot(axs, title='Comparison of Original and Final', x_label='dungeon size')\n )\n fig.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<h2>Final notes</h2>\n\n<p>The graph is a zig-zaged line. This is because the program is faster when there's only one row or column. And it currently only allows this case when the number is prime. It looks like if a list has at least two dimensions then the performance decreases dramatically to the upper line, but doesn't change much between a 20x2 and a 5x8. I can't prove this, as the graph is only 2D not 3D, but the lack of error bars suggest it. If <code>create_arg</code> is changed to always create a 1xn list once then you get the following graph.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Kmswi.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Kmswi.png\" alt=\"enter image description here\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T19:16:16.713", "Id": "428932", "Score": "1", "body": "Very nice graphs, how did you create them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T19:18:10.397", "Id": "428933", "Score": "2", "body": "@yuri I provided the entire source code under the section \"Graphs\" and before \"Final notes\", you'll need to install numpy, matplotlib and graphtimer from PyPI. It doesn't produce the final graph, getting that requires changing `create_arg`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T19:19:57.080", "Id": "428934", "Score": "0", "body": "Sorry didn't read that part, was too distracted by the shiny graphs." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T17:47:27.783", "Id": "221732", "ParentId": "221704", "Score": "5" } } ]
{ "AcceptedAnswerId": "221732", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T07:47:27.043", "Id": "221704", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "dynamic-programming" ], "Title": "The Dungeon game" }
221704
<p>I am preparing for an interview and came to know about this question: implement a vector class in C++. I thought of how I would write it an interview and included the code below. The things I know I did not cover already are: 1) No use of templates for different data types 2) No use of iterators for iterating. My point is I wanted to write a simple code and I want to know if that would be sufficient to crack the interview round or not? Can you please go through the below code and point out the things that I must cover from an interview perspective. Thanks.</p> <pre><code>class Vector{ int capacity; int sizet; int *arr; public: Vector():capacity(0),sizet(0),arr(new int){} Vector(int size):capacity(size),sizet(size),arr(new int[sizet]()){} Vector(const Vector &amp;v){ //copy ctor capacity = v.capacity; sizet = v.sizet; arr = new int[sizet]; for(int i=0;i&lt;sizet;i++) arr[i] = v.arr[i]; } int &amp;operator [](int index){ //overloading index[] operator return arr[index]; } Vector &amp;operator==(const Vector&amp; v){ //overloading assignment operator if(this != v){ capacity = v.capacity; sizet = v.sizet; arr = new int[sizet]; for(int i=0;i&lt;sizet;i++) arr[i] = v.arr[i]; } return *this; } void push_back(int elem){ if(sizet == capacity){ if(capacity ==0) capacity++; else capacity = 2*capacity; } arr[sizet++]=elem; } void pop_back(){ sizet--; } void insert(iterator it,int size=1,int val=0){ } int size(){ return sizet; } void resize(int n){ if(sizet &lt; n){ //if increasing the size for(int i=sizet;i&lt;n;i++) arr[sizet++]=0; } else //decreasing the size sizet = n; } int at(int index){ return arr[index]; } int front(){ return arr[0]; } int back(){ return arr[sizet]; } ~Vector(){ //dtor delete arr[]; } }; </code></pre> <p>Edit: Resolved the naming conflict as was suggested.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T08:33:22.140", "Id": "428832", "Score": "0", "body": "By tagging C++11, are you targeting C++11?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T08:36:11.527", "Id": "428833", "Score": "0", "body": "yes I must. Although, I cant figure out if there would be any change in my code if I use C++11 or C++ 14?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T08:38:36.827", "Id": "428834", "Score": "0", "body": "Your code doesn't even compile. Your `Vector::operator[]` return a `vector&`. Your `insert` is empty and uses an undefined type `iterator`. You have a data member and a member function sharing the same name `size`. Your destructor is `~vector` instead of `~Vector`. And there are a lot of compile errors left." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T08:40:09.157", "Id": "428837", "Score": "0", "body": "I am sorry, I did not state this in my statement. I did not compile the code.\nI only described like how I would write it in an interview like in a pen and paper. And needed a help to know what else should I cover or missed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T08:43:03.710", "Id": "428839", "Score": "5", "body": "Code Review reviews working code. Fix the errors, do some tests, and try your best to ensure that your code is working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T08:43:57.400", "Id": "428840", "Score": "0", "body": "thanks for pointing about the size and destructor name conflict. Like I said, my intention was to write it as in a pen and paper type code. So, that's why the naming conflict must have occur. I will keep that in mind." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T09:39:28.397", "Id": "428845", "Score": "0", "body": "The official vector specification also demands that `std::out_of_range` is thrown if you try to use `at(...)` with an index greater than the vector's size. I see nothing like this in your code. This breaks the promises given by using that name." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T11:03:12.190", "Id": "429013", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T13:33:09.247", "Id": "429038", "Score": "0", "body": "Also `unsigned int` is more appropriate than `int` for denoting size. If you're using int for size, you're wasting half of its capacity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T17:44:14.337", "Id": "429076", "Score": "0", "body": "@Vogel612, I wanted people to not repeat the already provided suggestions, that's why I updated the code in the post itself. But I get your concern.\nQuestion: When I update all the suggestions in my code, and I still like to have one review on that. Can I post the updated code in the answer section?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T17:45:46.490", "Id": "429077", "Score": "0", "body": "@MFCDev the case you are describing is suited to asking what we call a \"follow-up question\". So: no. An answer is not the place for a question :) You may want to link to your new question in this one to avoid users pointing out things you later fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T21:16:23.213", "Id": "429291", "Score": "0", "body": "Worth a read: https://lokiastari.com/blog/2016/02/27/vector/index.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-08T09:35:13.490", "Id": "429340", "Score": "0", "body": "@MartinYork WOW! That's a brilliant article. Thanks!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-08T12:53:43.140", "Id": "429349", "Score": "0", "body": "@MFCDev There was a set of 4 articles about vectors." } ]
[ { "body": "<ol>\n<li><p>You tagged <a href=\"/questions/tagged/c%2b%2b11\" class=\"post-tag\" title=\"show questions tagged &#39;c++11&#39;\" rel=\"tag\">c++11</a>, but your code does not look like C++11. You do not implement move construction and move assignment. You should implement them. Here's a sample implementation using the <a href=\"https://stackoverflow.com/q/3279543\">copy-and-swap idiom</a>.</p>\n\n<pre><code>friend void swap(Vector&amp; a, Vector&amp; b)\n{\n using std::swap;\n swap(a.capacity, b.capacity);\n swap(a.sizet, b.sizet);\n swap(a.arr, b.arr);\n}\n\nVector(Vector&amp;&amp; v)\n :Vector{}\n{\n swap(*this, v);\n}\n\nVector&amp; operator=(Vector v)\n{\n swap(*this, v);\n return *this;\n}\n</code></pre>\n\n<p>This way, you don't have to define a separate copy assignment operator.</p></li>\n<li><p>Your default constructor sets <code>arr</code> to <code>new int</code>. This makes no sense and cannot be handled by the destructor. You should set <code>arr</code> to <code>nullptr</code>.</p></li>\n<li><p>Use <code>++i</code>, not <code>i++</code>, in discarded-result expressions. See <a href=\"https://stackoverflow.com/a/484492\">Difference between <code>i++</code> and <code>++i</code> in a loop?</a>.</p></li>\n<li><p>Consider using standard algorithms instead of hand-crafted loops when plausible. For example:</p>\n\n<pre><code>for (int i = 0; i &lt; sizet; i++)\n arr[i] = v.arr[i];\n}\n</code></pre>\n\n<p>Can be replaced by</p>\n\n<pre><code>std::copy_n(v.arr, sizet, arr);\n</code></pre>\n\n<p>You will need to <code>#include &lt;algorithm&gt;</code> for this to work.</p></li>\n<li><p>Your copy constructor uses assignment instead of member initializer clauses. You should use member initializer clauses uniformly. Now your copy constructor should look like this:</p>\n\n<pre><code>Vector(const Vector&amp; v)\n :capacity{v.capacity},\n sizet{v.sizet},\n arr{new int[v.sizet]} // to avoid dependence on member declaration order\n{\n std::copy(v.arr, v.arr + sizet, arr);\n}\n</code></pre></li>\n<li><p>Where is the <code>const</code> overload for <code>operator[]</code>, <code>at</code>, <code>front</code>, and <code>back</code>?</p></li>\n<li><p>Your <code>push_back</code> is incorrect. It does not allocate any memory. You will get an out-of-range error when <code>capacity</code> exceeds the actual capacity. Same applies to <code>resize</code>.</p></li>\n<li><p><code>size()</code> should be <code>const</code>.</p></li>\n<li><p>Your <code>at</code> does the same job as <code>operator[]</code>. <code>at</code> should check for out-of-range errors and raise an exception if <code>index &gt;= sizet</code>.</p></li>\n<li><p><code>front</code> and <code>back</code> should return a reference instead of a value.</p></li>\n<li><p>The implementation of <code>back</code> is wrong. It should return <code>arr[sizet - 1]</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T09:49:32.543", "Id": "428848", "Score": "3", "body": "I highly doubt that 3. is still a major concern for modern compilers. At least in the example I checked on godbolt ([link](https://godbolt.org/z/BAzLxF)), the generated assembly is the same for pre- and post-increment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T09:50:53.293", "Id": "428849", "Score": "5", "body": "@AlexV \"This is mainly only a problem when the variable being incremented is a user defined type with an overridden ++ operator. For primitive types (int, etc) there's no performance difference. But, it's worth sticking to the pre-increment operator as a guideline unless the post-increment operator is definitely what's required.\" — Scott Langham" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T09:27:44.963", "Id": "221711", "ParentId": "221707", "Score": "13" } }, { "body": "<p>It's great that you provide a test program. Although it doesn't yet test very much, running it under Valgrind uncovers a few wild accesses:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>==17803== Invalid write of size 4\n==17803== at 0x109773: Vector::resize(int) (221707.cpp:68)\n==17803== by 0x10938A: main (221707.cpp:103)\n==17803== Address 0x4d74c94 is 0 bytes after a block of size 20 alloc'd\n==17803== at 0x483650F: operator new[](unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==17803== by 0x109508: Vector::Vector(int) (221707.cpp:11)\n==17803== by 0x1091FE: main (221707.cpp:92)\n==17803== \n==17803== Invalid read of size 4\n==17803== at 0x1093CE: main (221707.cpp:105)\n==17803== Address 0x4d74c98 is 4 bytes after a block of size 20 alloc'd\n==17803== at 0x483650F: operator new[](unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==17803== by 0x109508: Vector::Vector(int) (221707.cpp:11)\n==17803== by 0x1091FE: main (221707.cpp:92)\n==17803== \n==17803== Invalid read of size 4\n==17803== at 0x1097FD: Vector::at(int) const (221707.cpp:77)\n==17803== by 0x109406: main (221707.cpp:106)\n==17803== Address 0x4d74ca8 is 20 bytes after a block of size 20 alloc'd\n==17803== at 0x483650F: operator new[](unsigned long) (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==17803== by 0x109508: Vector::Vector(int) (221707.cpp:11)\n==17803== by 0x1091FE: main (221707.cpp:92)\n==17803== \n</code></pre>\n\n<p>One of the problems is that <code>resize()</code> doesn't allocate new capacity when necessary. In fact, there seems to be quite some confusion between size and capacity throughout the code; <em>size</em> should be the number of objects we're logically storing, and <em>capacity</em> is how many we <em>could</em> store before we need to re-allocate.</p>\n\n<p>When we do re-allocate, I would expect to use standard algorithms (<code>std::move()</code>) to copy the elements from old to new storage; there's no need to hand-code a loop.</p>\n\n<p>I'd advise against writing <code>using namespace</code> - that defeats the very benefits that namespaces were invented to give us.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T17:47:17.043", "Id": "428919", "Score": "0", "body": "Thanks. These are good suggestions too. I have not used move ctor or assignment operator ever before so I did not know it's usage.\nOne question: Do I need to have both move and copy constructor in the Vector class? As well as both move assignment and copy assignment operator?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T20:43:34.203", "Id": "428948", "Score": "0", "body": "It doesn't make much sense to have a defined assignment operator without the corresponding constructor - they are normally implemented as a pair. You may find it easiest to implement the move constructor and assignment operator using a `swap()` member - most decent tutorials will demonstrate that, so I won't elaborate further." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T10:41:06.240", "Id": "221715", "ParentId": "221707", "Score": "12" } } ]
{ "AcceptedAnswerId": "221711", "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T08:17:15.277", "Id": "221707", "Score": "9", "Tags": [ "c++", "c++11", "vectors" ], "Title": "Implement Own Vector Class in C++" }
221707
<p>I'm in a project that's currently using vue. I'm at the moment developing validations for the inputs and in a way to make them more flexible, my idea was to create an intermediate component "Group Component" where I set as a property the input I want to load. As such, validations are imported in the component.</p> <p>I've found difficulty understanding when the several inputs had passed the validations without errors in the "Page component", and to that problem I've figured out a solution, which I don't know if it's the ideal approach, since I'm using $ref to obtain the validations of the child components and on submission it validateds if all have passed. </p> <p>the package I'm using for validations is vuelidate.</p> <p>Is there a better approach?</p> <p>Validation in submitting the form on "Page component"</p> <pre><code> onSubmit() { setTimeout(() =&gt; { if (this.checkIfAllInputsFilled()) { console.log('yes'); } else { console.log('no'); } , 300) }, checkIfAllInputsFilled() { let validationsObj = { email: this.$refs.email.$v.$invalid, password: this.$refs.password.$v.$invalid }; return Object.keys(validationsObj).every((k) =&gt; !validationsObj[k]); } </code></pre> <p>All Files - code</p> <p>Page component</p> <pre><code>&lt;template&gt; &lt;div class="login"&gt; &lt;form class="login__form" @submit.prevent="onSubmit" novalidate&gt; &lt;base-input-group component="Input" labelClass="authentication" :labelValue="$t('global.email')" inputId="email" inputType="email" inputName="email" inputClass="input--default input--authentication" inputValue="" :contentErrors="[ { key: 'required', message: $t('errors.gerals.required') }, { key: 'email', message: $t('errors.gerals.invalid') } ]" @get-value="form.email = $event" ref="email" /&gt; &lt;div class="authentication__form__buttons display--flex"&gt; &lt;base-button type="submit" classAttribute="button--default button--background button--authentication" :text="$t('authentication.login')" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; // components const baseInputGroup = () =&gt; import( /* webpackChunkName: 'inputGroup' */ '../../../components/inputs/baseInputGroup'); const baseButton = () =&gt; import( /* webpackChunkName: 'baseButton' */ '../../../components/buttons/baseButton'); export default { components: { baseInputGroup: baseInputGroup, baseButton: baseButton }, data() { return { active: false, form: { email: '' } } }, methods: { onSubmit() { setTimeout(() =&gt; { if (this.checkIfAllInputsFilled()) { console.log('yes'); } else { console.log('no'); } }, 300) }, checkIfAllInputsFilled() { let validationsObj = { email: this.$refs.email.$v.$invalid }; return Object.keys(validationsObj).every((k) =&gt; !validationsObj[k]); } } } &lt;/script&gt; </code></pre> <p>Group component</p> <pre><code>&lt;template&gt; &lt;div class="field-group" :class="{'field--errors': $v.value.$error, 'field--success': !$v.value.$error}"&gt; &lt;label for="inputId" :class="`label label--${labelClass}`"&gt; {{ labelValue }}&lt;/label&gt; &lt;component :is="componentInput" :inputId="inputId" :inputType="inputType" :inputName="inputName" :inputClass="inputClass" :value="inputValue" :valid="$v.value" @input-value="value = $event" /&gt; &lt;component v-if="$v.value.$error" :is="componentErrors" :errorMessage="errorMessage" /&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { props: { component: String, labelClass: String, labelValue: String, inputId: String, inputType: String, inputName: String, inputClass: String, inputValue: String, contentErrors: Array }, data () { return { componentInput: null, componentErrors: null, value: '', validator: {}, errorMessage: '' } }, created() { import(`../../../validations/${this.inputName}.js`).then( validator =&gt; { this.validator = validator.default; }); this.loaderComponent() .then(() =&gt; { this.componentInput = () =&gt; this.loaderComponent(); }) }, methods: { fillMessageError() { this.contentErrors.map( error =&gt; { if (!this.$v.value[error.key]) this.errorMessage = error.message; }); } }, computed: { loaderComponent () { return () =&gt; import( /* webpackChunkName: 'input' */ `./childrens/base${this.component}`); }, loaderComponentErrors () { return () =&gt; import( /* webpackChunkName: 'errors' */ './../errors/baseError'); } }, validations () { return { value : { ...this.validator } } }, watch: { '$v.value.$error': { deep: true, // so it detects changes to properties only handler(newVal, oldVal) { if (newVal) { if (!this.componentErrors) { this.loaderComponentErrors() .then((component) =&gt; { this.componentErrors = () =&gt; this.loaderComponentErrors(); }); } this.fillMessageError(); } else { this.$emit('get-value', this.value) } } } } } &lt;/script&gt; </code></pre> <p>Input component</p> <pre><code>&lt;template&gt; &lt;input :id="inputId" :type="inputType" :name="inputName" :class="inputClass" :value="inputValue" @blur="action" @keyup.enter="action" &gt; &lt;/template&gt; &lt;script&gt; export default { props: { inputId: String, inputType: String, inputName: String, inputClass: String, inputValue: String, valid: Object, }, methods: { action($event) { this.$emit('input-value', $event.target.value); this.valid.$touch(); } } } &lt;/script&gt; <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-18T21:53:26.637", "Id": "430856", "Score": "0", "body": "Note to reviewers: This appears to also have been [cross posted on SO](https://stackoverflow.com/q/56564261/1575353), which may be a duplicate of [_Vuelidate: validate form with sub components_](https://stackoverflow.com/q/54344033/1575353)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T09:22:46.130", "Id": "221710", "Score": "4", "Tags": [ "javascript", "validation", "form", "vue.js" ], "Title": "Vuejs - input validation" }
221710
<p>How can I optimize this code of adapter's overriden method getItemCount() into simpler form?</p> <pre><code>@Override public int getItemCount() { return super.getItemCount() == 0 &amp;&amp; data != null ? 1 : super.getItemCount(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:23:50.517", "Id": "428863", "Score": "1", "body": "Could you provide some context? What is `data`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:26:40.603", "Id": "428864", "Score": "0", "body": "Also, what do you mean with 'simpler form'? You want to beatify or optimize performance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:27:52.973", "Id": "428865", "Score": "0", "body": "@dfzwze I want to beautify" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:46:17.920", "Id": "428869", "Score": "0", "body": "Beauty is in the eye of the beholder. It has nothing to do with code reviewing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:56:50.160", "Id": "428871", "Score": "0", "body": "@TorbenPutkonen I find the help center unclear about reviewing code layout. The reason I decided to answer this question anyway is because there is a potential performance optimization as well." } ]
[ { "body": "<p>Code Beautification is suggestive. This is how I would write your code. There is also a possible performance optimization by only calling <code>super.getItemCount()</code> once.</p>\n\n<ul>\n<li>be consistent with parentheses (I'm using a different rule for methods and conditions, but feel free to use your own preference as long as you are consistent)</li>\n<li>create one variable to store the item count</li>\n<li>get the item count you would like to return from the base class</li>\n<li>determine predicate from the perspective of either\n\n<ul>\n<li>(A) the edge case value of item count, when <code>itemCount == 0</code>; an inner condition is used to determine the new value</li>\n<li>(B) the combined condition that yields a different result <code>itemCount == 0 &amp;&amp; data != null</code></li>\n</ul></li>\n</ul>\n\n<p>snippet A</p>\n\n<pre><code>@Override\n public int getItemCount() {\n int itemCount = super.getItemCount();\n if (itemCount == 0) \n {\n itemCount = data != null ? 1 : 0;\n }\n return itemCount;\n }\n</code></pre>\n\n<p>snippet B </p>\n\n<pre><code>@Override\n public int getItemCount() {\n int itemCount = super.getItemCount();\n if (itemCount == 0 &amp;&amp; data != null) \n {\n itemCount = 1;\n }\n return itemCount;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T14:06:04.207", "Id": "428893", "Score": "0", "body": "Please don't just post code. Explain also the benefits of your chosen code layout. Now, the method naming suggests that `itemCount` clashes with super class member name. I would use `actualItemCount`, `adjustedItemCount` or better yet, some other form that describes the purpose of the overriding implementation (which we unfortunately don't know). I find the latter form better, as it groups the conditions that affect `itemCount` neatly into the same if-statement. The reader doesn't have to combine statements from multiple lines to figure out what happens." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T15:17:07.883", "Id": "428900", "Score": "0", "body": "@TorbenPutkonen (A) Fair enough, it was lacking some description (B) This is something we, unfortunately don't know because of the lack of information from the OP" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:38:15.560", "Id": "221718", "ParentId": "221712", "Score": "4" } } ]
{ "AcceptedAnswerId": "221718", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T09:51:42.313", "Id": "221712", "Score": "0", "Tags": [ "java", "performance", "android" ], "Title": "Optimize this code of adapter's overriden method getItemCount()" }
221712
<p>In Entity Framework Core we can have recursive entities. But we cannot do an "Include" for these recursives (can we?). So I wrote a <code>Get</code>-method that does it for me:</p> <p>First, this is my <code>RecursiveEntity&lt;T&gt;</code> base-class:</p> <pre><code>public class Entity : IEntity { [Key] public int Id { get; set; } } public abstract class RecursiveEntity&lt;TEntity&gt; : Entity, IRecursiveEntity&lt;TEntity&gt; where TEntity : RecursiveEntity&lt;TEntity&gt; { public virtual TEntity Parent { get; set; } public virtual ICollection&lt;TEntity&gt; Children { get; set; } } </code></pre> <p>And this is my <code>Repository</code>-base-class for recurisve entities:</p> <pre><code>public abstract class RecursiveRepository&lt;T, TDataContext&gt; where T : RecursiveEntity&lt;T&gt; where TDataContext : DbContext { protected IEnumerable&lt;T&gt; Get(Expression&lt;Func&lt;T, bool&gt;&gt; expression) { IQueryable&lt;T&gt; parents = DataContext.Set&lt;T&gt;() .Include(x =&gt; x.Children) .Where(w =&gt; w.Parent == null) .Where(expression); foreach (T entity in parents) { if (entity.Children != null &amp;&amp; entity.Children.Any()) entity.Children = _getChildren(entity, expression).ToList(); yield return entity; } } private IEnumerable&lt;T&gt; _getChildren(T parentEntity, Expression&lt;Func&lt;T, bool&gt;&gt; expression) { IQueryable&lt;T&gt; children = DataContext.Set&lt;T&gt;() .Include(x =&gt; x.Parent) .Where(w =&gt; w.Parent != null &amp;&amp; w.Parent.Id == parentEntity.Id) .Where(expression); foreach (T entity in children) { entity.Children = _getChildren(entity, expression).ToList(); yield return entity; } } } </code></pre> <p>Any suggestion what I can do better? Is it a good solution to do that many <code>DataContext&lt;Set&gt;</code>-accesses and assign them to the parent with <code>ToList()</code>?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T10:40:50.063", "Id": "428854", "Score": "1", "body": "Can there be cycles in this recursive entity? For instance, can my parent be my grandchild?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T10:42:57.453", "Id": "428855", "Score": "0", "body": "@dfhwze good point! regarding database, yes, it's possible. I should handle that in my backend - no, I dont want circular references." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T10:51:33.310", "Id": "428856", "Score": "1", "body": "I don't know whether EF supports dynamic hierarchical loading. it didn't in the past. However, one way to try and solve this it is to load the objects as a flattened list and then build the hierarchy in memory." } ]
[ { "body": "<p>If you remove <code>virtual</code> from <code>Children</code> it'll work with <code>Include(e =&gt; e.Children)</code>:</p>\n\n<pre><code> public abstract class RecursiveEntity&lt;TEntity&gt;\n : Entity, IRecursiveEntity&lt;TEntity&gt;\n where TEntity : RecursiveEntity&lt;TEntity&gt;\n {\n public virtual TEntity Parent { get; set; }\n public ICollection&lt;TEntity&gt; Children { get; set; }\n }\n</code></pre>\n\n<p>The meaning with <code>virtual</code> is to provide lazy loading. If you can't live with that, you'll have to do it manually, as you do.</p>\n\n<hr>\n\n<p>Alternatively I think, you can add \"MultipleActiveResultSets=True\" to your connection string.</p>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p>I seems that EF 6 and EFCore work differently when it comes to <code>Include</code>?</p>\n\n<p>EFCore has the <code>Include()</code> and <code>ThenInclude</code> pattern but that is rather useless for recursive initialization.</p>\n\n<p>When loading manually have you then experimented with the abilities to load navigation properties on each object as in:</p>\n\n<pre><code>public IEnumerable&lt;TEntity&gt; Get&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter) where TEntity: RecursiveEntity&lt;TEntity&gt;\n{\n foreach (TEntity entity in Set&lt;TEntity&gt;().Where(e =&gt; e.Parent == null).Where(filter))\n {\n GetChildren(entity, filter);\n yield return entity;\n }\n}\n\nprivate void GetChildren&lt;TEnity&gt;(TEnity parent, Expression&lt;Func&lt;TEnity, bool&gt;&gt; childFilter) where TEnity : RecursiveEntity&lt;TEnity&gt;\n{\n Entry(parent).Collection(e =&gt; e.Children).Query().Where(childFilter).Load();\n // Entry(parent).Reference(e =&gt; e.Parent).Load(); // I think this shouldn't be necessary because loading the children will load the parent on them\n\n if (parent.Children != null)\n {\n foreach (TEnity child in parent.Children)\n {\n GetChildren(child, childFilter);\n }\n }\n}\n</code></pre>\n\n<p>It should produce the same result as yours, but is maybe a little clearer and in line with the EF concept.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T12:34:42.737", "Id": "428875", "Score": "0", "body": "would be nice - I tried, but in my case, it only loads the direct children. not the children of the children.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:44:20.580", "Id": "428889", "Score": "0", "body": "@MatthiasBurger: Strange it works in EF 6" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:50:45.137", "Id": "428890", "Score": "0", "body": "I heared that in EF core, the \"virtual\" is not used anymore like in EF 6. And imho EF Core is not a \"follower\" of EF 6. Maybe this is not implemented. But I'll test it again later" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T06:30:43.657", "Id": "528331", "Score": "0", "body": "So the reverse (child to parents) should be `Db.Entry(child).Reference(c=>c.Parent).Query().Where(filter).Load();` ????" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T12:14:47.210", "Id": "221720", "ParentId": "221714", "Score": "6" } } ]
{ "AcceptedAnswerId": "221720", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T10:28:48.947", "Id": "221714", "Score": "4", "Tags": [ "c#", "recursion", ".net-core", "entity-framework-core" ], "Title": "Get all children recursively in Entity Framework Core" }
221714
<p>I have created 3 projects to implement layered architecture design mainly the - Presentation Layer (Web) - Domain Model Layer - Infrastructure Layer</p> <p>For simplicity, I have only two domain model entities: Customer.cs and Category.cs. In my domain model layer, I also put my repository interface (both custom and generic).</p> <p>In Infrastructure layer, I have the dbcontext, Unit of Work (including its interface) and repository classes (which implement repository interface). </p> <p>Here is my generic repository interface</p> <pre><code>public interface IRepositoryGeneric&lt;TEntity&gt; where TEntity : class { // CRD void Add(TEntity entity); void Remove(TEntity entity); TEntity Get(object Id); IEnumerable&lt;TEntity&gt; GetAll(); void Save(); } </code></pre> <p>Generic Repository class</p> <pre><code>public class RepositoryGeneric&lt;T&gt; : IRepositoryGeneric&lt;T&gt; where T : class { protected readonly AppDbContext db; public RepositoryGeneric(AppDbContext db) { this.db = db; } public void Add(T entity) { throw new NotImplementedException(); } public T Get(object Id) { throw new NotImplementedException(); } public IEnumerable&lt;T&gt; GetAll() { return db.Set&lt;T&gt;().ToList(); } public void Remove(T entity) { throw new NotImplementedException(); } public void Save() { throw new NotImplementedException(); } } </code></pre> <p>Unit of Work Interface</p> <pre><code>public interface IUnitOfWork : IDisposable { IRepositoryCustomer Customers { get; } IRepositoryCategory Categories { get; } int SaveChanges(); } </code></pre> <p>Unit of Work class</p> <pre><code>public class UnitOfWork : IUnitOfWork { private readonly AppDbContext db; public UnitOfWork() { db = new AppDbContext(); } private IRepositoryCustomer _Customers; public IRepositoryCustomer Customers { get { if (this._Customers == null) { this._Customers = new RepositoryCustomer(db); } return this._Customers; } } private IRepositoryCategory _Categories; public IRepositoryCategory Categories { get { if (_Categories == null) { _Categories = new RepositoryCategory(db); } return _Categories; } } public void Dispose() { db.Dispose(); } public int SaveChanges() { return db.SaveChanges(); } } </code></pre> <p>Yeah, I have yet to add Application layer, which is the Web API layer.</p> <p>Any comments on the structure of the whole solution? Any comments are welcome.</p> <p>My whole solution source is available at my github - <a href="https://github.com/ngaisteve1/LayeredArchitectureDesignCSharp" rel="nofollow noreferrer">https://github.com/ngaisteve1/LayeredArchitectureDesignCSharp</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T10:56:57.870", "Id": "428858", "Score": "1", "body": "I was about to review `RepositoryGeneric` when I realised this is a mockup class. Perhaps you could be more precise in describing which classes to review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:00:33.837", "Id": "428859", "Score": "0", "body": "Yeah, this whole solution is just a mockup to implement repository and uow concept. But, this mockup can be executed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:03:14.123", "Id": "428861", "Score": "3", "body": "Since you want a review of your mockup of layers, without any tangible code, I suggest you ask the question at 'software enigneering' https://softwareengineering.stackexchange.com/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T11:43:07.270", "Id": "428867", "Score": "2", "body": "You might want to read this and save yourself a lot of work: https://cpratt.co/repository-and-unit-of-work-patterns-with-entity-framework/ And also: https://www.thereformedprogrammer.net/is-the-repository-pattern-useful-with-entity-framework-core/ (\"No, the repository/unit-of-work pattern (shortened to Rep/UoW) isn’t useful with EF Core. EF Core already implements a Rep/UoW pattern, so layering another Rep/UoW pattern on top of EF Core isn’t helpful.\")" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T05:01:28.443", "Id": "429137", "Score": "1", "body": "@bcdotweb I found that unit testing is difficult when EF Core is used directly. The in memory provider works great for dbset, but doesn't really work with dbquery. Also in regards to domain driven design, EF appears to be a bad fit. Domain driven design seems to limit relationship modeling whereas EF is more relational. I am pretty new to domain driven design so I could be wrong. What are your thoughts?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T10:51:30.663", "Id": "221717", "Score": "1", "Tags": [ "c#", "design-patterns", "repository" ], "Title": "C# Generic Repository and Unit of Work Implementation for Northwind" }
221717
<h1>Background</h1> <p>I implemented the historic <a href="https://web.archive.org/web/20170228172445/http://en.cppreference.com/w/cpp/container/dynarray" rel="nofollow noreferrer"><code>std::dynarray</code></a> according to the specification under the name <code>dynamic_array</code> in C++17. <code>dynamic_array</code> doesn't attempt to get allocated on stack storage.</p> <p>The most interesting part is the allocator support. Unlike other containers, <code>dynamic_array</code> does not take an allocator as a template parameter. But it supports construction from an arbitrary allocator, and it has to call the appropriate allocator on destruction. As such, the allocator has to be stored with the help of type erasure.</p> <p>At first I thought of using <code>std::any</code> to hold the allocator. However, there is a problem: <code>std::any</code> does not have a <code>visit</code> functionality, we can't get the type of the allocator back, thus unable to call <code>std::allocator_traits&lt;A&gt;::destroy</code>.</p> <p>As such, my approach is to use a <code>std::function</code>. A lambda is generated for each construction from an allocator, which captures the allocator by copy and calls the correct destroy function. Admittedly, this is one of the few times I find a meaningful usage for <code>mutable</code> lambdas.</p> <h1>Code</h1> <p>Here's the header <code>dynamic_array.hpp</code>:</p> <pre><code>// C++17 fixed-size dynamic array #ifndef INC_DYNAMIC_ARRAY_HPP_akMQiHuI0M #define INC_DYNAMIC_ARRAY_HPP_akMQiHuI0M #include &lt;algorithm&gt; #include &lt;cstddef&gt; #include &lt;cstdint&gt; #include &lt;functional&gt; #include &lt;initializer_list&gt; #include &lt;iterator&gt; #include &lt;memory&gt; #include &lt;type_traits&gt; namespace LF_lib { template &lt;class T&gt; class dynamic_array { public: using value_type = T; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using reference = T&amp;; using const_reference = const T&amp;; using pointer = T*; using const_pointer = const T*; using iterator = T*; using const_iterator = const T*; using reverse_iterator = std::reverse_iterator&lt;iterator&gt;; using const_reverse_iterator = std::reverse_iterator&lt;const_iterator&gt;; // default-initializes the elements explicit dynamic_array(std::size_t n) :dynamic_array{n, std::allocator&lt;T&gt;{}} { } template &lt;class A&gt; dynamic_array(std::size_t n, const A&amp; a) :count{n} { if (count == 0) { register_empty_cleanup(); return; } A alloc = a; elems = std::allocator_traits&lt;A&gt;::allocate(alloc, count); T* p = begin(); try { register_cleanup(alloc); for (; p != end(); ++p) std::allocator_traits&lt;A&gt;::construct(alloc, p); } catch (...) { for (T* q = begin(); q != p; ++q) std::allocator_traits&lt;A&gt;::destroy(alloc, q); std::allocator_traits&lt;A&gt;::deallocate(alloc, elems, count); throw; } } dynamic_array(std::size_t n, const T&amp; value) :dynamic_array{n, value, std::allocator&lt;T&gt;{}} { } template &lt;class A&gt; dynamic_array(std::size_t n, const T&amp; value, const A&amp; a) :count{n} { if (count == 0) { register_empty_cleanup(); return; } A alloc = a; elems = std::allocator_traits&lt;A&gt;::allocate(alloc, count); T* p = begin(); try { register_cleanup(alloc); for (; p != end(); ++p) std::allocator_traits&lt;A&gt;::construct(alloc, p, value); } catch (...) { for (T* q = begin(); q != p; ++q) std::allocator_traits&lt;A&gt;::destroy(alloc, q); std::allocator_traits&lt;A&gt;::deallocate(alloc, elems, count); throw; } } dynamic_array(const dynamic_array&amp; other) :dynamic_array{other, std::allocator&lt;T&gt;{}} { } template &lt;class A&gt; dynamic_array(const dynamic_array&amp; other, const A&amp; a) :count{other.size()} { if (count == 0) { register_empty_cleanup(); return; } A alloc = a; elems = std::allocator_traits&lt;A&gt;::allocate(alloc, count); T* p = begin(); try { register_cleanup(alloc); for (const T* q = other.cbegin(); p != cend(); ++p, ++q) std::allocator_traits&lt;A&gt;::construct(alloc, p, *q); } catch (...) { for (T* q = begin(); q != p; ++q) std::allocator_traits&lt;A&gt;::destroy(alloc, q); std::allocator_traits&lt;A&gt;::deallocate(alloc, elems, count); throw; } } dynamic_array(std::initializer_list&lt;T&gt; init) :dynamic_array{init, std::allocator&lt;T&gt;{}} { } template &lt;class A&gt; dynamic_array(std::initializer_list&lt;T&gt; init, const A&amp; a) :count{init.size()} { if (count == 0) { register_empty_cleanup(); return; } A alloc = a; elems = std::allocator_traits&lt;A&gt;::allocate(alloc, count); T* p = begin(); try { register_cleanup(alloc); for (const T* q = init.begin(); p != end(); ++p, ++q) std::allocator_traits&lt;A&gt;::construct(alloc, p, *q); } catch (...) { for (T* q = begin(); q != p; ++q) std::allocator_traits&lt;A&gt;::destroy(alloc, q); std::allocator_traits&lt;A&gt;::deallocate(alloc, elems, count); throw; } } ~dynamic_array() { cleanup(elems, count); } dynamic_array&amp; operator=(const dynamic_array&amp;) = delete; dynamic_array&amp; operator=(dynamic_array&amp;&amp;) = delete; T&amp; at(std::size_t index) { check(index); return elems[index]; } const T&amp; at(std::size_t index) const { check(index); return elems[index]; } T&amp; operator[](std::size_t index) { return elems[index]; } const T&amp; operator[](std::size_t index) const { return elems[index]; } T&amp; front() { return elems[0]; } const T&amp; front() const { return elems[0]; } T&amp; back() { return elems[count - 1]; } const T&amp; back() const { return elems[count - 1]; } T* data() noexcept { return elems; } const T* data() const noexcept { return elems; } iterator begin() noexcept { return elems; } const_iterator begin() const noexcept { return elems; } const_iterator cbegin() const noexcept { return begin(); } iterator end() noexcept { return elems + count; } const_iterator end() const noexcept { return elems + count; } const_iterator cend() const noexcept { return end(); } reverse_iterator rbegin() noexcept { return end(); } const_reverse_iterator rbegin() const noexcept { return end(); } const_reverse_iterator crbegin() const noexcept { return rbegin(); } reverse_iterator rend() noexcept { return begin(); } const_reverse_iterator rend() const noexcept { return begin(); } const_reverse_iterator crend() const noexcept { return rend(); } bool empty() const noexcept { return size != 0; } std::size_t size() const noexcept { return count; } std::size_t max_size() const noexcept { return SIZE_MAX / sizeof(T); } void fill(const T&amp; value) { std::fill(begin(), end(), value); } private: T* elems = nullptr; std::size_t count; std::function&lt;void(T*, std::size_t)&gt; cleanup; void register_empty_cleanup() { cleanup = [](T*, std::size_t) {}; } template &lt;class A&gt; void register_cleanup(A&amp; alloc) { cleanup = [alloc](T* elems, std::size_t count) mutable { T* it = elems; for (std::size_t i = 0; i &lt; count; ++i) std::allocator_traits&lt;A&gt;::destroy(alloc, it++); std::allocator_traits&lt;A&gt;::deallocate(alloc, elems, count); }; } void check(std::size_t index) const { if (index &gt;= count) throw std::out_of_range{"LF_lib::dynamic_array out of range"}; } }; template &lt;class T&gt; bool operator==(const dynamic_array&lt;T&gt;&amp; lhs, const dynamic_array&lt;T&gt;&amp; rhs) { return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } template &lt;class T&gt; bool operator!=(const dynamic_array&lt;T&gt;&amp; lhs, const dynamic_array&lt;T&gt;&amp; rhs) { return !(lhs == rhs); } template &lt;class T&gt; bool operator&lt; (const dynamic_array&lt;T&gt;&amp; lhs, const dynamic_array&lt;T&gt;&amp; rhs) { return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } template &lt;class T&gt; bool operator&lt;=(const dynamic_array&lt;T&gt;&amp; lhs, const dynamic_array&lt;T&gt;&amp; rhs) { return !(rhs &lt; lhs); } template &lt;class T&gt; bool operator&gt; (const dynamic_array&lt;T&gt;&amp; lhs, const dynamic_array&lt;T&gt;&amp; rhs) { return rhs &lt; lhs; } template &lt;class T&gt; bool operator&gt;=(const dynamic_array&lt;T&gt;&amp; lhs, const dynamic_array&lt;T&gt;&amp; rhs) { return !(lhs &lt; rhs); } } namespace std { template &lt;class T, class A&gt; struct uses_allocator&lt;LF_lib::dynamic_array&lt;T&gt;, A&gt; :std::true_type { }; } #endif </code></pre> <p>And here's an example on its usage, showing how the allocators work under the hood:</p> <pre><code>#include &lt;iomanip&gt; #include &lt;iostream&gt; #include &lt;numeric&gt; #include &lt;string&gt; #include &lt;type_traits&gt; #include "dynamic_array.hpp" using LF_lib::dynamic_array; template &lt;typename T&gt; class Tracing_alloc :private std::allocator&lt;T&gt; { using Base = std::allocator&lt;T&gt;; public: using value_type = T; T* allocate(std::size_t n) { std::cerr &lt;&lt; "allocate(" &lt;&lt; n &lt;&lt; ")\n"; return Base::allocate(n); } void deallocate(T* ptr, std::size_t n) { std::cerr &lt;&lt; "deallocate(" &lt;&lt; static_cast&lt;void*&gt;(ptr) &lt;&lt; ", " &lt;&lt; n &lt;&lt; ")\n"; Base::deallocate(ptr, n); } template &lt;typename... Args&gt; void construct(T* ptr, Args&amp;&amp;... args) { std::cerr &lt;&lt; "construct(" &lt;&lt; ptr &lt;&lt; ", args...)\n"; std::allocator_traits&lt;Base&gt;::construct(*this, ptr, args...); } void destroy(T* ptr) { std::cerr &lt;&lt; "destroy(" &lt;&lt; ptr &lt;&lt; ")\n"; std::allocator_traits&lt;Base&gt;::destroy(*this, ptr); } }; template &lt;typename T&gt; bool operator==(const Tracing_alloc&lt;T&gt;&amp;, const Tracing_alloc&lt;T&gt;&amp;) { return true; } template &lt;typename T&gt; bool operator!=(const Tracing_alloc&lt;T&gt;&amp;, const Tracing_alloc&lt;T&gt;&amp;) { return false; } class Construct_throw { public: Construct_throw() { static int i = 0; if (i++ &gt; 3) throw std::exception{}; } }; void test(std::size_t n) { dynamic_array&lt;std::string&gt; arr{n, Tracing_alloc&lt;std::string&gt;{}}; for (auto&amp; x : arr) x = "a"; std::inclusive_scan(arr.begin(), arr.end(), arr.begin(), std::plus&lt;&gt;{}); for (const auto&amp; x : arr) std::cout &lt;&lt; std::quoted(x) &lt;&lt; " "; std::cout &lt;&lt; "\n"; dynamic_array&lt;std::string&gt; arr2{arr, Tracing_alloc&lt;std::string&gt;{}}; for (const auto&amp; x : arr2) std::cout &lt;&lt; std::quoted(x) &lt;&lt; " "; std::cout &lt;&lt; "\n"; dynamic_array&lt;std::string&gt; arr3{{"foo", "bar", "baz"}, Tracing_alloc&lt;std::string&gt;{}}; for (const auto&amp; x : arr3) std::cout &lt;&lt; std::quoted(x) &lt;&lt; " "; std::cout &lt;&lt; "\n"; dynamic_array&lt;Construct_throw&gt; arr4{n, Tracing_alloc&lt;Construct_throw&gt;{}}; } int main() try { test(0); test(10); } catch (...) { return 1; } </code></pre> <p>Here's the output I got: (the initial empty lines are intentional)</p> <pre> allocate(3) construct(000001CE3ADE8F60, args...) construct(000001CE3ADE8F80, args...) construct(000001CE3ADE8FA0, args...) "foo" "bar" "baz" destroy(000001CE3ADE8F60) destroy(000001CE3ADE8F80) destroy(000001CE3ADE8FA0) deallocate(000001CE3ADE8F60, 3) allocate(10) construct(000001CE3ADEC130, args...) construct(000001CE3ADEC150, args...) construct(000001CE3ADEC170, args...) construct(000001CE3ADEC190, args...) construct(000001CE3ADEC1B0, args...) construct(000001CE3ADEC1D0, args...) construct(000001CE3ADEC1F0, args...) construct(000001CE3ADEC210, args...) construct(000001CE3ADEC230, args...) construct(000001CE3ADEC250, args...) "a" "aa" "aaa" "aaaa" "aaaaa" "aaaaaa" "aaaaaaa" "aaaaaaaa" "aaaaaaaaa" "aaaaaaaaaa" allocate(10) construct(000001CE3ADEDED0, args...) construct(000001CE3ADEDEF0, args...) construct(000001CE3ADEDF10, args...) construct(000001CE3ADEDF30, args...) construct(000001CE3ADEDF50, args...) construct(000001CE3ADEDF70, args...) construct(000001CE3ADEDF90, args...) construct(000001CE3ADEDFB0, args...) construct(000001CE3ADEDFD0, args...) construct(000001CE3ADEDFF0, args...) "a" "aa" "aaa" "aaaa" "aaaaa" "aaaaaa" "aaaaaaa" "aaaaaaaa" "aaaaaaaaa" "aaaaaaaaaa" allocate(3) construct(000001CE3ADE8F60, args...) construct(000001CE3ADE8F80, args...) construct(000001CE3ADE8FA0, args...) "foo" "bar" "baz" allocate(10) construct(000001CE3ADE8CC0, args...) construct(000001CE3ADE8CC1, args...) construct(000001CE3ADE8CC2, args...) construct(000001CE3ADE8CC3, args...) construct(000001CE3ADE8CC4, args...) destroy(000001CE3ADE8CC0) destroy(000001CE3ADE8CC1) destroy(000001CE3ADE8CC2) destroy(000001CE3ADE8CC3) deallocate(000001CE3ADE8CC0, 10) destroy(000001CE3ADE8F60) destroy(000001CE3ADE8F80) destroy(000001CE3ADE8FA0) deallocate(000001CE3ADE8F60, 3) destroy(000001CE3ADEDED0) destroy(000001CE3ADEDEF0) destroy(000001CE3ADEDF10) destroy(000001CE3ADEDF30) destroy(000001CE3ADEDF50) destroy(000001CE3ADEDF70) destroy(000001CE3ADEDF90) destroy(000001CE3ADEDFB0) destroy(000001CE3ADEDFD0) destroy(000001CE3ADEDFF0) deallocate(000001CE3ADEDED0, 10) destroy(000001CE3ADEC130) destroy(000001CE3ADEC150) destroy(000001CE3ADEC170) destroy(000001CE3ADEC190) destroy(000001CE3ADEC1B0) destroy(000001CE3ADEC1D0) destroy(000001CE3ADEC1F0) destroy(000001CE3ADEC210) destroy(000001CE3ADEC230) destroy(000001CE3ADEC250) deallocate(000001CE3ADEC130, 10) </pre> <p>Of course, you may get completely different addresses.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T12:11:49.760", "Id": "221719", "Score": "3", "Tags": [ "c++", "array", "reinventing-the-wheel", "memory-management", "c++17" ], "Title": "A fixed-size dynamic array" }
221719
<p>I want to get a result from the website when I submit a form. There are several things that can go wrong. </p> <p>In a simple scenario I want to return:</p> <p><code>true</code> - when form was submitted</p> <p><code>false</code> - when form wasn't submitted</p> <p><code>null</code> - when we don't know if form was submitted or not</p> <p>I did that ugly <code>try</code>, because of <code>NullReferenceException</code> (if form is filled correctly, there would be no <code>summary</code> element, and if form is filled incorrectly, there would be no <code>popup</code> element).</p> <p>How can I make this more elegant?</p> <pre><code>public bool? GetResult(TimeSpan timeout) { var deadline = DateTime.Now.Add(timeout); do { // check if success try { var success = new WebDriverWait(Driver, TimeSpan.FromSeconds(5)) .Until(ExpectedConditions.TextToBePresentInElement(Driver.FindElement(By.Id("summary")), "Success!")); if (success) return true; } catch (Exception ex) { } // check if not enough data try { var notEnoughData = new WebDriverWait(Driver, TimeSpan.FromSeconds(5)) .Until(ExpectedConditions.TextToBePresentInElement(Driver.FindElement(By.Id("popup")), "Not enough data")); if (notEnoughData) return false; } catch (Exception ex) { } // check if too much data try { var tooMuchData = new WebDriverWait(Driver, TimeSpan.FromSeconds(5)) .Until(ExpectedConditions.TextToBePresentInElement(Driver.FindElement(By.Id("popup")), "Too much data")); if (tooMuchData) return false; } catch (Exception ex) { } // check if empty data try { var tooMuchData = new WebDriverWait(Driver, TimeSpan.FromSeconds(5)) .Until(ExpectedConditions.TextToBePresentInElement(Driver.FindElement(By.Id("popup")), "Empty data")); if (tooMuchData) return false; } catch (Exception ex) { } } while (DateTime.Now &gt; deadline); return null; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T16:07:33.357", "Id": "428907", "Score": "0", "body": "You should at least include code for `WebDriverWait` (so we can review async operations on it) and `Driver` (so we can try to avoid null reference exceptions). And use `StopWatch` for verifying elapsed time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T19:07:26.030", "Id": "428929", "Score": "0", "body": "That doesn't seem to be your working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T06:28:35.660", "Id": "428975", "Score": "0", "body": "@dfhwze `WebDriverWait` is part of Selenium api: https://www.seleniumhq.org/docs/04_webdriver_advanced.jsp." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T06:28:59.143", "Id": "428976", "Score": "0", "body": "@Heslacher it is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T16:46:06.753", "Id": "429056", "Score": "0", "body": "Well now the question is closed. Let me place a reopen-vote and hopefully the question will be reopened." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T19:22:48.337", "Id": "429099", "Score": "0", "body": "@Heslacher I still think the OP should provide more information about the UI. We need to be able to review his exception handling as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T19:27:30.967", "Id": "429100", "Score": "0", "body": "@dfhwze I don't see why we need the UI context here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T19:29:36.943", "Id": "429101", "Score": "0", "body": "@Heslacher I would think to verify how to prevent the NRE he talks about in the 'ugly try' paragraph." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T23:45:23.017", "Id": "429122", "Score": "1", "body": "@dfhwze chack my answer about the NRE" } ]
[ { "body": "<blockquote>\n <p>I did that ugly try, because of NullReferenceException (if form is filled correctly, there would be no summary element, and if form is filled incorrectly, there would be no popup element). </p>\n</blockquote>\n\n<p>This problem can be easyly handled by a <code>null</code> check of the returned <code>WebElement</code> from the call to <code>Driver.FindElement()</code>. </p>\n\n<p>A little bit more problematic is IMO the looping condition because the condition only could evaluate to <code>true</code> if the passed <code>TimeSpan</code> is negativ. If this is what you want you really should place a comment there. If you didn't mean to pass a negative timespan then you should reverse the looping condition to <code>DateTime.Now &lt; deadline</code>. </p>\n\n<p>Extracting the repeated call to <code>TimeSpan.FromSeconds(5)</code> to a variable will make the code easier to read. </p>\n\n<p>You know although copy &amp; pasta will save time, you need to check if the pasted code is correct (empty data vs tooMuchData) </p>\n\n<blockquote>\n<pre><code> // check if empty data\n try\n {\n var tooMuchData = new WebDriverWait(Driver, TimeSpan.FromSeconds(5))\n .Until(ExpectedConditions.TextToBePresentInElement(Driver.FindElement(By.Id(\"popup\")), \"Empty data\"));\n if (tooMuchData) return false; \n</code></pre>\n</blockquote>\n\n<p>Implementing the mentioned points will look like so </p>\n\n<pre><code>public bool? GetResult(TimeSpan timeout)\n{\n var deadline = DateTime.Now.Add(timeout);\n var waitTimeout = TimeSpan.FromSeconds(5);\n\n do\n {\n WebElement summaryWebElement = Driver.FindElement(By.Id(\"summary\"));\n if (summaryWebElement != null)\n {\n var success = new WebDriverWait(Driver, waitTimeout).Until(ExpectedConditions.TextToBePresentInElement(summaryWebElement , \"Success!\"));\n if (success) return true;\n }\n\n WebElement popupWebElement = Driver.FindElement(By.Id(\"popup\"));\n if (popupWebelement != null)\n {\n var notEnoughData = new WebDriverWait(Driver, waitTimeout).Until(ExpectedConditions.TextToBePresentInElement(popupWebElement, \"Not enough data\"));\n if (notEnoughData) return false;\n\n var tooMuchData = new WebDriverWait(Driver, waitTimeout).Until(ExpectedConditions.TextToBePresentInElement(popupWebelement, \"Too much data\"));\n if (tooMuchData) return false;\n\n var emptyData = new WebDriverWait(Driver, waitTimeout).Until(ExpectedConditions.TextToBePresentInElement(popupWebElement, \"Empty data\"));\n if (emptyData) return false;\n }\n\n } while (DateTime.Now &gt; deadline);\n\n return null;\n} \n</code></pre>\n\n<p>Because the checks for the popup text only differs from the expected text you could think about using a foreach loop over an array containing the expected strings.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T04:31:07.227", "Id": "429131", "Score": "0", "body": "the only thing I would change is to get rid of that DateTime for checking elapsed time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T23:35:18.983", "Id": "221816", "ParentId": "221721", "Score": "3" } } ]
{ "AcceptedAnswerId": "221816", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:04:57.527", "Id": "221721", "Score": "3", "Tags": [ "c#", "error-handling", "selenium" ], "Title": "Get result from form website operation" }
221721
<p>The premise of this program is to use the least amount of vehicles to allocate the available load.</p> <p>What I did is allocate the largest amount of load on the truck that fits better.</p> <p>This program's intention is not to optimize a load. I.e. if I have a load of 24, the program does not use two 12 capable vehicles, but the 30 one (because it is more costly to move two vehicles than one). This code works as I expect but I would like to get suggestions on how to improve it / make it more efficient.</p> <pre><code>// Available vehicles const vehicles = [ {name: 'Camión', capacity: 5}, {name: 'Rabón', capacity: 8}, {name: 'Tráiler', capacity: 30}, {name: 'Torton', capacity: 12, std: true}, ]; function calculate(productList:any[]) { let groups = []; const totalSize: number = productList.reduce((accumulator, currentValue) =&gt; accumulator + currentValue); const stdVehicle = this.vehicles.find(v =&gt; {return v.std}); // Sorting array this.vehicles.sort(function(a, b){return a.capacity - b.capacity}); // Checking for exact match const exactMatch = this.vehicles.filter(v =&gt; {return v.capacity === totalSize}); if (exactMatch.length) { // Exact Match found! exactMatch = exactMatch[0]; return [{ hasToPay: (stdVehicle.capacity &gt;= exactMatch.capacity), vehicle: exactMatch, remaining: 0, load: exactMatch.capacity, }]; } let remainingSize = totalSize; while(remainingSize &gt; 0) { let closest = this.vehicles.filter(v =&gt; {return v.capacity &gt; remainingSize}); if (!closest.length) { // Total size is bigger than our biggest vehicle. Setting our biggest vehicle for first group closest = this.vehicles[this.vehicles.length - 1]; } else { // Setting closest (but bigger) vehicle to allocate remaining size closest = closest[0]; } groups.push({ vehicle: closest, remaining: (closest.capacity - remainingSize &lt; 0) ? 0 : closest.capacity - remainingSize, load: (remainingSize &gt; closest.capacity) ? closest.capacity : remainingSize, }); remainingSize -= closest.capacity; } // Deciding whether or not the customer has to pay for each group groups.map(r =&gt; {r.hasToPay = !(r.load === r.vehicle.capacity &amp;&amp; stdVehicle.capacity &lt;= r.vehicle.capacity)}); console.log("===================================="); return groups; } // Test cases const a = [12, 12, 12]; // 3 items with the size of the std const b = [1, 1, 3]; // Items that summed up fit exactly on a camión const c = [10, 15, 5]; // Items that summed up fit exactly on a tráiler const d = [30, 30, 12]; // 3 items that summed up fit exactly on 2 tráilers and 1 torton const e = [9, 5]; // 2 items that summed up fit on a trailer and has remaining console.log(this.calculate(a)); console.log(this.calculate(b)); console.log(this.calculate(c)); console.log(this.calculate(d)); console.log(this.calculate(e)); </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:26:41.700", "Id": "221722", "Score": "4", "Tags": [ "typescript" ], "Title": "Product allocation on trucks" }
221722
<p>That is a simple program to hide text messages in text files. I'd like to hear any advices to improve my code and style.</p> <p>Some notes:</p> <ol> <li><em>There is no error handling</em> to simplify the program. It is not a «real» program anyway. There is many assertions instead error handling.</li> <li>I wrote my own implementations to <code>strdup</code> and <code>strrev</code> because these functions are not a part of ISO C. I called they as <code>reverseString</code> and <code>duplicateString</code> corresponding since names like <code>str*</code> is reserved by ISO C.</li> <li>I check the validity of input arguments in functions to prevent mistakes of using internal API.</li> <li>All the functions marked as <code>static</code> because all they in a single translation unit. </li> </ol> <p>And one another question: <em>the input file should be opened in text mode while temporary file is always opens in binary mode (<code>w+b</code>). Could it lead to some problems?</em></p> <h3>Compiler</h3> <p>I'm using Clang to compile the program with such flags:</p> <pre><code>-std=c11 -Weverything -Wpedantic -fsanitize=address -D_CRT_SECURE_NO_WARNINGS </code></pre> <p>It gives only one warning:</p> <pre><code>warning: implicit conversion turns floating-point number into integer: 'double' to 'size_t' (aka 'unsigned int') [-Wfloat-conversion] const size_t newCapacity = ceil(s-&gt;capacity * DYNAMIC_STRING_GROW_FACTOR); </code></pre> <h3>Static code analyzer</h3> <p>Also I have checked the code by CppCheck and it gives only one error: «<em>Memory leak: <code>ret</code> in function <code>stringToBinary</code></em>»:</p> <pre><code>char *stringToBinary(const char *s) { assert(s); assert(strlen(s) &gt; 0); char *ret = calloc((strlen(s) + 1) * CHAR_BIT + 1, 1); assert(ret); for (size_t i = 0; s[i] != '\0'; i++) strcat(ret, charToBinary(s[i])); return strcat(ret, charToBinary('\0')); } </code></pre> <p>But I think it is a false positive because <code>ret</code> is freed in the <code>hideMessage</code> function:</p> <pre><code>char *msgBinary = stringToBinary(msg); ... free(msgBinary); </code></pre> <hr> <p>I'll be glad if you give me <strong>any</strong> tips to improve my code or correct my mistakes. Thanks you in advance! Best regards :)</p> <pre><code>#include &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;limits.h&gt; #include &lt;assert.h&gt; #define DYNAMIC_STRING_GROW_FACTOR 1.5 typedef struct DynamicString { char *s; size_t capacity; size_t length; } DynamicString; static void createDynamicString(DynamicString *, size_t); static void destroyDynamicString(DynamicString *); static void increaseDynamicStringCapacity(DynamicString *); static void appendCharToDynamicString(DynamicString *, char); static void hideMessage(FILE *, const char *); static char *extractMessage(FILE *); static void copyFile(FILE *, FILE *); static char *stringToBinary(const char *); static char *charToBinary(char); static char charFromBinary(const char *); static char *reverseString(char *); static char *duplicateString(const char *s); int main(void) { FILE *file = fopen("file.txt", "r+"); assert(file); hideMessage(file, "hello, world"); char *msg = extractMessage(file); assert(msg); puts(msg); free(msg); fclose(file); } /* The HIDEMESSAGE function * * The function hides text message into the file by that way: 1) the message * converts to binary; 2) each bit of the converted message writes at the end * of each file's line (right before the new-line character): if the bit * is 1 then a space (' ') appends to the line otherwise it's nothing appends * to the line. * * Assumes the the file does not contain any spaces right before new-line * characters. Also assumes that the file has enough lines for storing * the message. */ void hideMessage(FILE *f, const char *msg) { assert(f); assert(msg); assert(strlen(msg) &gt; 0); char *msgBinary = stringToBinary(msg); assert(msgBinary); FILE *tempFile = tmpfile(); assert(tempFile); for (int ch, i = 0; (ch = fgetc(f)) != EOF;) { if (msgBinary[i] &amp;&amp; (ch == '\n')) if (msgBinary[i++] == '1') fputc(' ', tempFile); fputc(ch, tempFile); } copyFile(f, tempFile); free(msgBinary); fclose(tempFile); } /* The EXTRACTMESSAGE function * * The function extracts message hidden by the HIDEMESSAGE function from * the input file and returns a pointer to heap-allocated string which * contains the message. */ char *extractMessage(FILE *f) { assert(f); DynamicString msgBuffer; createDynamicString(&amp;msgBuffer, 128); char charInBinary[CHAR_BIT + 1] = {0}; for (int prevCh = 0, ch, i = 0; (ch = fgetc(f)) != EOF; prevCh = ch) { if (ch == '\n') charInBinary[i++] = (prevCh == ' ') ? '1' : '0'; if (i % CHAR_BIT == 0 &amp;&amp; i != 0) { if (!strcmp(charInBinary, charToBinary('\0'))) break; i = 0; appendCharToDynamicString(&amp;msgBuffer, charFromBinary(charInBinary)); } } char *ret = duplicateString(msgBuffer.s); assert(ret); destroyDynamicString(&amp;msgBuffer); return ret; } /* The CREATEDYNAMICSTRING function * * The function initializes a DynamicString passing by the first argument. * The initial capacity of the string is passing by the second argument. * Capacity is the max length of the string. At the same time length is * current length of the string. Thus the function allocates capacity + 1 * bytes for the string (considering the null-character). * * The input pointer to DynamicString struture should be a valid pointer and * capacity should be greater than 0. */ void createDynamicString(DynamicString *ret, size_t capacity) { assert(ret); assert(capacity &gt; 0); ret-&gt;s = malloc(capacity + 1); assert(ret-&gt;s); ret-&gt;length = 0; ret-&gt;capacity = capacity; } /* The APPENDCHARTODYNAMICSTRING function * * The function appends a character to the input DynamicString. If capacity of * the string is not enough the function increases it. * * The input pointer to a DynamicString should be a valid pointer as well as * its string buffer. */ void appendCharToDynamicString(DynamicString *s, char c) { assert(s); assert(s-&gt;s); if (s-&gt;length == s-&gt;capacity) increaseDynamicStringCapacity(s); s-&gt;s[s-&gt;length++] = c; s-&gt;s[s-&gt;length] = '\0'; } /* The INCREASEDYNAMICSTRINGCAPACITY function * * The function increases capacity of the input DynamicString. Grow factor * is sets by a macro constant DYNAMIC_STRING_GROW_FACTOR. * * The input pointer to a DynamicString struture should be a valid pointer * as well as its string buffer. */ void increaseDynamicStringCapacity(DynamicString *s) { assert(s); assert(s-&gt;s); const size_t newCapacity = ceil(s-&gt;capacity * DYNAMIC_STRING_GROW_FACTOR); s-&gt;s = realloc(s-&gt;s, newCapacity + 1); assert(s-&gt;s); s-&gt;capacity = newCapacity; } /* The DESTROYDYNAMICSTRING function * * The function destroys the input DynamicString. It frees the string buffer * of the input DynamicString. * * The input pointer to a DynamicString should be a valid pointer as well as * its string buffer. */ void destroyDynamicString(DynamicString *s) { assert(s); assert(s-&gt;s); free(s-&gt;s); } /* The COPYFILE function * * The function copies all the contents of src to dest. Both arguments should * be valid pointers. dest should be open for writing, src should be open * for reading. The function does not close the files. The both file cursor * position sets to the beginning. */ void copyFile(FILE *dest, FILE *src) { assert(dest); assert(src); rewind(dest); rewind(src); for (int ch; (ch = fgetc(src)) != EOF;) fputc(ch, dest); rewind(dest); rewind(src); } /* The CHARFROMBINARY function * * The function converts the input string returned by the CHARTOBINARY function * to a character. * * The input string should be a valid null-terminated string and its length * should be greater 0. * * charFromBinary(charToBinary(c)) == c */ char charFromBinary(const char *s) { assert(s); assert(strlen(s) &gt; 0); char ret = 0; unsigned int p = 1; for (size_t i = strlen(s); i-- &gt; 0; p *= 2) if (s[i] == '1') ret += p; return ret; } /* The STRINGTOBINARY function * * The function converts the input string to binary form and returns a pointer * to heap-allocated null-terminated string. Null-terminator of the input * string also converts to binary form and appends to the result. The caller * should free memory allocated for the output string. * * The input string should be a valid null-terminated string and its length * should be greater 0. * * stringToBinary("cat") =&gt; "01100011011000010111010000000000" * stringToBinary("dog") =&gt; "01100100011011110110011100000000" * stringToBinary("R\0") =&gt; "0101001000000000" */ char *stringToBinary(const char *s) { assert(s); assert(strlen(s) &gt; 0); char *ret = calloc((strlen(s) + 1) * CHAR_BIT + 1, 1); assert(ret); for (size_t i = 0; s[i] != '\0'; i++) strcat(ret, charToBinary(s[i])); return strcat(ret, charToBinary('\0')); } /* The CHARTOBINARY function * * The function converts value of the input character to binary form and * returns a pointer to the static null-terminated string which contains * the result. The result contains leading zeroes. * * charToBinary(100) =&gt; "01100100" * charToBinary('A') =&gt; "01000001" * charToBinary('\0') =&gt; "00000000" */ char *charToBinary(char c) { static char ret[CHAR_BIT + 1]; memset(ret, '0', sizeof ret); ret[sizeof ret - 1] = '\0'; for (size_t i = 0; c; i++) { ret[i] = (c % 2) ? '1' : '0'; c /= 2; } return reverseString(ret); } /* The REVERSESTRING function * * The input string should be a valid pointer to a null-terminated string. * If the input string is empty the function does noting. * * reverseString("hello") =&gt; "olleh" * reverseString("a") =&gt; "a" * reverseString("") =&gt; "a" */ char *reverseString(char *s) { assert(s); char *begin = s; char *end = s + strlen(s) - 1; for (; begin &lt; end; begin++, end--) { const char t = *begin; *begin = *end; *end = t; } return s; } /* The DUPLICATESTRING function * * The function returns a pointer to a heap-allocated string, which is a * duplicate of the input string. The returned pointer can be passed to the * free function. */ char *duplicateString(const char *s) { assert(s); assert(strlen(s) &gt; 0); char *copy = malloc(strlen(s) + 1); assert(copy); return strcpy(copy, s); } </code></pre> <p><sub>P.S. I'm not a native English speaker so… sorry for the inconvenience.</sub></p>
[]
[ { "body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Don't hardcode file names</h2>\n\n<p>Generally, it's not a good idea to hardcode a file name in software. Instead, it would be better to allow the user of the program to specify the name, as with a command line parameter.</p>\n\n<h2>Don't use <code>assert</code> to handle errors</h2>\n\n<p>The use of <code>assert</code> is to help debug the program, so in some cases, such as <code>assert(f)</code> in <code>hideMessage</code> it makes sense, but in others, such as <code>assert(file)</code> in <code>main()</code>, it's not appropriate. Better would be to write something like this:</p>\n\n<pre><code>if (infile == NULL) {\n fprintf(stderr, \"Error: could not open input file \\\"%s\\\"\\n\", argv[1]);\n return 2;\n}\n</code></pre>\n\n<h2>Don't bother encoding terminating NUL character</h2>\n\n<p>By definition, the string-terminating NUL character (<code>'\\0'</code>) is a string of zeroes which will, according to the encoding rules, not alter the line endings. For that reason, there's little reason to bother encoding them.</p>\n\n<h2>Allow separation of input and output files</h2>\n\n<p>It may be that having the input and output files as separate files would be handy. For that reason, I'd suggest making them separate file names.</p>\n\n<h2>Rethink the use of strings</h2>\n\n<p>The conversion of each message string to a string that's eight times longer (by converting into the equivalent string of <code>'1'</code> and <code>'0'</code> characters is not really necessary. One could instead simply pick off bits of the message when encoding. Here's one way to do that:</p>\n\n<pre><code>bool hideMessage(const char *msg, FILE *infile, FILE *outfile) {\n if (msg == NULL) {\n return false;\n }\n for ( ; *msg; ++msg) {\n for (int mask = 0x80; mask; mask &gt;&gt;= 1) {\n if (encodeBit(infile, outfile, mask &amp; *msg) == EOF) {\n return false;\n }\n }\n }\n // copy the rest of the file\n for (int ch = fgetc(infile); ch != EOF; ch = fgetc(infile)) {\n fputc(ch, outfile);\n }\n return true;\n}\n</code></pre>\n\n<p>This marches through the passed message, encoding bit at a time until it encounters the end of the input message and then simply copies the rest of the input file to the output file unaltered. Here's one way to write the <code>encodeBit</code> function:</p>\n\n<pre><code>int encodeBit(FILE *infile, FILE *outfile, char bit) {\n for (int ch = fgetc(infile); ch != EOF; ch = fgetc(infile)) {\n switch(ch) {\n case '\\n':\n if (bit) {\n fputc(' ', outfile);\n }\n fputc(ch, outfile);\n return ch;\n break;\n default:\n fputc(ch, outfile);\n }\n }\n return EOF;\n}\n</code></pre>\n\n<p>This code returns the last character read, so that <code>EOF</code> can be used as an indication of error (that is, the file is too short to encode the message).</p>\n\n<p>One can also create the reverse functions in very similar manner.</p>\n\n<h2>Be aware of file modes differences</h2>\n\n<p>On POSIX compliant operating systems, such as Linux, there is no difference between binary and text mode for file handles. However other operating systems, most notably Windows, do differentiate between them. The difference is that CR LF (0x0d 0x0a) is used as the line ending in Windows (while just LF, 0x0a is used on Linux). For that reason, for code like this, I'd suggest opening both files in text mode. This means, unfortunately, that you can't use <code>tmpfile()</code> and follow this advice. Otherwise you could have the unfortunate situation in which the file is emitted with CR SP LF (0x0d 0x20 0x0a) which would likely confuse Windows greatly.</p>\n\n<h2>Comments on comments</h2>\n\n<p>Although a native English speaker will likely be able to detect from the comments that they were not written by a native English speaker, they're still quite understandable and convey exactly the kinds of information that a reader needs -- \"what does it do and how should I use it?\" My only complaint, and it's a small one, is that starting each comment block with \"The APPENDCHARTODYNAMICSTRING function\" is not helpful. First, we know it's a function so that doesn't add much information, and second, it turns the relatively readable <code>appendCharToDynamicString</code> and turned it into something less readable. I tend to document my C code with annotations that can be used by <a href=\"http://www.doxygen.nl/\" rel=\"nofollow noreferrer\">Doxygen</a> which can then be used to very easily turn your source code into high quality documentation.</p>\n\n<h2>Consider enhancements</h2>\n\n<p>It might be useful to encrypt the string before encoding. It might also be useful to provide the ability to detect if the file already might contain a hidden message. This could be done by always encoding a <code>1</code> bit before every message. Further, if the code used space and tab characters to encode ones and zeroes, it would be possible to stack multiple messages in the same file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T18:20:05.863", "Id": "429259", "Score": "0", "body": "Thanks a lot for the answer! Do I understand correctly that using `CHAR_BIT` is not make sense in my code? And the second, a little funny, question, can a native English speaker understand my comments in the code? =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T18:22:24.530", "Id": "429261", "Score": "0", "body": "And one another question: the input file should be opened in text mode while temporary file is always opens in binary mode (`w+b`). Could it lead to some problems in general case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T18:50:19.813", "Id": "429263", "Score": "0", "body": "I've updated my answer to try to answer your questions. In the comments, your English isn't perfect, but it's certainly adequate in my view. Молодец!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T18:57:56.997", "Id": "429265", "Score": "0", "body": "Oh, and your use of `CHAR_BIT` is OK, but made moot if you follow the suggestions in my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T19:18:04.773", "Id": "429269", "Score": "0", "body": "Oh, thanks you a lot again!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T17:13:43.333", "Id": "221871", "ParentId": "221723", "Score": "2" } } ]
{ "AcceptedAnswerId": "221871", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T13:46:25.993", "Id": "221723", "Score": "2", "Tags": [ "c", "strings", "file", "steganography" ], "Title": "Simple program to hide messages in files (steganography)" }
221723
<p>Do 3 arrays contain a common element, if they contain output it. For example: [1,2,3], [2,3], [2,4] -> answer = 2</p> <pre><code>let arr1 = [1, 3, 11, 32, 44, 99]; let arr2 = [4, 12, 15, 99]; let arr3 = [4, 11, 13, 15, 23, 43]; function searchThreeSameNum(arr1, arr2, arr3) { let i = 0; let j = 0; while (1) { if (i == arr1.length || j == arr2.length) { return 'No equal numbers'; } if (arr1[i] &lt; arr2[j]) { i++; continue; } else if (arr1[i] &gt; arr2[j]) { j++; continue; } else if (arr1[i] == arr2[j]) for (let k = 0; k &lt; arr3.length; k++) { if (arr1[i] == arr3[k]) return arr1[i]; } return 'No equal numbers'; } } </code></pre> <p>I will be glad if you give me any tips to improve my code. Thanks in advance. Sorry, I'm not an English speaker.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T15:12:53.000", "Id": "428899", "Score": "1", "body": "Need more clarification. You could start by giving several cases, or at least the answer to this one. And when you say \"common element\", are you expecting just one answer? What happens if there's more than one? Can there be more than one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T15:32:53.213", "Id": "428902", "Score": "0", "body": "What do you mean by \"first\" common element? The lowest value? Or some metric involving the three indices?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T15:40:18.290", "Id": "428903", "Score": "1", "body": "The lowest value" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T12:38:44.320", "Id": "429022", "Score": "0", "body": "I would rather compare two arrays, then compare that result to the third. I believe such code would be more reusable and easy to adapt to find the same value in 4 arrays. But it would be MUCH less efficient if you generally expect to find the first match of all 3 arrays fairly early." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T19:46:09.653", "Id": "429102", "Score": "1", "body": "I just noticed how freakishly anemic the `Set` API in ECMAScript is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T08:09:33.027", "Id": "429159", "Score": "0", "body": "@JörgWMittag it's weak, but still the best option in my opinion" } ]
[ { "body": "<p>Although your code seems to work, it is difficult to read. Loops inside loops and many <code>if</code>, <code>else if</code> blocks and <code>continue</code> or <code>return</code>. Let's start with some big issues:</p>\n\n<p>You use an <em>endless while loop</em> when it is clear you don't have to. The code below would perform the same function:</p>\n\n<pre><code>function searchThreeSameNum(arr1, arr2, arr3) {\n let i = 0, j = 0;\n while (i &lt; arr1.length &amp;&amp; j &lt; arr2.length) {\n if (arr1[i] &lt; arr2[j]) {\n i++;\n continue;\n } else if (arr1[i] &gt; arr2[j]) {\n j++;\n continue;\n } else if (arr1[i] == arr2[j]) {\n for (let k = 0; k &lt; arr3.length; k++) {\n if (arr1[i] == arr3[k]) return arr1[i];\n } \n } \n }\n return 'No equal numbers';\n}\n</code></pre>\n\n<p>This has one less <code>return 'No equal numbers';</code> (<a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">code repetition</a>) and only one <code>return</code> from within the while loop. </p>\n\n<p>Now let's look at what the loop is actually doing. It runs through array 1 and 2 and tries to find equal pairs of values in them. If a pair is found it searches in the third array for the same value and returns it when it is found. </p>\n\n<p>There is a handy array method called <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\">includes()</a>. It could replace the whole looping of the third array, like this:</p>\n\n<pre><code>function searchThreeSameNum(arr1, arr2, arr3) {\n let i = 0, j = 0;\n while (i &lt; arr1.length &amp;&amp; j &lt; arr2.length) {\n if (arr1[i] &lt; arr2[j]) {\n i++;\n continue;\n } else if (arr1[i] &gt; arr2[j]) {\n j++;\n continue;\n } else if (arr1[i] == arr2[j]) {\n if (arr3.includes(arr1[i])) return arr1[i];\n } \n }\n return 'No equal numbers';\n}\n</code></pre>\n\n<p>I could even go a step further and get rid of the while loop altogether by looping through array 1 and see if its values are contained in array 2 and 3, like this:</p>\n\n<pre><code>function searchThreeSameNum2(arr1, arr2, arr3) {\n for (number of arr1) {\n if (arr2.includes(number) &amp;&amp; arr3.includes(number)) return number;\n }\n return 'No equal numbers';\n}\n</code></pre>\n\n<p>Note that this simplification makes this function easy to read, but also less efficient. It has to checks array 2 and 3 completely, for every element of array 1, until a match is found.</p>\n\n<p>The assumption, in the function above, is that array 1 is properly sorted. If it isn't you can <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\">sort</a> it.</p>\n\n<pre><code>function searchThreeSameNum2(arr1, arr2, arr3) {\n let sorted = arr1.sort((a, b) =&gt; a - b);\n for (number of sorted) {\n if (arr2.includes(number) &amp;&amp; arr3.includes(number)) return number;\n }\n return 'No equal numbers';\n}\n</code></pre>\n\n<p>Arrays 2 and 3 don't need to be sorted.</p>\n\n<p><strong>In summary</strong> </p>\n\n<ol>\n<li>If you use a while loop, always break the loop with a proper condition in the right place. Do not use endless loops.</li>\n<li>Try not to use complex execution flow constructions, with lot of <code>else</code>, <code>continue</code> and <code>return</code>. They are difficult to read and to debug. </li>\n<li>Use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\">build in array methods</a>, they are very handy, but don't overdo it.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T01:49:18.533", "Id": "428963", "Score": "2", "body": "Searching the whole of `arr2` and `arr3` for *each* number in `arr1` gives you `O(N^2)` complexity if they all have equal length. Or `O(A * B)` complexity if they're different. (Assuming worst-case where no hit is found). Reducing this to `O(A + B +C)` or so is the point of writing an algorithm instead of just using brute force library functions. The OP's code only searches `arr3` for matches in `arr1[i] == arr2[j]`. It still has a bad N^2 worst-case, unlike Roland's answer, but only when arr1 and arr2 have a lot of matching elements vs. your always." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T01:54:51.387", "Id": "428964", "Score": "1", "body": "For small problem sizes simplifying to a brute-force algorithm can be appropriate for simplicity readability, and I agree with your comments about it being hard to follow the logic. But your claim \"*we don't need the complex while loop at all*\" is an oversimplification that ignores the point of the algorithm the OP was attempting. And BTW, your final version only needs `arr1` sorted if you care about finding the smallest same element, rather than *a* same element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T08:54:36.043", "Id": "428990", "Score": "0", "body": "@PeterCordes You're right that, at larger array sizes, the proposed algorithm is less efficient than an algorithm that walks all three arrays. I might indeed have gone a step too far. In this case there is clearly a trade-off between readability and efficiency. I stressed the former because it was lacking in the question, but if the latter is important, a slightly more complex algorithm is probably the beter choice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T09:32:29.117", "Id": "429001", "Score": "0", "body": "Sure, it's useful to present the last most-readable option. My suggestion is just that you should introduce it accurately, as a *less efficient* algorithm that's simpler to write and read. For *very* small arrays it might be more efficient in practice (smaller / simpler code with less overhead). But Roland's algorithm looks very good for even small-ish arrays." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T09:52:28.283", "Id": "429002", "Score": "0", "body": "I agree, I'll add that into my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T09:59:46.630", "Id": "429003", "Score": "0", "body": "Yay, now I can upvote this answer :) I previously wanted to, but that was a showstopper." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T16:44:56.020", "Id": "221729", "ParentId": "221724", "Score": "10" } }, { "body": "<p>Your code assumes that each of the 3 arrays is sorted. Otherwise the <code>&lt;</code> operator would not work. It's ok to assume this. You should have mentioned this in your question.</p>\n\n<p>You use the <code>==</code> operator for comparing the numbers and the lengths. You should better use the <code>===</code> since the <code>==</code> operator considers 0 and <code>\"0\"</code> equal, which is not good in most cases.</p>\n\n<p>It does not matter which of the 3 arrays comes first. The result will always be the same. Therefore it would be nice if the code looked the same for each of the 3 arrays. Your current code looks different for <code>arr3</code>.</p>\n\n<p>I would write the code differently:</p>\n\n<pre><code>function smallestCommonElement(a, b, c) {\n let i = 0, j = 0, k = 0;\n\n while (i &lt; a.length &amp;&amp; j &lt; b.length &amp;&amp; k &lt; c.length) {\n const max = Math.max(a[i], b[j], c[k]);\n\n let same = true;\n while (i &lt; a.length &amp;&amp; a[i] &lt; max) i++, same = false;\n while (j &lt; b.length &amp;&amp; b[j] &lt; max) j++, same = false;\n while (k &lt; c.length &amp;&amp; c[k] &lt; max) k++, same = false;\n\n if (same)\n return a[i];\n }\n return null;\n}\n</code></pre>\n\n<p>The idea is to start at the beginning of the arrays. In each step, look at the current values and find the maximum number. Advance each array to this maximum number. If none of the 3 arrays has been advanced, this means that the current values from all the arrays must be the same. In that case, return this value. Otherwise the values must be different, so try again. Do all this until one of the arrays is at the end, in which case there is no common element.</p>\n\n<hr>\n\n<p>Looking again at your code, there is a bug. Given the arrays <code>[2, 3], [2, 3], [3]</code>, your code will return <code>'No equal number'</code> even though the 3 appears in each array. Using a debugger (or pen and paper), you should step through your code to see where the bug is.</p>\n\n<p>It's an edge case, and it happens in the part of the code that differs from the other parts. That's why I suggested that the code for all 3 arrays should look the same. It's one less chance of introducing bugs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T12:56:06.823", "Id": "429026", "Score": "2", "body": "I would change `let n = 0;` to `let same=1;` and instead of `n++;` do `same=0;`. Then `if (n === 0)` becomes `if (same)`. This clearly tells what the variable does." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T16:09:59.977", "Id": "429050", "Score": "0", "body": "@Zizy thanks for the remark, I improved the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T19:06:27.347", "Id": "429089", "Score": "2", "body": "[`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) can take more than 2 numbers :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T23:16:50.637", "Id": "429121", "Score": "0", "body": "@hjpotter92 Thanks for the remark, the code is getting better with each revision :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T16:47:30.287", "Id": "221730", "ParentId": "221724", "Score": "15" } }, { "body": "<p>Well, you have one huge bug in the code. You have <code>return …</code> as the last line of the <code>while(1)</code> loop. This <code>return</code> will be hit the moment first <code>arr1</code> and <code>arr2</code> elements match but <code>arr3</code> does not contain that element. I suggest you to use Roland's approach as it works and keeps your general algorithm the same.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T12:51:59.823", "Id": "221779", "ParentId": "221724", "Score": "4" } }, { "body": "<p>An easier way is to use JavaScript's Array.includes, Array.some and/or Array.find methods</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>let arr1 = [1, 3, 11, 32, 44, 99]\nlet arr2 = [4, 12, 15, 99]\nlet arr3 = [4, 11, 13, 15, 23, 43]\n\nfunction searchThreeSameNum (arr1, arr2, arr3) {\n return arr1.find(number =&gt; {\n return arr2.includes(number) &amp;&amp; arr3.includes(number)\n })\n}\n\nconst result = searchThreeSameNum(arr1, arr2, arr3)\nconsole.log(result)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T07:51:17.503", "Id": "429153", "Score": "0", "body": "This is probably the simplest possible answer. I'd write it as `const searchThreeSameNum = (arr1, arr2, arr3) => arr1.find(number => arr2.includes(number) && arr3.includes(number))` though" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T14:10:59.130", "Id": "221782", "ParentId": "221724", "Score": "5" } }, { "body": "<p>Sometimes it is worth generalizing an algorithm to handle an arbitrary number of inputs. Not always, of course, but at least the exercise of thinking about how you would generalize an algorithm can force you to consider whether there is any unnecessary code duplication---this might be the algorithmic analogue of looking for <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants\" rel=\"nofollow noreferrer\">magic constants</a>.</p>\n\n<p>It turns out that, with the exact same number of lines of code, you can make a <code>smallestCommonElement</code> function that takes any number of arrays as arguments.</p>\n\n<p>This has a time complexity at least as good as the original. Without having done a careful analysis, if there are <span class=\"math-container\">\\$k\\$</span> arrays of lengths <span class=\"math-container\">\\$n_1,\\dots,n_k\\$</span>, then it seems to run in <span class=\"math-container\">\\$O(n_1 + \\dots + n_k)\\$</span> time. (The index into a given array is guaranteed to increase at least once every two iterations of the main loop.) The original seems to have time complexity <span class=\"math-container\">\\$O((n_1 + n_2)n_3)\\$</span>.</p>\n\n<p>This code uses Roland's idea of using <code>while</code> loops to step indices forward for each array and Kiko Software's suggestion to avoid the <code>while(1)</code>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/* Takes sorted numerical arrays as arguments, returns the smallest\n common element between them or null. */\nfunction smallestCommonElement(/*arguments*/) {\n // Indices into the given arrays\n let indices = Array(arguments.length).fill(0);\n // The current possible smallest common element\n let cur_val = -Infinity;\n\n do {\n var same = true;\n for (let i = 0; i &lt; arguments.length; i++) {\n // Step an array forward to cur_val (or beyond if the array\n // doesn't have cur_val)\n while (indices[i] &lt; arguments[i].length &amp;&amp; arguments[i][indices[i]] &lt; cur_val) {\n indices[i]++;\n }\n if (indices[i] &lt; arguments[i].length) {\n if (arguments[i][indices[i]] &gt; cur_val) {\n // We went past cur_val, so record in 'same' that cur_val does\n // not represent the smallest common element this time through.\n same = false;\n cur_val = arguments[i][indices[i]];\n }\n } else {\n // We got to the end of this array, so there is no smallest common element.\n return null;\n }\n }\n } while (!same);\n\n return cur_val;\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": "2019-06-06T17:48:19.210", "Id": "221798", "ParentId": "221724", "Score": "2" } } ]
{ "AcceptedAnswerId": "221730", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T14:51:34.350", "Id": "221724", "Score": "11", "Tags": [ "javascript", "array" ], "Title": "Check if three arrays contains the same element" }
221724
<h2>Description</h2> <p>I had to create a dictionary structure where one value can be referenced by several keys.</p> <p>For example the keys <code>a</code>, <code>b</code>, <code>c</code> reference the value 1 and <code>d</code>, <code>e</code> reference the value 2. If two groups of keys intersect then I want to merge them, for example the group <code>a</code>, <code>b</code> and <code>b</code>, <code>c</code> should result to <code>a</code>, <code>b</code>, <code>c</code>.</p> <p>I also need an efficient solution:</p> <ul> <li>linear time for creation (init) - <span class="math-container">\$O(n)\$</span>.</li> <li>constant time for access (update and get) - <span class="math-container">\$O(1)\$</span></li> <li>no need for inserting and delete since I have the final list of keys at the init</li> </ul> <p>I'm come from Java world and I'm not totally confortable with the Python philosophy so I think some review could be useful.</p> <h2>Main code</h2> <pre><code>from collections.abc import Mapping from typing import Iterator, Set, FrozenSet, AbstractSet, ValuesView, Tuple class MultiKeysDict(Mapping): """ Dictionary to manage multiple key to one value. The keys groupes should be set at the initialization and can't change later. If two keys groupes share a key so they will reference the same value. """ class Value: """ Store the value data """ def __init__(self, default_value): self.data = default_value def __init__(self, grp_keys: Set[FrozenSet], default_value = None): """ Create a dictionary based keys groups. Every group will share the same value. Intersected group will share the same value. :param grp_keys: The groups of keys. :param default_value: The default value. """ self._storage = dict() self._values = set() # Build all keys reverse_dict = dict() # For groupe merging for keys in grp_keys: refs = set() for key in keys: if key in self._storage: refs.add(self._storage[key]) # New group of keys if not refs: new_value = MultiKeysDict.Value(default_value) self._storage.update(dict.fromkeys(keys, new_value)) reverse_dict[new_value] = set(keys) self._values.add(new_value) # Extend an existing group of keys elif len(refs) == 1: old_value = refs.pop() self._storage.update(dict.fromkeys(keys, old_value)) reverse_dict[old_value].update(keys) # Merge several group of keys (troubles start here) else: old_value = refs.pop() keys_to_merge = [key for ref in refs for key in reverse_dict[ref]] self._storage.update(dict.fromkeys(keys_to_merge, old_value)) reverse_dict[old_value].update(keys_to_merge) # Remove merged references for ref in refs: del reverse_dict[ref] self._values.discard(ref) def __getitem__(self, k): return self._storage[k].data def __setitem__(self, key, value): self._storage[key].data = value def __len__(self) -&gt; int: return len(self._values) def __iter__(self) -&gt; Iterator: return (value.data for value in self._values) def keys(self) -&gt; AbstractSet: return self._storage.keys() def values(self) -&gt; ValuesView: return [value.data for value in self._values] # Should be ValuesView type? def items(self) -&gt; AbstractSet[Tuple]: return {(key, self.__getitem__(key)) for key in self.keys()} </code></pre> <h2>Some tests</h2> <pre><code>import unittest from tools.multikey_dict import MultiKeysDict class TestMultiKeyDict(unittest.TestCase): def test_basic_init(self): # Expected: [a, b] [c, d] [e, f, g] d = MultiKeysDict({ frozenset({'a', 'b'}), frozenset({'c', 'd'}), frozenset({'e', 'f', 'g'}) }) d['a'] = 42 d['c'] = 'lolilol' d['f'] = [1, 2, 3] # [a, b] self.assertEqual(d['a'], d['b']) self.assertEqual(d['b'], 42) # [c, d] self.assertEqual(d['c'], d['d']) self.assertEqual(d['d'], 'lolilol') # [e, f, g] self.assertIs(d['e'], d['f']) self.assertIs(d['e'], d['g']) self.assertEqual(d['f'], [1, 2, 3]) def test_intersection_init(self): # Expected: [a, b, c] [d, e] d = MultiKeysDict({ frozenset({'a', 'b'}), frozenset({'b', 'c'}), frozenset({'d', 'e'}) }) d['a'] = 1 d['d'] = 2 # [a, b, c] self.assertEqual(d['b'], 1) self.assertEqual(d['c'], 1) self.assertIs(d['a'], d['c']) # [d, e] self.assertIs(d['d'], d['e']) def test_merge_init(self): # Expected: [a, b, c, d] [e, f] d = MultiKeysDict({ frozenset({'a', 'b'}), frozenset({'c', 'd'}), frozenset({'b', 'c'}), frozenset({'e', 'f'}) }) d['a'] = 1 # [a, b, c, d] self.assertEqual(d['a'], 1) self.assertEqual(d['b'], 1) self.assertEqual(d['c'], 1) self.assertEqual(d['d'], 1) </code></pre> <p>The code seems to work as expected but I'm not sure about my implementation, especially the <code>values()</code> and <code>items()</code> part.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T20:26:55.217", "Id": "428942", "Score": "1", "body": "Code well organised, docstring, type annotations & unit-tests. You have great habits already!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T11:50:24.653", "Id": "429018", "Score": "0", "body": "When you say you need it to run in \\$O(n)\\$ time what do you mean, creation, indexing, iterating, finding the length? Can one of these be faster - like indexing, and length are \\$O(1)\\$ in my answer. And can one be slower, creation can be \\$O(n^2)\\$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T12:47:16.883", "Id": "429024", "Score": "0", "body": "@Peilonrayz I edited the question to make it clearer. I think my current code respect these criteria." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T12:53:50.510", "Id": "429025", "Score": "0", "body": "@Opsse I've re-read your `__init__` and it looks like it runs in \\$O(n^2)\\$ time. This is as `refs` worst case can be `grp_keys`, meaning that you have both an outer and inner loop looping over `grp_keys`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T13:15:19.087", "Id": "429031", "Score": "0", "body": "@Peilonrayz Yes you are right I didn't see this one." } ]
[ { "body": "<ol>\n<li><code>collections.abc.Mapping</code> is meant to be <em>immutable</em>. You want <code>MutableMapping</code>.</li>\n<li>The result from <code>list(d)</code> is <em>unpythonic</em>, it's standard to return the same as <code>Mapping.keys</code>.</li>\n<li>You default all values to <code>None</code>, this smells really fishy to me. This means on an empty dictionary it says it's full, it also means <code>d[key]</code> magically returns <code>None</code>. And <code>key in d</code> is always <code>True</code>.</li>\n<li>Personally I'd create two dictionaries, the first would translate from known keys to the <code>frozenset</code>. The second would be the the actual dictionary with the keys as the <code>frozenset</code>.</li>\n<li><p>It's a bit strange to me that you'd pass poorly constructed sets to <code>MultiKeysDict</code>, but it's possible to have it merge the keys provided. However this runs in <span class=\"math-container\">\\$O(n^2)\\$</span> time. I provided this as a <code>classmethod</code>.</p>\n\n<p>If you prefer it to run on all creations then you can just change the call slightly and call it from <code>__init__</code>.</p></li>\n</ol>\n\n<pre><code>import collections\n\n\nclass MultiKeysDict(collections.abc.MutableMapping):\n def __init__(self, translations):\n self._data = {}\n self._translations = {\n k: set_\n for set_ in translations\n for k in set_\n }\n\n @classmethod\n def from_overlapping(cls, sets):\n handled = set()\n for set_ in sets:\n to_merge = {s for s in handled if s &amp; set_}\n for s in to_merge:\n handled.remove(s)\n set_ |= s\n handled.add(set_)\n return cls(handled)\n\n def _translate(self, key):\n if key not in self._data:\n key = self._translations[key]\n return key\n\n def __getitem__(self, key):\n return self._data[self._translate(key)]\n\n def __setitem__(self, key, value):\n self._data[self._translate(key)] = value\n\n def __delitem__(self, key):\n del self._data[self._translate(key)]\n\n def __iter__(self):\n return iter(self._data)\n\n def __len__(self):\n return len(self._data)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T08:01:17.240", "Id": "428986", "Score": "0", "body": "I will take a look about `MutableMapping` and `list(d)`. About the `None` issue I'm not sure to get it. The `in` condition will return `True` if the key is set and `False` if not, which seems to be the [standard behaviours](https://docs.python.org/3/reference/expressions.html#in) for `dict`, no ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T08:39:47.450", "Id": "428989", "Score": "0", "body": "About the implementation you suggest, I think this doesn't fit the keys intersection case that I explained in the description (or I misunderstood something). This raise a `KeyError` in my second unit test for `self.assertEqual(d['c'], 1)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T10:33:25.880", "Id": "429004", "Score": "0", "body": "@Opsse `d = {}; 'a' in d is False; d['a']` results in an index error. Yours results in `'a' in d is True; d['a'] is None`. This is non-standard and frankly bizarre behavior. As for the second aspect yes, I'll fix that in a bit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T13:03:01.827", "Id": "429029", "Score": "0", "body": "I agree that it makes more sense to move the key merging logic out of the init, I will do the same. I understand your point about the `None` default, but in my use case I need to set a default value that I will update later. So maybe I should make the default value mandatory at the init." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T13:10:32.187", "Id": "429030", "Score": "0", "body": "@Opsse You are free to ignore my advice. I've said what is standard and normal usage, if you want to divert from that, then that's up to you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T13:18:43.017", "Id": "429032", "Score": "0", "body": "Actually I listened you advice, I suggested to remove the `None` for a mandatory default value." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T20:14:23.230", "Id": "221745", "ParentId": "221725", "Score": "9" } }, { "body": "<p>At first glance, your code looks quite good. I would like to share some of my thoughts with you nevertheless.</p>\n\n<ol>\n<li>Some variable names could be improved to make the code more readable. For instance <code>grp_keys</code>, seems to hint towards keys to groups. To me it would be more intuitive if the name was something like <code>key_groups</code>, which does sound more what you actually want from the user. One can likely argue about this. The name <code>self._storage</code> is also quite generic.</li>\n<li>There should be no whitespace around the <code>=</code> when used for keyword arguments, i.e. <code>default_value=None</code> instead of <code>default_value = None</code> (<a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">relevant PEP8 section</a>)</li>\n<li>Some of the comments could use a second look. E.g. <code>groupes</code> should likely be <code>groups</code> and there are a few sentences that don't make much sense, e.g. <code>Every group will share the same value. Intersected group will share the same value.</code> should likely be <code>Every key of a group will share the same value. Intersecting groups will also share the same value.</code></li>\n<li>Using <code>Set[FrozenSet]</code> to initialize your class might be overly restrictive. Your code should work fine with other sequence types and likely even iterables.</li>\n</ol>\n\n<hr>\n\n<p>It took me quite some time to understand what's going on in <code>__init__</code>. While thinking about an alternative solution I arrived at something similar to <a href=\"https://codereview.stackexchange.com/users/42401/peilonrayz\">@Peilonrayz'</a> <a href=\"https://codereview.stackexchange.com/a/221745/92478\">answer</a>. <s>so I won't duplicate that. Using this approach invalidates the last point mentioned above and you should stick with your current approach.</s> My approach can be found below. I'm not sure if it meets your complexity requirements, but it did pass your tests.</p>\n\n<p><strong>A word of warning:</strong> As @Peilonrayz rightfully pointed out in a comment, the presented implementation will fail for cases like <code>MultiKeysDict([frozenset('ab'), frozenset('cd'), frozenset('bc')])</code>. The changes need to fix that would lead to what he presented in his answer.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class MultiKeysDict(Mapping):\n \"\"\"\n Dictionary to manage multiple key to one value.\n The keys groups has to be set at initialization and can't change later.\n If two keys groups share a key they will reference the same value.\n \"\"\"\n\n class Value:\n \"\"\"\n Store the value data\n \"\"\"\n\n def __init__(self, default_value):\n self.data = default_value\n\n def __repr__(self):\n return f\"Value({self.data!r})\"\n\n def __init__(self, key_groups: Set[FrozenSet], default_value=None):\n \"\"\"Create a dictionary based on key groups.\n\n Every key in a group will share the same value.\n Intersecting groups will also share the same value.\n\n :param key_groups: The groups of keys.\n :param default_value: The default value.\n \"\"\"\n self._proxy = dict()\n self._data = dict()\n\n current_group_id = 0\n for keys in key_groups:\n known_keys = keys.intersection(self._proxy.keys())\n if known_keys: # merge\n key = next(iter(known_keys))\n self._proxy.update(dict.fromkeys(keys, self._proxy[key]))\n else:\n self._proxy.update(dict.fromkeys(keys, current_group_id))\n self._data[current_group_id] = MultiKeysDict.Value(default_value)\n current_group_id += 1\n\n def __getitem__(self, key):\n return self._data[self._proxy[key]].data\n\n def __setitem__(self, key, value):\n self._data[self._proxy[key]].data = value\n\n def __len__(self):\n return len(self._data)\n\n def __iter__(self):\n return iter(self._data)\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T08:57:00.090", "Id": "428991", "Score": "0", "body": "I agree with most of your points, I will fix it. I can only argue about `Set[FrozenSet]`, I don't think I can make it less restrictive since `Set[Set]` is not possible (only `FrozenSet` is hashable). And other collection type would be too generic because I don't want duplicated value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T08:58:08.023", "Id": "428992", "Score": "0", "body": "About Peilonrayz answer I think it doesn't work. I explained why in comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T09:31:53.603", "Id": "429000", "Score": "0", "body": "Maybe I will have another look at my approach once I get back home and add it to the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T19:12:52.860", "Id": "429091", "Score": "0", "body": "@Opsse: I added my approach to the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T20:03:40.293", "Id": "429103", "Score": "0", "body": "FYI `MultiKeysDict([frozenset('ab'), frozenset('cd'), frozenset('bc')])._proxy == {'a': 0, 'b': 0, 'c': 0, 'd': 1}`. d should also be 0. (Note the input is a list to force this output)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T20:33:08.563", "Id": "429105", "Score": "0", "body": "@Peilonrayz: Good catch!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-07T08:47:31.220", "Id": "429173", "Score": "0", "body": "I will use your both code to improve mine, thank you for your time." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T20:34:40.867", "Id": "221746", "ParentId": "221725", "Score": "8" } } ]
{ "AcceptedAnswerId": "221745", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T15:09:55.337", "Id": "221725", "Score": "10", "Tags": [ "python", "python-3.x", "hash-map" ], "Title": "Multi Key dictionary implementation" }
221725
<p>I am creating fake data using <a href="https://github.com/marak/Faker.js/" rel="nofollow noreferrer">faker.js</a>. Out of simplicity I created a for-loop.</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 faker = require("faker") const dataLength = 10 const productArr = [] for (var index = 0; index &lt; dataLength; index++) { productArr.push({ name: faker.commerce.productName(), category: faker.commerce.department(), price: faker.commerce.price(), description: faker.lorem.paragraph(), }) } console.log(productArr.length) console.log(JSON.stringify(productArr))</code></pre> </div> </div> </p> <p>Is there a more elegant solution to iterate through an array that has a fixed length?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T19:09:36.767", "Id": "428930", "Score": "0", "body": "This looks quite elegant to me. However, you're not \"iterating through an array\", you are _creating an array_." } ]
[ { "body": "<p>Since you're iterating for the sole purpose of creating an array, <code>map</code> is <em>somewhat</em> appropriate here.</p>\n\n<pre><code>const productArr = [... Array(dataLength)] // Create a dummy array dataLength elements long\n .map(_ =&gt; ({ // And map over it\n name: faker.commerce.productName(),\n category: faker.commerce.department(),\n price: faker.commerce.price(),\n description: faker.lorem.paragraph(),\n }));\n</code></pre>\n\n<p>I'm mentioning it just in case you aren't aware of <code>map</code>, but it could be argued that this exact usage is an abuse of the function. Really, <code>map</code> is for transforming one list into another list of the same length. In this case though, we're completely ignoring the original contents of the array being iterated over (shown by the fact that the parameter is called <code>_</code>).</p>\n\n<p>I can't say I necessarily recommend <code>map</code> in this case, but I thought I'd mention it.</p>\n\n<p>If however you ever wanted to enumerate the data you're producing, it would be appropriate:</p>\n\n<pre><code>const productArr = [... Array(dataLength).keys()] // [0, 1, 2, 3, ...]\n .map(i =&gt; ({ \n i: i, // And use the parameter this time\n name: faker.commerce.productName(),\n category: faker.commerce.department(),\n price: faker.commerce.price(),\n description: faker.lorem.paragraph(),\n }));\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp\">Resource for the \"range\" on the first line.</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T20:00:30.360", "Id": "221742", "ParentId": "221736", "Score": "3" } } ]
{ "AcceptedAnswerId": "221742", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T18:41:47.840", "Id": "221736", "Score": "0", "Tags": [ "javascript" ], "Title": "More elegant solution to create a array of fake data" }
221736
<p>Classes in Python do not have native support for static properties. A meta-class can rather easily add this support as shown below. Are there any problems programmers might experience if they use this implementation?</p> <pre><code>#! /usr/bin/env python3 class StaticProperty(type): def __getattribute__(cls, name): attribute = super().__getattribute__(name) try: return attribute.__get__(cls, type(cls)) except AttributeError: return attribute def __setattr__(cls, name, value): try: super().__getattribute__(name).__set__(cls, value) except AttributeError: super().__setattr__(name, value) class Test(metaclass=StaticProperty): __static_variable = None @property def static_variable(cls): assert isinstance(cls, StaticProperty) return cls.__static_variable @static_variable.setter def static_variable(cls, value): assert isinstance(cls, StaticProperty) cls.__static_variable = value def __init__(self): self.__value = None @property def value(self): assert isinstance(self, Test) return self.__value @value.setter def value(self, value): assert isinstance(self, Test) self.__value = value def main(): print(repr(Test.static_variable)) Test.static_variable = '1st Hello, world!' print(repr(Test.static_variable)) instance = Test() print(repr(instance.value)) instance.value = '2nd Hello, world!' print(repr(instance.value)) assert Test._Test__static_variable == '1st Hello, world!' assert instance._Test__value == '2nd Hello, world!' if __name__ == '__main__': main() </code></pre> <p>My first inclination is that the <code>property</code> class should be sub-classed as <code>static_property</code> and should be checked for in <code>StaticProperty.__new__</code> to ensure it is being used properly.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T20:38:25.993", "Id": "428945", "Score": "0", "body": "So, to be clear, you want class properties? Properties that are bound to the class not the instance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T20:42:23.467", "Id": "428947", "Score": "0", "body": "@Peilonrayz Yes, but the example code seems to illustrate that both kinds of properties are possible. Some might find it confusing, though, if there is no distinction between a class and instance property." } ]
[ { "body": "<ul>\n<li>You've masked a bug, in <code>__setattr__</code> a property raises an <code>AttributeError</code> if the setter hasn't been defined. This causes you to overwrite the property.</li>\n<li>(As you've said) There's no distinction between a class property and an instance property. You can change it so there is, but it doesn't allow the property to only be defined on the class, not the instance.</li>\n<li>You can just define the static properties on the metaclass. This removes a lot of the headaches.</li>\n<li>If you <em>really</em> want to define everything onto the class not the metaclass then you can make the metaclass hoist the wanted functions into a new metaclass. This means everything works as if you only defined two metaclasses with the properties correctly defined.</li>\n</ul>\n\n<p>No fancy changes:</p>\n\n<pre><code>class MyMeta(type):\n @property\n def class_(self):\n return self._class\n\n @class_.setter\n def class_(self, value):\n self._class = value\n\n @property\n def class_instance(self):\n return self._class_instance\n\n @class_instance.setter\n def class_instance(self, value):\n self._class_instance = value\n\nclass Test(metaclass=MyMeta):\n class_instance = MyMeta.class_instance\n\n @property\n def instance(self):\n return self._instance\n\n @instance.setter\n def instance(self, value):\n self._instance = value\n</code></pre>\n\n<p>Hoisting:</p>\n\n<pre><code>class classproperty(property):\n pass\n\n\nclass classinstanceproperty(property):\n pass\n\n\nclass StaticProperty(type):\n def __new__(self, name, bases, props):\n class_properties = {}\n to_remove = {}\n for key, value in props.items():\n if isinstance(value, (classproperty, classinstanceproperty)):\n class_properties[key] = value\n if isinstance(value, classproperty):\n to_remove[key] = value\n\n for key in to_remove:\n props.pop(key)\n\n HoistMeta = type('HoistMeta', (type,), class_properties)\n return HoistMeta(name, bases, props)\n\n\nclass Test(metaclass=StaticProperty):\n @classproperty\n def class_(self):\n return self._class\n\n @class_.setter\n def class_(self, value):\n self._class = value\n\n @classinstanceproperty\n def class_instance(self):\n return self._class_instance\n\n @class_instance.setter\n def class_instance(self, value):\n self._class_instance = value\n\n @property\n def instance(self):\n return self._instance\n\n @instance.setter\n def instance(self, value):\n self._instance = value\n</code></pre>\n\n<hr>\n\n<p>These both pass the following tests: (I could only get your approach to work with instance and class instance)</p>\n\n<pre><code>\ntest = Test()\ntest._instance = None\ntest.instance = True\nassert test._instance is True\nassert test.instance is True\ntest.instance = False\nassert test._instance is False\nassert test.instance is False\n\nTest._instance = None\nTest.instance = True\nTest.instance = False\nassert Test._instance is None\ntest._instance = True\nif Test._instance is not True:\n print(\"instance can't be used after modifying class\")\n\nTest._class_instance = None\nTest.class_instance = True\nassert Test._class_instance is True\nTest.class_instance = False\nassert Test._class_instance is False\n\ntest = Test()\ntest._class_instance = None\ntest.class_instance = True\nassert test._class_instance is True\nassert Test._class_instance is False\ntest.class_instance = False\nassert test._class_instance is False\n\nTest._class = None\nTest.class_ = True\nassert Test._class is True\nTest.class_ = False\nassert Test._class is False\n\ntest = Test()\ntest._class = None\ntest.class_ = True\nassert test._class is None\nassert Test._class is False\ntest.class_ = False\nassert test._class is None\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T22:58:29.740", "Id": "221753", "ParentId": "221740", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-05T19:56:59.817", "Id": "221740", "Score": "2", "Tags": [ "python", "python-3.x", "meta-programming", "static", "properties" ], "Title": "Python decorator to support static properties" }
221740