text
stringlengths
1
2.12k
source
dict
c#, object-oriented, design-patterns, .net, dependency-injection { DeliverysetFileCopyHandler.Sub, new DeliverysetSubtitleFilesCopyHandler() } }; return new DeliverysetFileCopyHandlerFactory(deliverySetFileCopyHandlers); }); services.AddSingleton<IDeliverysetFileDetectChangesHandlerFactory, DeliverysetFileDetectChangesHandlerFactory>(_ => { var deliverySetFileDetectChangesHandlers = new Dictionary<DeliverysetChange, IDeliverysetFileDetectChangesHandler> { { DeliverysetChange.Video, new DeliverysetVideoFilesDetectChangesHandler() }, { DeliverysetChange.Asset, new DeliverysetAssetsDetectChangesHandler() }, { DeliverysetChange.Subtitle, new DeliverysetSubtitleFilesDetectChangesHandler() } }; return new DeliverysetFileDetectChangesHandlerFactory(deliverySetFileDetectChangesHandlers); }); return services; } } }
{ "domain": "codereview.stackexchange", "id": 44442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, object-oriented, design-patterns, .net, dependency-injection", "url": null }
c#, object-oriented, design-patterns, .net, dependency-injection I put the whole fully compiling code in github. Don't watch repo structured it was copied from bigger solution for code review purposes. link to repo I know that this is a lot of classes and interfaces. But if it was putted in single method in single class it won't be so big. This also my concern if I am not split to much the code. Ps. I'm not asking for an in-depth review of the code and pointing out fixes in each class. Small tips on what to pay attention to and what I can improve in total approach will also very helpful. EDIT: Answer for: BCdotWEB - About the using statements, my bad that I copied it from the temporary repo for code review. In my real solution I have more dlls and they have other namespaces - About splitting by "type". If I understood correctly, you mean entities, enums, events. I've taken it from this repo CleanArchitecture, but I probably misunderstood something. - "SaveDeliveryset" name for method is redundant I agree, it was previous in bigger interface and I forgot refactor it - For getVersionInfo it is probably very bad naming, but as you see I have a problem with that for the whole project - About "IsAllAreEqual" same I forgot to refactor it, because previously I looked for all changes not for every change. Thanks for pointing that - do not call something a "xxxxxxxList". I know that is a bad thing, I will name a plural car, cars. But it is my mistake that I named the entity with plural. About your last paragraph: As you said I use DI and interfaces, because I have some unit tests for it. I am probably doing it so much, because of the Dependency Inversion definition. That I should not instantiate the implementation because it will probably break the Open/Close principle. I really try to stick with rules, but probably I understand them well in some small examples, but totally get lost in real big business scenario which means that I don't understand them :D Answer: Some general remarks:
{ "domain": "codereview.stackexchange", "id": 44442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, object-oriented, design-patterns, .net, dependency-injection", "url": null }
c#, object-oriented, design-patterns, .net, dependency-injection Answer: Some general remarks: What is the point in shoving everything in a namespace called "Library"? All of your usings now are eight characters longer for no reason. Same for the "Persistence" and the "Services" namespaces, which themselves seem to mainly serve as namespaces which contains other namespaces ("Models", "DataServices",...) Your entire structure seems to be splitting up code by "type". Looking at what you present here, I wonder if most of those folders contain more than a handful of files. To me this feels outdated, an old way of working which creates much pointless overhead. These days we tend to group code by "topic", e.g. if your business logic deals with applications and environments, all the code related to one of these gets grouped under a namespace called "Applications" or "Environment", and inside that namespace you can split the files by function (e.g. "Creating" or "Deleting") if the list becomes unwieldy. A "DeliverysetSaverService" which has a "SaveDeliveryset" method feels redundant to me. Call the method "Handle" or "Execute". Same with "_deliverysetVersionInfoByIdRetrieve" and "GetVersionInfo". Why does "deliverysetVersionInfoByIdRetrieve" even need to start with "deliveryset"? Isn't all the code in DeliverysetService about deliverysets? And what is a "Retrieve"? Same for "_deliverySetFileChangesCoordinator" and "GetDeliverysetChangesInfo". "IsAllAreEqual" is very confusingly named. WRT "subtitleFilesList": do not call something a "xxxxxxxList". A collection of cars should be named "cars", not "carsList". Why do you have a class with a plural name: "SubtitleFiles"?
{ "domain": "codereview.stackexchange", "id": 44442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, object-oriented, design-patterns, .net, dependency-injection", "url": null }
c#, object-oriented, design-patterns, .net, dependency-injection Why do you have a class with a plural name: "SubtitleFiles"? Honestly, I get completely lost in the maze that is your code. It feels overly complex to me, very focused on its implementation instead of its function. At several places I notice that if I want to find out what happens in a specific method, I need to go looking at how it it implemented from an interface, only to find a class that itself calls other methods which are also implemented from an interface, etc. I get that you feel you need this for DI and perhaps testability, but at some point it becomes so complex that it is simply not maintainable. I really wonder if some of your code couldn't be significantly simplified by just calling a static class.
{ "domain": "codereview.stackexchange", "id": 44442, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, object-oriented, design-patterns, .net, dependency-injection", "url": null }
python, strings, datetime, regex Title: A function that uses a regex to parse date and time and returns a datetime object Question: The code works, but I think can be simplified, I don't know which specific steps, but my version seems to me quite complicated I build a function that takes a specific string format and returns a datetime.datetime object. This is the string format "Fri Oct 11 15:09:30 GMT+01:00 2019" that I want to convert into a datetime object with this format '%H:%M:%S %d/%m/%Y' (My final goal not in the scope of this question is to convert these strings from a set to calculate the delta time across the samples) import re from datetime import datetime def date_extractor(date_string: str) -> str: #find the day re_day = re.findall(r'\s(\d{2})\s',date_string) #find the time re_hour = re.findall(r'\d{2}:\d{2}:\d{2}',date_string) #find the month re_month = re.findall(r'\s([a-zA-Z]{3})\s',date_string) #find the year re_year = re.findall(r'\d{4}',date_string) #join with the hour join_hour = "".join(re_hour) join_day_month_year = "/".join(re_day+re_month+re_year) combining_string = join_hour +" "+ join_day_month_year #Convert to datetime first date_obj = datetime.strptime(combining_string, "%H:%M:%S %d/%b/%Y") #Convert to string to get the right format date_transformed = date_obj.strftime('%H:%M:%S %d/%m/%Y') #Convert again to datetime date_transformed = datetime.strptime(date_transformed, '%H:%M:%S %d/%m/%Y') #return the final object return date_transformed #testing section base_string = "Fri Oct 11 15:09:30 GMT+01:00 2019" converted_string = date_extractor(base_string) print(f"The converted_string is {converted_string} and it's datatype is {type(converted_string)}" ) Answer: Wow, that's a lot of regexes! "Fri Oct 11 15:09:30 GMT+01:00 2019" ... convert into a datetime object with this format: "%H:%M:%S %d/%m/%Y"
{ "domain": "codereview.stackexchange", "id": 44443, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings, datetime, regex", "url": null }
python, strings, datetime, regex Perfect. You practically gave the concise solution right there. But then you wandered off into a regex for this field and a regex for that field. Let's just use the standard .strptime(): import datetime as dt stamp = "Fri Oct 11 15:09:30 GMT+01:00 2019" fmt = "%a %b %d %H:%M:%S %Z%z %Y" print(dt.datetime.strptime(stamp, fmt)) Once you have a pair of datetime objects, you can simply subtract them to obtain a timedelta object. And you can interrogate that for .total_seconds(). Here is some actual code review. re_hour = re.findall(r'\d{2}:\d{2}:\d{2}',date_string) Please name this re_hms instead, as it clearly has more than just the hour. Also, the .findall() probably isn't the method to prefer, here, given the later need for a clumsy "".join(re_hour) expression.
{ "domain": "codereview.stackexchange", "id": 44443, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, strings, datetime, regex", "url": null }
haskell, error-handling, pattern-matching Title: Stepwise nested pattern mattching with exceptions Question: Background I'm building a lisp-like toy language in Haskell with the following (stripped down) AST: type Lisp = ExceptT Error (StateT Env IO) type PrimOp = [Value] -> Lisp Value data Value -- | any identifier, e.g. "x", "lambda" = VName Name -- | s-expression, e.g. "(x y z)" | VExpr (NonEmpty Value) -- | curried lambda, e.g. "((lambda (x y) (y x)) 123)" -- or even simply "(lambda (x) x)" | VCurry (NonEmpty Name) Value Env -- | primitive / built-in syntactic operations, e.g. "lambda" | VPrimOp PrimOp Part of the language is a primitive operation named lambda: (lambda (<args>...) <value>) -- syntax (lambda (x y) x) -- example: const function ... which gets translated to the following in Haskell AST: VExpr (VName "lambda" :| [VExpr (VName "x" :| [VName "y"]), VName "x"]) ... then evaluated by the primitive operation primLambda, converting it from a s-expression to a curried function: VCurry ("x" :| ["y"]) (VName "x") <env> <- primlambda <above-ast> The Problematic Code Due to various quirks of the language, I cannot write the lambda into the parser. Thus I have ended up with the following implementation of lambda as a VPrimOp: primLambda :: PrimOp primLambda values = do (params, result) <- case values of [params, result] -> pure (params, result) _ -> throwError $ EArgCount "lambda" 2 (length values) names <- case params of VExpr names -> pure names _ -> throwError $ EArgType "lambda" "VExpr" params names' <- forM names $ \case VName name -> pure name name -> throwError $ EArgType "lambda" "VName" name gets (VCont names' result)
{ "domain": "codereview.stackexchange", "id": 44444, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, error-handling, pattern-matching", "url": null }
haskell, error-handling, pattern-matching Obviously there is a repeated pattern here: I'm doing some pattern matching at each of the 3 steps, and calling throwError if the pattern does not match. However, the second and third step looks only at part of the first result, and the third step has to match everything in a list. Is there a more concise way to do this? Answer: After tinkering around, I settled on this solution using optics and some type classes: data Match a b = a :& b infixr 1 :& type family MatchLength (o :: Type) :: Nat type instance MatchLength () = 0 type instance MatchLength (Match a b) = 1 + MatchLength b class MatchOptic o s a | o -> s, o -> a where matchOptic :: Text -> o -> s -> Lisp a instance ( Is k An_AffineTraversal, Is k A_Review, Data s ) => MatchOptic (Optic' k i s a) s a where matchOptic name optic value = either throws pure (matching optic value) where throws _ = throwError (EArgType name (show (toConstr (review optic undefined))) (show (toConstr value))) class MatchOptics o s r | o -> r where matchOptics :: Name -> o -> [s] -> Lisp r instance MatchOptics () s () where matchOptics _ _ [] = pure () matchOptics name _ values = throwError (EArgCount name 0 (length values)) instance ( KnownNat (MatchLength os), MatchOptic o s a, MatchOptics os s as ) => MatchOptics (Match o os) s (Match a as) where matchOptics name (optic :& optics) (value:values) = do result <- matchOptic name optic value results <- matchOptics name optics values `catchError` \case EArgCount n x y -> throwError (EArgCount n (x + 1) (y + 1)) err -> throwError err pure (result :& results) matchOptics name optics [] = throwError (EArgCount name plen 0) where plen = fromIntegral (natVal (Proxy @(MatchLength os)))
{ "domain": "codereview.stackexchange", "id": 44444, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, error-handling, pattern-matching", "url": null }
haskell, error-handling, pattern-matching MatchOptic matches a single Value with an optic (more specifically a Prism), and raises EArgType if the optic does not produce a match. It uses Data to automatically get the constructor of a value (e.g. show (toConstr (Just 1)) == "Just"). MatchOptics matches a list of [Value] with multiple optics, and uses :& as a "polymorphic" list to store the Optics and the matched results. The resulting primLambda code looks like this: primLambda :: PrimOp primLambda values = do names :& result :& () <- matchOptics "lambda" (_VExpr :& simple @Value :& ()) values names' <- mapM (matchOptic "lambda" _VName) names gets (VCont names' result) The code is much more concise and does length-matching and constructor-matching in one step. It also avoids the need to write many different unpackX functions like in @ShapeOfMatter's answer, since optics are automatically generated using template-haskell. The solution can be extended by providing alternative MatchOptic instances. For example, the following instance and expression can be used to match aeson arrays that can also be null: instance Is k A_Fold => MatchOptic (String, Optic' k i s a) s a where matchOptic name (cons, optic) value = maybe throws pure (headOf optic value) where throws = throwError (EArgType name cons "") matchOptic "abc" ("optional array", failing (_Null % to (const Nothing)) (_Array % to Just))
{ "domain": "codereview.stackexchange", "id": 44444, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "haskell, error-handling, pattern-matching", "url": null }
javascript, beginner, google-apps-script Title: Copy and Pasting Values from Spreadsheets Question: Background This code is apart of a library I'm developing for my company. It takes in anywhere from 3 to 5 arguments. All of the code functions properly. To be more specific, a user has data on a spreadsheet that they want copied somewhere else. The first function takes the data the user wants copied and puts it somewhere else on the same sheet in a spreadsheet. The second function takes the data and pastes it on a different sheet within the same spreadsheet. The third and fourth functions are the ones that I expect to be used most often. They copy and paste data from one spreadsheet to another spreadsheet. They are the more complex of the methods within this function. The reason there are two of them is because the format of the range can either be in array or string format. For example: if you wanted to paste data from cell A1 to cell B1, you could set copyRange = 'A1' or copyRange = [1,1,1,1], and then set pasteRange = 'B1' or pasteRange = [1,1]. A caveat though is that if the copyRange is in array format, pasteRange must also be in array format, and vice-versa. Same if either was in string format. Another caveat that may not have been obvious is that copyRange has four indexes, whereas pasteRange only has two. This is because the setValues() function that GAS uses, the size of the data array being copied must be the same size as the data array being pasted to. To avoid user error that the data arrays are not the same size, the third and fourth indexes of the copyRange array are used in place of pasteRange's third and fourth indexes in the getRange() function. For visualization, it looks like this: ss.getRange(pasteRange[0], pasteRange[1], copyRange[2], copyRange[3]).setValues(ss.getRange(copyRange[0], copyRange[1], copyRange[2], copyRange[3]).getValues())
{ "domain": "codereview.stackexchange", "id": 44445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script My Request I've attempted using objects on my own to improve it, but have had trouble implementing them properly. The convention I've followed to improve my code was from this answer, but have been unsuccessful so far in implementing it in this function specifically. Any assistance is appreciated, thank you. My Code //Functions that copy and paste values function copyPasteValues(){ var function1 = function(sheet, copyRange, pasteRange){ let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet) if(Array.isArray(copyRange) && Array.isArray(pasteRange)){ ss.getRange(pasteRange[0], pasteRange[1], copyRange[2], copyRange[3]).setValues(ss.getRange(copyRange[0], copyRange[1], copyRange[2], copyRange[3]).getValues()) //Should there be a typeof check for string here? (Throwing more errors) } else{ ss.getRange(copyRange).copyTo(ss.getRange(pasteRange)) } } var function2 = function(sourceSheet, targetSheet, copyRange, pasteRange){ let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sourceSheet) let sa = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(targetSheet) if(Array.isArray(copyRange) && Array.isArray(pasteRange)){ sa.getRange(pasteRange[0], pasteRange[1], copyRange[2], copyRange[3]).setValues(ss.getRange(copyRange[0], copyRange[1], copyRange[2], copyRange[3]).getValues()) } else{ ss.getRange(copyRange).copyTo(sa.getRange(pasteRange)) } }
{ "domain": "codereview.stackexchange", "id": 44445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script var function3 = function(sourceSheet, targetSheet, spreadsheetID, copyRange, pasteRange){ //Pushing data to another spreadsheet and pasting it to another try{ let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sourceSheet) let sa = SpreadsheetApp.openById(spreadsheetID).getSheetByName(targetSheet) ss.getRange(copyRange).setValues(sa.getRange(pasteRange).getValues()) //Pulling data from another spreadsheet and pasting it } catch(e){ if(e instanceof Error){ let ss = SpreadsheetApp.openById(spreadsheetID).getSheetByName(sourceSheet) let sa = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(targetSheet) ss.getRange(copyRange).setValues(sa.getRange(pasteRange).getValues()) } else{ throw e } } } var function4 = function(sourceSheet, targetSheet, spreadsheetID, copyRange, pasteRange){ //Pushing data from another spreadsheet and pasting it to another try{ if(arrayCheck(copyRange, pasteRange)){ let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sourceSheet) let sa = SpreadsheetApp.openById(spreadsheetID).getSheetByName(targetSheet) sa.getRange(pasteRange[0], pasteRange[1], copyRange[2], copyRange[3]).setValues(ss.getRange(copyRange[0], copyRange[1], copyRange[2], copyRange[3]).getValues()) } //Pulling data from another spreadsheet and pasting it to another } catch(e){ if(e instanceof Error){ let ss = SpreadsheetApp.openById(spreadsheetID).getSheetByName(sourceSheet) let sa = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(targetSheet) sa.getRange(pasteRange[0], pasteRange[1], copyRange[2], copyRange[3]).setValues(ss.getRange(copyRange[0], copyRange[1], copyRange[2], copyRange[3]).getValues()) } else{ throw e } } }
{ "domain": "codereview.stackexchange", "id": 44445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script try{ if(arguments.length === 3){ function1(arguments[0], arguments[1], arguments[2]) } else if(arguments.length === 4){ function2(arguments[0], arguments[1], arguments[2], arguments[3]) } else if(arguments.length === 5){ if(Array.isArray(arguments[3]) && Array.isArray(arguments[4])){ function4(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]) } else{ function3(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]) } } } catch(e){ Logger.log(e) } } Other Relevant Functions function arrayCheck(copyRange, pasteRange){ if(!Array.isArray(copyRange) || !Array.isArray(pasteRange)){ throw 'Ranges must be in array format' } else{ return true } } Updated Version (2/7/2023) Here is an even more updated one that I feel is more legible and understandable, as the previous updated one was just brute forcing it based on argument length. Most of the checks are going to be used for error handling once I feel comfortable with where the program currently sits function copyValues(){ try{ const options = { copy: arguments[0], paste: arguments[1], source: arguments[2] } if(arguments.length >= 4){ options.target = arguments[3] if(arguments.length >= 5){ options.ss_ID = arguments[4] } } if(arrayCheck(options.copy, options.paste)){ switch(true){ case arguments.length === 3: ss = spreadsheet.getSheetByName(options.source) ss.getRange(options.paste[0], options.paste[1], options.copy[2], options.copy[3]).setValues(ss.getRange(options.copy[0], options.copy[1], options.copy[2], options.copy[3]).getValues()) break; case arguments.length === 4: arrayPaste(options.copy, options.paste, spreadsheet.getSheetByName(options.source), spreadsheet.getSheetByName(options.target)) break;
{ "domain": "codereview.stackexchange", "id": 44445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script case arguments.length === 5: let obj = spreadsheetCheck(options.source, options.target, options.ss_ID) arrayPaste(options.copy, options.paste, obj.ss, obj.sa) break; } } else if(stringCheck(options.copy, options.paste)){ switch(true){ case arguments.length === 3: ss = spreadsheet.getSheetByName(options.source) ss.getRange(options.paste).setValues(ss.getRange(options.copy).getValues()) break; case arguments.length === 4: stringPaste(options.copy, options.paste, spreadsheet.getSheetByName(options.source), spreadsheet.getSheetByName(options.target)) break; case arguments.length === 5: let obj = spreadsheetCheck(options.source, options.target, options.ss_ID) stringPaste(options.copy, options.paste, obj.ss, obj.sa) } } } catch(e){ Logger.log(e) } function spreadsheetCheck(source, target, ss_ID){ let ss, sa switch(true){ case SpreadsheetApp.openById(ss_ID).getSheetByName(source) === null: ss = spreadsheet.getSheetByName(source) sa = SpreadsheetApp.openById(ss_ID).getSheetByName(target) break; case SpreadsheetApp.openById(ss_ID).getSheetByName(target) === null: ss = SpreadsheetApp.openById(ss_ID).getSheetByName(source) sa = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(target) break; } return {ss, sa} } function arrayPaste(copy, paste, ss, sa){ sa.getRange(paste[0], paste[1], copy[2], copy[3]).setValues(ss.getRange(copy[0], copy[1], copy[2], copy[3]).getValues()) } function stringPaste(copy, paste, ss, sa){ sa.getRange(paste).setValues(ss.getRange(copy).getValues()) } function arrayCheck(copy, paste){ if(Array.isArray(copy) && Array.isArray(paste)){ return true } else{ return false } }
{ "domain": "codereview.stackexchange", "id": 44445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script function stringCheck(copy, paste){ if(String(copy) === copy && String(paste) === paste){ return true } else{ return false } } } Answer: Review This review pertains to the updated version of the code. Overall the code is bloated and noisy. Even after a clean up it feels wrong (ambiguous) as the try catch implies there are bugs, but the code gives no clue as what they may be. Syntax error! If your code uses strict mode, or is part of a module (both of which should be true) then it will throw a syntax error before it even runs. The reason is that it uses an undeclared variable ss. Keep it simple. Every line of code is a line that needs to be maintained and understood. Each line also contains potential bugs. Less code means code that is easier to maintain, understand, and contains fewer bugs. Code that is not required to complete the task is also known as noise. You have a lot of noisy code. Example: rather than the 13 lines you have for: function arrayCheck(copy, paste){ if(Array.isArray(copy) && Array.isArray(paste)){ return true } else{ return false } } function stringCheck(copy, paste){ if(String(copy) === copy && String(paste) === paste){ return true } else{ return false } } you can use 2 lines that do the same... const arrayCheck = (copy, paste) => Array.isArray(copy) && Array.isArray(paste); const stringCheck = (copy, paste) => String(copy) === copy && String(paste) === paste; Naming If you are forced to use names that are very long (good names are one or two words and less than 20 characters long) then use aliases to reduce the noise. Names need only have semantic meaning within the scope that they exist; this scope gives names context to complete the named semantic meaning. There is no need to give every name a uniqueness across the entire code base.
{ "domain": "codereview.stackexchange", "id": 44445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script Avoid names that have no semantic meaning, e.g. from the code the names ss, sa have no readable meaning, nor conforms to any commonly used abbreviations. Your use of switch statements is adding source noise where none is needed. Using if, else if, else statements will reduce the noise. Personally JS switch is very poorly implemented and provides none of the advantages it does in other languages. Don't use them in JS You have a try catch that only logs the error. This is pointless code. It also makes it harder to debug as the catch will silently hide bugs if you don't have the console open (or in this case the log is consumed by an unknown Logger). Production code should not output to the console or just push thrown exceptions to a log. (this is very amature). Production code should not use try catch to cover unknown bugs Use modern JS. Using arguments is very old school JS, also arguments has some referencing complexities that can be avoided using modern syntax. Use rest parameters when you have an unknown number of arguments. E.g. function copyValues(...args) { The creating and assigning properties to options just adds noise. You don't need all the references to options. You can assign the named variables using destructuring assignment. eg const [copy, paste, source, target, ss_ID] = args; If you return an array from spreadsheetCheck you can then use a spread operator to call paste. eg stringPaste(copy, paste, ...spreadsheetCheck( Semicolons are required in JS, unless you know all the rules of Automatic Semicolon Insertion (ASI) then use semicolons.
{ "domain": "codereview.stackexchange", "id": 44445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script Clean up Because your code is ambiguous, I have had to make some guesses, and thus it is not faithful to your code. This also means that it is longer than it can be. To keep noise levels low I have used common abbreviations for source, copy, check, array, string and target (i.e.src, cpy, chk, arr, str, and trg respectively) The rewrite is 48% the size of your original 92 lines. What would you quote for 100K lines of code compared to 50K lines of code "use strict"; function copyValues(...args){ const arrChk = (cpy, paste) => Array.isArray(cpy) && Array.isArray(paste); const strChk = (cpy, paste) => cpy instanceof String && paste instanceof String; const sheet = spreadsheet, sheetByName = spreadsheet.getSheetByName.bind(sheet); const argCount = args.length; const [cpy, paste, src, trg, ss_ID] = args; if (arrChk(cpy, paste)) { if (argCount === 3) { const ss = sheetByName(src); ss.getRange(paste[0], paste[1], cpy[2], cpy[3]).setValues(ss.getRange(cpy[0], cpy[1], cpy[2], cpy[3]).getValues()); } else if (argCount === 4) { arrayPaste(cpy, paste, sheetByName(src), sheetByName(trg)); } else if (argCount === 5) { arrayPaste(cpy, paste, ...chkSheet(src, trg, ss_ID)); } } else if (strChk(cpy, paste)) { if (argCount === 3) { const ss = sheetByName(src); ss.getRange(paste).setValues(ss.getRange(cpy).getValues()); } else if (argCount === 4) { stringPaste(cpy, paste, sheetByName(src), sheetByName(trg)); } else if (argCount === 5) { stringPaste(cpy, paste, ...chkSheet(src, trg, ss_ID)); } }
{ "domain": "codereview.stackexchange", "id": 44445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script function chkSheet(src, trg, ss_ID) { const id = SpreadsheetApp.openById(ss_ID), openByName = id.getSheetByName.bind(id); if (openByName(src) === null) { return [sheetByName(src), openByName(trg)]; } if (openByName(trg) === null) { return [openByName(src), SpreadsheetApp.getActiveSpreadsheet().getSheetByName(trg)]; } return []; } function arrayPaste(cpy, paste, ss, sa){ sa.getRange(paste[0], paste[1], cpy[2], cpy[3]).setValues(ss.getRange(cpy[0], cpy[1], cpy[2], cpy[3]).getValues()); } function stringPaste(cpy, paste, ss, sa){ sa.getRange(paste).setValues(ss.getRange(cpy).getValues()); } }
{ "domain": "codereview.stackexchange", "id": 44445, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, google-apps-script", "url": null }
c++, performance, strings, c++17 Title: String literals concatenation with support for dynamic strings Question: I have implemented a function to concatenate string literals at compile time. Basic requirements: Very simple API. Can be used as a one-liner. Must accept variadic string literals. Highly optimized instruction set, no runtime-overhead. Basically concat("A ", "quick ", "brown ", "fox"); should not differ (much) from writing a single string literal by hand. The function must accept string literals, static strings (for nested calls) and dynamic strings. The resulting type must be deduced from the arguments at compile time. So that N string literals would result in a single contiguous string literal with no dynamic allocations. But if at least one argument is a dynamic string, the function would yield a dynamic string with one allocation at most. C++17. I am sure the code can be implemented to support C++11, but personally I don't have a need for that right now. Implementation: Unfortunately, one can't return raw arrays, so a custom type was introduced. The whole concatenation of variadic literals was facilitated by std::tuple_cat's ability to accept std::array. The string itself is to be accessed via static_cast. Customization point _cast exists to allow user-defined specialization for static_cast from ct_string. This is kind of an experimental approach. One is free to assume that ct_string is a contiguous array of Char of size N. But I don't want to make std::array as a part of specification, since it is mostly used for std::tuple_cat. I added ct_string specializations for tuple traits, since it is static. I am not sure if I need or am expected to implement iterator functions for the class.
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 The Code: Gist: https://gist.github.com/sergio-eld/e903adfa2f3a157a147cb2d8f83f18e5 /** * Standard: C++17 * Constexpr string literals concatenation function. * Accepts both string literals and dynamic strings. * When all the arguments are static will yield a ct_string object evaluated at compile time. * If dynamic strings present, will yield an std::string object using single allocation. * * Return type is deduced from variadic arguments. * * Usage: // Example: // Godbolt: https://godbolt.org/z/rTnnbnozc #include <iostream> int main(){ // static string std::cout << eld::concat("The ", "quick ", "brown ", "fox ", "jumps ", "over ", "the ", "lazy ", "dog") << '\n'; // dynamic string std::cout << eld::concat("The ", std::string("quick "), "fat ", std::string("frog")) << '\n'; using eld::separator; // with separator std::cout << eld::concat(separator{", "}, "John Cena") << '\n'; std::cout << eld::concat(separator{", "}, "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog") << '\n'; } * * TODO: * - char arguments support * - deduction traits for static strings * - (?) non-string arguments with to_string conversion */ #include <cstddef> #include <utility> #include <type_traits> #include <tuple> #include <array> #include <string_view> #include <string> #include <functional> #include <numeric> namespace eld { template <size_t N, typename Char = char> class ct_string; } namespace std { template <size_t N> struct tuple_size<eld::ct_string<N>> : std::integral_constant<size_t, N> {}; template <size_t I, size_t N, typename Char> struct tuple_element<I, eld::ct_string<N, Char>> { using type = Char; }; template <size_t I, size_t N, typename Char> constexpr auto get(const eld::ct_string<N, Char> &str) noexcept -> Char { return str.template get<I>(); }
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 template <typename Char, size_t ... M> constexpr auto tuple_cat(const eld::ct_string<M, Char> &... strs) noexcept; } namespace eld { template <size_t N, typename Char> class ct_string { public: using value_type = Char; template <size_t M> constexpr ct_string(const value_type (&str)[M]) : ct_string(str, std::make_index_sequence<M - 1>()) {} constexpr ct_string(std::array<Char, N> arr) noexcept : _value(arr) {} constexpr ct_string(const ct_string&) noexcept = default; constexpr ct_string(ct_string&&) noexcept = delete; ct_string& operator=(const ct_string&) = delete; ct_string& operator=(ct_string&&) = delete; constexpr auto value() const -> std::basic_string_view<Char> { return {&_value[0], N}; } constexpr size_t size() const noexcept { return _value.size(); } template <size_t I> constexpr value_type get() const noexcept { static_assert(I < N, "Index is out of bounds"); return _value[I]; } template <typename C, size_t ... M> constexpr static auto cat(ct_string<M, C> ... strs) noexcept -> ct_string<(M + ...), C>{ return std::apply( [] (auto... cs) -> ct_string<(M + ...), Char> { return std::array{ cs... }; }, std::tuple_cat(std::tuple_cat(strs._value)...)); } template <typename To> constexpr explicit operator To() const noexcept{ return _cast<To>{}(std::as_const(this->_value)); } friend std::basic_ostream<Char>& operator<<(std::basic_ostream<Char> &os, const ct_string &str){ os << static_cast<std::string_view>(str); return os; } private: // clang requires this! template <size_t M, typename C> friend class ct_string;
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 template <size_t M, size_t ... I> constexpr ct_string(const value_type (&str)[M], std::index_sequence<I...>) noexcept : _value({str[I]...}) {} // customization point for casting array template <typename T, typename...> struct _cast { // would be better to pass as C-array reference instead, not to expose std:array constexpr T operator()(const std::array<value_type, N>&) const noexcept; }; public: /// Internal data representation, not to be accessed or relied upon as a part of specification /// It HAS to be public due to C++20 requirement for an object to be used as a Non-Type Template Parameter const std::array<value_type, N> _value; }; template <size_t N, typename Char> ct_string(const Char (&str)[N]) -> ct_string<N - 1, Char>; template <typename Char, size_t N> ct_string(std::array<Char, N>) -> ct_string<N, Char>; template <size_t N, typename Char> template <typename ... Void> struct ct_string<N, Char>::_cast<std::basic_string_view<Char>, Void...>{ constexpr auto operator()(const std::array<Char, N> &arr) const noexcept -> std::basic_string_view<Char>{ return {arr.data(), arr.size()}; } }; template <size_t N, typename Char> template <typename ... Void> struct ct_string<N, Char>::_cast<std::basic_string<Char>, Void...>{ constexpr auto operator()(const std::array<Char, N> &arr) const noexcept -> std::basic_string_view<Char>{ return {arr.data(), arr.size()}; } }; namespace traits{ // TODO: deduction rules instead template <typename String> struct is_static_string : std::false_type {}; template <size_t N, typename Char> struct is_static_string<ct_string<N, Char>> : std::true_type{};
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 template <typename Char, size_t N> struct is_static_string<Char[N]> : std::true_type{}; template <typename Char, size_t N> struct is_static_string<Char(&)[N]> : is_static_string<Char[N]>{}; template <typename Char, size_t N> struct is_static_string<const Char(&)[N]> : is_static_string<Char[N]>{}; } namespace detail { class _concat { private: using _static_string = std::true_type; using _dynamic_string = std::false_type; template <typename ... Strs> using _string_type = typename std::conjunction<traits::is_static_string<Strs>...>::type; public: template <typename ... Strings> constexpr auto operator()(const Strings &...strs) const noexcept { return _impl(_string_type<Strings...>{}, strs...); } private: template <typename ... Strings> constexpr static auto _impl(_static_string, const Strings &... strs) noexcept { return std::tuple_cat(ct_string(strs)...); } // can it be made constexrp? template <typename ... Strings> static auto _impl(_dynamic_string, const Strings &... strs) noexcept { auto dynamicString = std::string(); dynamicString.reserve((std::size(strs) + ...)); (dynamicString.append(static_cast<std::string_view>(strs)), ...); return dynamicString; } }; } template <typename T> struct separator { T value; }; template <typename T> separator(T) -> separator<T>; template <typename Char, size_t N> separator(const Char(&literal)[N]) -> separator<decltype(ct_string(literal))>;
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 template <typename FirstString, typename ... Strings> constexpr auto concat(const FirstString& first, const Strings& ... strings){ return detail::_concat{}(first, strings...); } template <typename T, typename FirstString, typename ... Strings> constexpr auto concat(separator<T> sep, const FirstString &fs, const Strings &... strs) noexcept{ const auto tupleStrings = std::tuple_cat(std::tie(fs), std::tie(sep.value, strs)...); return std::apply([](auto&& ... strs){ return concat(std::forward<decltype(strs)>(strs)...);}, tupleStrings); } } namespace std { template <typename Char, size_t ... M> constexpr auto tuple_cat(const eld::ct_string<M, Char> &... strs) noexcept{ return eld::ct_string<0, Char>::cat(strs...); } } Example: https://godbolt.org/z/rTnnbnozc #include <iostream> int main(){ // static string std::cout << eld::concat("The ", "quick ", "brown ", "fox ", "jumps ", "over ", "the ", "lazy ", "dog") << '\n'; // dynamic string std::cout << eld::concat("The ", std::string("quick "), "fat ", std::string("frog")) << '\n'; using eld::separator; // with separator std::cout << eld::concat(separator{", "}, "John Cena") << '\n'; std::cout << eld::concat(separator{", "}, "The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog") << '\n'; } I'd be happy to recieve any feedback.
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 Answer: Design review Cool. The idea is good; it’s something I could see myself using. The implementation is sound. In general, cool. I like your requirements, except I would strongly recommend moving to C++20 for a number of reasons. The step from C++17 to C++20 is the biggest leap forward in C++ since the step from C++98/03 to C++11. Once C++20 becomes “the norm”, nobody’s going to want to be stuck writing C++17 anymore. And there are a lot of features C++20 brings that directly impact what you’re trying to do. Like… a lot. Far more than I could list, though I’ll mention some as we go along. If you do want to stick with C++17, that’s fine, but there will be some restrictions and caveats. The biggest issue with your design, and the concept in general, is the confusion that comes with the term “static string”. What… exactly… do you think that means? Do you mean a compile-time string? Because that’s what it sounds like you mean. Or do you mean a string that exists in static storage? Because that’s something completely different. I would advise tightening up your terminology. If you’re going to use “static”, you need to explicitly specify what you mean by it. “Literal”? That’s probably not what you mean: a string literal is a specific syntactic construct in C++, and an array of characters is not a string literal (though a string literal can be converted to an array of characters). “Compile-time”? Maybe. “Constant”? Meh. Really, it’s less important which term you use, than it is to clearly specify what you mean.
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 The main thing I would suggest, from an overall design perspective, is that your focus should be on the static/compile-time/whatever string type… not the concatenation function. When I teach C++, one of my mantras is “if you get the types right, everything else Just Works”. That’s very true here, too. That ct_string type… that is the real magic underlying your code. Everything works because of that type. But because you have focused on the concatenation and not the type, things are little clunky in places. For example, let’s say I do: constexpr auto s = eld::concat("a", "b", "c");. Now what? What can I do with s? Well, I can stream it. I can get its size. I can convert it to string_view, using the non-standard .value(). But that’s about it. Wouldn’t it be cool if I could do stuff like: constexpr auto s = eld::concat("a", "b", "c"); constexpr auto t = eld::concat("d", "e", "f");
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 constexpr auto u = s + t; // u is ct_string{"abcdef"}; constexpr auto c = 'x'; if (std::ranges::find(s, c) != std::ranges::end(s)) std::cout << s << " contains " << c; // If I want a path: auto const path = std::filesystem::path{"/path/to"} / s; // ... and so on... All of the ergonomics above would come from the ct_string class. But okay, let’s say that the ct_string class isn’t the focus here; the concatenation is. Even so, I would suggest a rethink of the concatenation in terms of ct_string. Why? Because: // Assuming: constexpr auto operator""_static_string() -> ct_string; // Probably not possible in C++17. constexpr auto f() -> ct_string { return eld::concat("b"); } constexpr auto sv = std::string_view{"a"}; // All of the following statements should be identical: constexpr auto s = eld::concat("a", "b", "c"); constexpr auto s = "ab"_ct_string + "c"; constexpr auto s = "a" + f() + "c"; constexpr auto s = eld::concat("a", "b") + eld::concat("c"); constexpr auto s = eld::concat(eld::concat("a"), eld::concat("b"), eld::concat("c")); constexpr auto s = sv + eld::ct_string{"bc"}; // This last one is tricky, and may not be possible. The problem is that even // if a string view is a compile-time string view, you need to get the size // into the type system.
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 (There is no practical difference between doing s = concat(a, b, c, d) and s = a + b + c + d at compile-time, but it makes sense to the former at run-time, because there are no intermediary strings created; you can collect all the sizes and allocate the result once. But I find s = a + b + c + d nicer to read, and if you’re doing constexpr auto s = ..., then you know it’s all compile-time, so I’d prefer the nicer format. For cases that could be either compile- or run-time, okay, sure, the function style makes sense.) I do have to point out that this whole venture is technically not even possible in C++17. At least, it’s probably not possible to do it correctly. Observe: auto p = std::make_unique<std::array<char, 5>>(); // ... or read from file, or whatever... (*p)[0] = 'f'; (*p)[1] = 'a'; (*p)[2] = 'k'; (*p)[3] = 'e'; (*p)[4] = '\0'; auto so_called_static_string = eld::ct_string{*p}; // This concatenation can't happen at compile time! It *does* yield a // ct_string object, as your documentation promises... but not one // evaluated at compile-time. You could end up with multiple, recursive // calls to `tuple_cat` creating and copying arrays all happening at // run-time. auto s = eld::concat( eld::separator{" "}, "The", "quick", "brown", so_called_static_string); In C++20, this won’t be a problem because you can simply make the static string constructor(s) consteval. That’s just one of numerous problems that can be solved by ditching C++17, so, again—and, I promise, for the last time (not counting the summary)—I really, really strongly suggest you should do so, and move to C++20. Alright, on to the code review: Code review template <size_t N, typename Char = char> class ct_string; I’m not a fan of this interface. Firstly, I would probably include traits. But even if not, I would put the character type first. So: template <typename Char, typename Traits, std::size_t> class ct_string;
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 In my mind, the size is the least important part of the type, since it’s going to be deduced or calculated 99% of the time. And ordering the parameters like this brings it in line with the standard string types: template <typename Char, typename Traits, std::size_t > class ct_string; template <typename Char, typename Traits, typename Allocator> class std::basic_string; template <typename Char, typename Traits > class std::basic_string_view;
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 Which means you don’t need to remember yet another exception to the “rules” of C++, which is mercifully just one bit less cognitive load you have to carry. Just about the only “downside” of ordering the parameters this way is you can’t sensibly default the size. I mean… you could default it to zero or -1 and it won’t be “wrong”… but it wouldn’t be logical. But in reality, when are you ever going to want to specify the size anyway? It’s not like you’re going to be writing ct_string<4> or ct_string<5> as a matter of course. And you’re certainly never going to write auto s = ct_string<>{}. You’re always going to want the size to be deduced. So who cares if it has no default? (There is also another argument, one that manifests later when you write functions like cat() and have to reverse the arguments: template <typename C, std::size_t... M>. There will (probably) never be a situation where you are dealing with multiple character types at the same time… but there are (as you have found) good reasons to have multiple sizes in one operation. It is traditional in C++ (for practical reasons), when dealing with something that has both a fixed set of arguments and a variable number of arguments, to have the variable set last. That implies the size should be last.) Incidentally, it’s std::size_t. The std:: is not optional. Yes, virtually all compilers/standard libraries include size_t in the global namespace for historical reasons (C compatibility). It’s still not the correct way. namespace std { template <size_t N> struct tuple_size<eld::ct_string<N>> : std::integral_constant<size_t, N> {}; These days, I think the expert consensus is that opening up the std namespace is a code smell. The preferred way to do this would be: template <std::size_t N> struct std::tuple_size<eld::ct_string<N>> : std::integral_constant<std::size_t, N> {};
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 Note, though, that you have only specialized tuple_size for Char as the default char. ct_string<N, char8_t> (or any other character type) does not match this specialization. The specialization of tuple_element is fine, but get() and tuple_cat() are problematic. get() does not correctly handle the reference category, but frankly, there really is no sense specializing it in any case. The tuple/structured binding interface works just fine with get() as a member function. If you want get() to work as an ADL free function, okay, fine, you could do that, too. But if you want std::get() to work for your type… that’s weird because std::get() isn’t a customization point, and, anyway, what you have isn’t correct: aside from the reference category issue, you don’t have support for std::get<T>(). As for std::tuple_cat()… also not a customization point, and, worse, you have changed its behaviour in a surprising way. This is what the documentation for std::tuple_cat() says: Returns: tuple<CTypes...>(celems...). See? std::tuple_cat() explicitly returns a std::tuple. You have hijacked the function, and changed the return type. This will be surprising and infuriating, because a standard pattern for converting anything to a tuple is std::tuple_cat(thing). If that thing happens to be a ct_string, the pattern is broken. Bottom line: don’t specialize std::get() or std::tuple_cat(). Neither are customization points, and anyway, your specializations break the specification’s promises for those functions. On to the ct_string class. template <size_t M> constexpr ct_string(const value_type (&str)[M]) : ct_string(str, std::make_index_sequence<M - 1>()) {}
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 I’m not sure why the index sequence is necessary here. I’m guessing it’s because you’ve written yourself into a corner by making _value const… which is a problem I’ll be mentioning later. It should be possible to just copy the array’s contents into _value. Now, I get that the purpose of this constructor is to convert C-strings—NUL-terminated char arrays. Which means you want "abc", which is char[4] to convert to ct_string<3, char>. But without any constraints, this is a catastrophe waiting to happen. Observe: char uh_oh[100]{}; auto boom = eld::ct_string<3, char>{uh_oh}; What you want is three things: You want to constraint this constructor so that M is less-than-or-equal-to N + 1. If M is less than N + 1, you want to pad out _value with Char{}s. If M equals N + 1, you want to confirm that str[N] is Char{}. constexpr ct_string(std::array<Char, N> arr) noexcept : _value(arr) {} Is this constructor really necessary? And, more importantly, is it really necessary for it to be part of the public interface? (You’ll note that it’s the constructor I exploited above.) constexpr ct_string(const ct_string&) noexcept = default; constexpr ct_string(ct_string&&) noexcept = delete; ct_string& operator=(const ct_string&) = delete; ct_string& operator=(ct_string&&) = delete; Is it really necessary delete the move ops, and copy assignment? What, exactly, about the type does it improve? Does it make it safer? I can’t see how. It just seems to make it more frustrating to use for no real benefit. constexpr auto value() const -> std::basic_string_view<Char> { return {&_value[0], N}; }
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 _value.data() is less cryptic than &_value[0]. But there’s a more fundamental issue that I might as well bring up here: what if N is zero? Now, you can’t have a zero-sized array, but without checking for that, you’re relying on the graces of the compiler to actually error-out, rather than allowing non-standard extensions or whatnot. You’re also hoping that the error messages generated make sense, even though they will be referring to hidden implementation details of the class. You can, though, have a zero-sized string. And that’s where you have problems. Personally, I would make the internal array size N + 1, and add a NUL. This not only solves the zero-sized string problem (because the array size will still be 1), it makes conversion to a C-string trivial. Which can be handy. Finally, there’s no conceivable way this function can fail, so it should probably be marked noexcept. Speaking of which: template <size_t I> constexpr value_type get() const noexcept { static_assert(I < N, "Index is out of bounds"); return _value[I]; }
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 value() can’t conceivably fail but isn’t marked noexcept… get<I>() can conceivably fail, yet is not marked noexcept. I mean, get<I>() can’t fail if it’s constrained to be [0, N), which it is via the static_assert, so there’s no real problem here. I just wanted to point out the way of thinking, as part of the interface design process. The real problem with get() is that it doesn’t respect the reference category. If *this is a non-const lvalue, it should return a non-const lvalue reference… and so on. (Yes, I know your current implementation can’t return a non-const reference… that’s another problem, which we’ll get to.) The proper way to implement get() is to quadruplicate it (and, if you care about volatile octuplicate it… but no one cares about volatile): public: template <std::size_t I> constexpr auto get() & noexcept -> Char& { return _get<I>(*this); } template <std::size_t I> constexpr auto get() const& noexcept -> Char const& { return _get<I>(*this); } template <std::size_t I> constexpr auto get() && noexcept -> Char&& { return _get<I>(std::move(*this)); } template <std::size_t I> constexpr auto get() const&& noexcept -> Char const&& { return _get<I>(std::move(*this)); } private: template <std::size_t I, typename S> static constexpr auto _get(S&& s) noexcept -> decltype(auto) { static_assert(I < N, "Index is out of bounds"); return forward<S>(s)._value[I]; } (C++23 makes this much easier with deducing this.) template <typename C, size_t ... M> constexpr static auto cat(ct_string<M, C> ... strs) noexcept -> ct_string<(M + ...), C>{ return std::apply( [] (auto... cs) -> ct_string<(M + ...), Char> { return std::array{ cs... }; }, std::tuple_cat(std::tuple_cat(strs._value)...)); }
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 There are quite a few issues here. First, as a matter of style, I’m not a fan of the extra space in size_t ... M. That makes the ellipsis look like a binary operator, which makes it look like a fold expression. The almost universal convention is to put the ellipsis with the type: size_t... M. That’s how you’ve written it later (auto... cs), after all. Also as a matter of style, the ellipsis in pack expansions is usually attached to the thing being expanded. In other words, not ct_string<M, C> ... strs, but rather ct_string<M, C>... strs. Again, adding that extra space creates confusion, because now it looks like a fold expression. Again, you do the right thing later (twice: std::array{cs...} and std::tuple_cat(strs._value)...). This because super important when you start using decorators, because ct_string<M, C> && ... strs really looks like a fold expression, while ct_string<M, C>&& ... strs does not. Speaking of which: You are taking all the arguments by value. This is hopefully harmless, if this function always ever runs at compile time. However, as I’ve demonstrated, you can’t be sure of that in C++17. And copying large strings can get expensive. So you should use references to be safe. Now, as for the implementation of this function… it’s really a bit absurd. All you need is something like this: template <typename C, std::size_t... M> static constexpr auto cat(ct_string<M, C> const&... strs) noexcept { auto res = ct_string<(M + ...), C>{}; auto p = res._value.begin(); auto append = [&p](auto&& s) { p = std::ranges::copy(s, p).out; }; (append(strs), ...); return res; }
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 (append(strs), ...); return res; } (That assumes a default constructor for the static string class, which it doesn’t have. If you don’t want one, there are plenty of ways to work around it, though most require an extra, temporary array. Not a big deal since this is supposed to be a compile-time operation.) If ct_string had operator+ it would be even simpler: template <typename C, std::size_t... M> static constexpr auto cat(ct_string<M, C> const&... strs) noexcept { return (strs + ...); } This technically involves a lot of intermediaries, but it’s supposed to be a compile-time op. If there’s any chance it won’t be, I’d go with the first version. But the real problem with this function is that it doesn’t really make any sense as a static member function of the ct_string class. And you know this, because in order to use it later, you have to write: eld::ct_string<0, Char>::cat(strs...). That’s conceptual gibberish. With that line of code, you’re saying that you’re using the concatenation function of a zero-length string on a bunch of strings of any length. … whut ? See, the concatenation function should not be a property of the string size. There is no difference between ct_string<0, char>::cat(...) and ct_string<1, char>::cat(...). No part of the concatenation function has anything to do with N; neither the arguments, the return type, nor the algorithm used. If you had a base class—as in template <std::size_t N, typename Char> class ct_string : public ct_string_base<Char>, then it might make sense to have cat() in the base class (so ct_string_base<Char>::cat(...)). But, really, this seems like something that should be a free function… which, ultimately, it is, in the form of eld::concat(). You’re really kinda going in circles by having both. template <typename To> constexpr explicit operator To() const noexcept{ return _cast<To>{}(std::as_const(this->_value)); }
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 What exactly is this for? I know, I read the bit about the experimental approach to casting. But I honestly can’t see the sense in it. ct_string is a string, n’est-ce pas? That means it should behave as a string—it should be printable, it should have a size, it should have character access, etc.. It should also be convertible to the core vocabulary types for strings in C++, which are: std::string_view; and a (pointer to a) NUL terminated character array; … or, for maximum flexibility and efficiency, both. Once you can do that with a ct_string, you can anything stringy. You don’t need anything else. Okay, but you also want to be able to do some static trickery. It’s a static string, so, sure, why not. But you already have that by way of your specializations of std::tuple_size, std::tuple_element, and get() (although, the latter is currently done incorrectly). const std::array<value_type, N> _value; Don’t make data members const. It’s an anti-pattern. I get that you’re in a bit of a pickle because you want this array to be an implementation detail, but it has to be public. The solution, however, is not to make the array const. That is a halfway-nonfix that only creates other headaches. I would suggest one of two strategies: Insist on the array being an implementation detail by giving it a really ugly name. Yes, even uglier than a single underscore prefix. Name it something like _internal_value_DONT_MESS_WITH_THIS, and maybe even change the name every version bump, so that anyone who tries to use it faces grief. Stop worrying and learn to love it. In other words, drop the underscore and just make that value array part of the public interface. Sure people will be able to change the contents of the string as they please… but why is that a problem anyway? People can already do that for std::string, and it hasn’t ruined that class.
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 If you implement get() properly, people will already be able to access and modify the string anyway, so… what’s the problem? Why do you want it to be immutable anyway? Just because something is static doesn’t mean it has to be constant. In fact, it’s becoming common practice in C++ to do complicated work at compile time, including lots of modifying of values. Even std::string is now constexpr. So I would suggest to forget immutability; it gains you nothing, and if users really want immutable static strings, well, that’s what const is for. namespace traits{ // TODO: deduction rules instead template <typename String> struct is_static_string : std::false_type {}; template <size_t N, typename Char> struct is_static_string<ct_string<N, Char>> : std::true_type{}; template <typename Char, size_t N> struct is_static_string<Char[N]> : std::true_type{}; template <typename Char, size_t N> struct is_static_string<Char(&)[N]> : is_static_string<Char[N]>{}; template <typename Char, size_t N> struct is_static_string<const Char(&)[N]> : is_static_string<Char[N]>{}; } These don’t work. To my knowledge, it is impossible in C++17 to determine whether a string is static or not, for whatever you definition of “static” happens to be. To see how easy these are to break: auto p = std::make_unique<char[]>(3); auto q = reinterpret_cast<char (*)[3]>(p.get()); std::cout << eld::traits::is_static_string<decltype(*q)>::value; auto s = std::make_unique<eld::ct_string<2, char>>(*q); std::cout << eld::traits::is_static_string<decltype(*s)>::value; I suspect you need at least C++20 to verify compile-time strings. class _concat { private: using _static_string = std::true_type; using _dynamic_string = std::false_type;
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 template <typename ... Strs> using _string_type = typename std::conjunction<traits::is_static_string<Strs>...>::type; public: template <typename ... Strings> constexpr auto operator()(const Strings &...strs) const noexcept { return _impl(_string_type<Strings...>{}, strs...); } private: template <typename ... Strings> constexpr static auto _impl(_static_string, const Strings &... strs) noexcept { return std::tuple_cat(ct_string(strs)...); } // can it be made constexrp? template <typename ... Strings> static auto _impl(_dynamic_string, const Strings &... strs) noexcept { auto dynamicString = std::string(); dynamicString.reserve((std::size(strs) + ...)); (dynamicString.append(static_cast<std::string_view>(strs)), ...); return dynamicString; } }; Let’s take a step back and think about what you really want to happen with the concatenation function. What you really want is to vary the return type depending on the arguments. If, and only if, all of the arguments are a type that represents a sequence of characters with a compile-time known size, then you want to return a ct_string. Otherwise, you want to return a std::string. Let’s focus on that first requirement. You want anything where there is a compile-time-known number of elements, and all the elements are char, to be considered a “static string”. That includes: eld::ct_string<3, char> char[3] (technically, char[4] where the last character is NUL, but whatever) std::array<char, 3> std::tuple<char, char, char> struct foo { char a; char b; char c; } (where foo supports the tuple-like interface)
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 (I’m assuming that last one, but it makes sense.) The comment on that last one has an interesting clue: “tuple-like”. If we introduce “tuple-like” as a requirement, we get: eld::ct_string<3, char> char[3] (technically, char[4] where the last character is NUL, but whatever) anything tuple-like: std::array<char, 3> std::tuple<char, char, char> struct foo { char a; char b; char c; } (where foo supports the tuple-like interface)
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 Technically, ct_string is also tuple-like, but I’m keeping it separate because it is the type being focused on here. Now, ct_string is, well, ct_string. char[3] is what you seem to be considering a “static string”. (Again, technically char[4], with the trailing NUL, but whatevs.) char[3] is (implicitly) convertible to ct_string. The other three things aren’t currently convertible to ct_string… but they could be, quite trivially. The conversion is simply to ct_string<std::tuple_size_v<T>, char>, and you fill the internal array with std::make_index_sequence<std::tuple_size_v<T>>() and {get<IndexSequence>(t)...}. In other words: If all the arguments are convertible to ct_string, you want to return a ct_string. Otherwise, a std::string. See, what I’m getting at is that you are not really looking for static strings… whatever you may mean by “static”. What you are really looking for is much simpler. If all the arguments are ct_string or convertible to ct_string, then you want to return a ct_string. So what you need is a trait/concept that returns true for ct_string, T[N] (const or not, where T is a character), and anything that is tuple-like where all the tuple elements are the same (and are characters). That trait represents “convertible to a ct_string”, which suggests the name for it. And the interesting thing is… that’s already your implementation! Your “static” cat() function is just: return std::tuple_cat(ct_string(strs)...);. The only error is that std::tuple_cat() should return a std::tuple(), so you need one more step to convert that tuple to a ct_string. (Or, alternately, not use std::tuple_cat(), and instead have a function like the one I showed above, that just concatenates ct_strings. One last thing to mention. In the “dynamic” implementation, you do: auto dynamicString = std::string(); dynamicString.reserve((std::size(strs) + ...)); (dynamicString.append(static_cast<std::string_view>(strs)), ...);
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 (dynamicString.append(static_cast<std::string_view>(strs)), ...); return dynamicString;
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 Be careful here. When converting stringy things to string_view, you have to watch out for embedded NUL characters. Your conversion from ct_string to string_view does the right thing… this function does not. If one of the strs is a char array with an embedded NUL, it will degrade to a char*, and then string_view will use std::strlen() to determine the length… which will not be the same as the size of the char array. You need to be a little more careful here. You can’t just trust conversion to string_view. You need to detect whether the str is a char* or a char (&)[], and behave differently. Also, you’re not considering that the character type may not be char. template <typename T> struct separator { T value; }; Mmm, I’m not going to go into any of this separator stuff. It’s not a bad idea, but it’s entirely orthogonal to everything else—the static string type, the concatenation, etc.. Basically, I would suggest cutting the separator stuff out entirely for now, getting everything else right, and then worrying adding separator functionality… which will then be fairly trivial. (And you can determine whether it can be done “statically” by checking whether all the strings and the separator value are convertible to ct_string.) template <typename FirstString, typename ... Strings> constexpr auto concat(const FirstString& first, const Strings& ... strings){ return detail::_concat{}(first, strings...); } Your implementation is very close to being a neibloid. I would suggest going all in, and getting all the benefits of neibloids. In other words, your current design is basically this: namespace detail { class _concat { public: template <typename... Strings> /* requires (constraints...) */ constexpr auto operator()(Strings&&... strings) const { // implementation... } private: // ... implementation details ... }; } // namespace detail
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 private: // ... implementation details ... }; } // namespace detail template <typename FirstString, typename... Strings> constexpr auto concat(FirstString&& first, Strings&&... strings) { return detail::_concat{}(std::forward<FirstString>(first), std::forward<Strings>(strings)); } I suggest modifying it to this: namespace detail { class _concat { public: template <typename FirstString, typename... Strings> /* requires (constraints...) */ constexpr auto operator()(FirstString&& first, Strings&&... strings) const { // implementation... } private: // ... implementation details ... }; } // namespace detail inline constexpr auto concat = detail::_concat{}; Which, as you can see, is basically the same. There’s just one less level of indirection, and you get the benefits of concat being an object rather than a function (which is what neibloids are all about). C++20 So, let’s assume that you’re taking my advice and ditching C++17 for C++20. What do you gain? Well, for starters, your ct_string class becomes, basically: template <std::size_t N, typename Char> requires (N < std::numeric_limits<std::size_t>::max()) class ct_string { public: using value_type = Char; template <std::size_t M> requires (M <= (N + 1)) consteval ct_string(value_type const (&s)[M]) { // ... } // any other useful member functions or friends... };
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 // any other useful member functions or friends... }; The magic is the consteval keyword, which makes sure the ct_string class is what you want it to be: a compile-time string class. If you make every method of creating a ct_string consteval, then basically all of the problems with determining whether a string is compile-time or not go away. If it’s a ct_string, it must be a compile-time string. What you could do is create a concept/trait that detects whether a thing is a static string… where “static string” is defined as: knows its size at compile-time, and has only characters. So: ct_string, char[N], std::tuple<char, char>, std::array<char, 3>, and anything that follows the tuple protocol and is all characters. With that, and some helper functions to extract the size and characters, concat() basically becomes: template <string_like S1, string_like... S> requires (std::same<char_type_of<S1>, char_type_of<S>> and ...) constexpr auto concat(S1 const& s1, S const&... s) { if constexpr (is_static_string<S1> and ... and is_static_string<S>) { char_type_of<S1> dummy[1] = {}; auto res = ct_string<(static_string_size_of<S1> + ... static_string_size_of<S>), char_type_of<S1>>{dummy}; // do append as shown previously... return res; } else { auto res = std::basic_string<char_type_of<S1>>{}; res.reserve((std::size(s1) + ... + std::size(s))); (res.append(s1), ..., res.append(to_string_view(s))); return res; } }
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 // You will need: // concept string_like: // Detects anything stringy. Maybe could just check // convertibility to string_view? // trait char_type_of<T>: // Basically std::ranges::range_value_t<T>, except it has to // work even if T is a char* or char const*. // concept is_static_string: // Returns true for ct_string, character arrays, and // anything tuple-like. // trait static_string_size_of<T>: // Basically tuple_size<T>, but has to work for C arrays. // function to_string_view(): // Basically just a cast to string_view, but has to be smart // about C arrays with embedded NULs. As you can see, there’s not much you need, and most of it is pretty easy to hash out. There is one little wrinkle in C++20, and it’s that even with the if constexpr above, you can’t be sure that the function is running at compile-time. That means that you might not be able to make ct_string consteval-only until C++23. I’d have to do more thinking to know if this is a deal-breaker or not. C++23 will bring if consteval, which will completely solve the problem of figuring out whether a given concat() is happening at run-time or compile-time, and then everything will for sure work. I slapped together a simple godbolt to illustrate: https://godbolt.org/z/P8G3YerTn. Note that I made no attempt to make concat() both compile-time and run-time; it’s all compile-time. And I didn’t bother to make any of the concatenation stuff smart enough to do conversions. But you can see that everything in the eld namespace is compile-time only (except for the IOstream stuff, of course). Summary
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 A generalized concatenation function is a good idea. One that is smart enough to do all the concatenation at compile-time whenever possible is even better. You need to nail down your terminology, and clearly decide and define what you mean by a “static” string. If you mean a compile-time string… then C++17 isn’t going to work for you. It will mostly work, but can be broken. Accept the limitations, or move to C++20 (at least). (Personally, I would recommend splitting the difference: move to C++20, because it’s such a massive improvement in everything (the constraints alone will improve your life immensely), and accept that you can’t make a perfect compile-time-only string type until C++23.) Consider putting the focus on the compile-time string class, rather than the concatenation function. As I always say when I teach C++, it’s all about the types; when you get the types right, everything else Just Works. Forget the separator stuff altogether, at least for now. It’s a distraction. If you get everything else working, then it will be trivial to add.
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 Think about what you are trying to accomplish in terms of interfaces and protocols… especially standard ones. You are trying to make a string class… so what does the standard string class interface look like in C++ (for this, you can use std::string_view as a model of what a constant string looks like). You are also trying to make something that can be manipulated at compile-time, and in the type system, so look into what that usually means in C++. (For example, there is the tuple protocol.) Ideally, if ct_string is supposed to be a string, it should be a more-or-less transparently drop-in replacement for std::string or std::string_view. If ct_string is supposed to be a compile-time string that can be manipulated by the type system, then it would be nice if it could be decomposed as a structured binding, converted to a tuple/array, and so on (that doesn’t mean you need to provide all the functions to convert to tuples/arrays… just implement the standard protocols that allow it; like, if ct_string is tuple-like, then you can convert to a tuple with just auto as_tuple = std::tuple_cat(ct_str);, and conversion to arrays is not much harder). Consider making concat() a neibloid. Never override, overload, or specialize functions in std. Specifically, tuple_cat() and get(). (You can specialize classes, when permitted… never functions.) And whenever you do specialize something in std, follow the rules. Don’t make class data members const. Watch out for embedded NUL.
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
c++, performance, strings, c++17 In addition to focusing on the compile-time string type, I would also recommend making a proper test suite, using a proper test framework. Among other things, test: zero-length strings character types other than char strings with embedded NUL that the things you think are compile-time really are compile-time (in your main(), you have a comment stating that the first concat() produces a static string… are you sure?) Happy coding!
{ "domain": "codereview.stackexchange", "id": 44446, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, strings, c++17", "url": null }
python, python-3.x, algorithm, sorting, reinventing-the-wheel Title: A selection sort implemented in Python Question: I'm not proficient at Python. My question is twofold: whether this selection sort algorithm implementation for number lists could be considered clean code (in the sense of being modular and maintainable), and how should I go about making it more Pythonic if necessary. def selection_sort(the_list): for sorted_sublist_end_position in range(0, len(the_list) - 1): smallest_item_position = find_smallest_item_position(the_list, sorted_sublist_end_position) swap(the_list, sorted_sublist_end_position, smallest_item_position) return the_list def find_smallest_item_position(the_list, position_before_unsorted_sublist): current_smallest_item_position = position_before_unsorted_sublist sublist_start_position = position_before_unsorted_sublist + 1 for unsorted_sublist_position in range(sublist_start_position, len(the_list)): if the_list[unsorted_sublist_position] < the_list[current_smallest_item_position]: current_smallest_item_position = unsorted_sublist_position return current_smallest_item_position def swap(a_list, i, j): aux = a_list[i] a_list[i] = a_list[j] a_list[j] = aux print(selection_sort([2, 5, 4])) print(selection_sort([5, 4, 2])) print(selection_sort([])) Potential issues I can think of: Variable names are very long (that would come from my Java background). I guess I could pass a single sublist to the second function, as the sublist start position is implicit, instead of two arguments. Would that make the code more Pythonic? Clean Code says functions should do one thing / be responsible by one thing. So I expect a function for instance to perform a single for. The second function performs both a for and a nested if, however if I extract a sub-function out of it the sub-function name will be just a rephrasing of what the sub-function does, which is not good. Should I go about doing that or is the function good enough as it is?
{ "domain": "codereview.stackexchange", "id": 44447, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, algorithm, sorting, reinventing-the-wheel", "url": null }
python, python-3.x, algorithm, sorting, reinventing-the-wheel Answer: whether this selection sort... could be considered clean code (in the sense of being modular and maintainable) Sorting (especially using a trivial algorithm like selection sort) is a simple thing to implement, so assuming you do it right, you will not need to maintain it in the future, like ever. As for modularity I cannot give any definite answer since there isn't much to work with. There're only 3 functions, and it is unknown how or why you might be using them in the future. It is very well possible that you will not really need those helper functions at all. Potential issues I can think of: Variable names are very long That is true. Your code is very hard to read because the variable names are way too expressive. For example: The loop variables could be replaced with i without losing clarity since it's obvious that you're iterating over array indices current_smallest_item_position explains its purpose in too much detail and could be replaced current_min (it's understood that this is an index from the function itself) sublist_start_position doesn't explain its meaning well and could be replaced with search_from Here's an example of how I'd rewrite your code changing the variable naming only: def selection_sort(lst): for i in range(len(lst) - 1): j = find_smallest_item_position(lst, i) swap(lst, i, j) return lst def find_smallest_item_position(lst, search_after): current_min = search_after search_from = search_after + 1 for i in range(search_from, len(lst)): if lst[i] < lst[current_min]: current_min = i return current_min
{ "domain": "codereview.stackexchange", "id": 44447, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, algorithm, sorting, reinventing-the-wheel", "url": null }
python, python-3.x, algorithm, sorting, reinventing-the-wheel (Notice how I replaced range(0, len(lst) - 1) with range(len(lst) - 1). That is because a starting index of 0 is implied when range receives a single argument.) Looks much more clear now, doesn't it? The find_smallest_item_position function could be improved further by getting rid of current_min = search_after thing and inlining the search_from calculation: def find_smallest_item_position(lst, current_min): for i in range(current_min + 1, len(lst)): if lst[i] < lst[current_min]: current_min = i return current_min I guess I could pass a single sublist to the second function, as the sublist start position is implicit, instead of two arguments. Would that make the code more Pythonic? Are you thinking of doing this instead? def selection_sort(lst): for i in range(len(lst) - 1): j = find_smallest_item_position(lst, i) # old version j = find_smallest_item_position(lst[i:]) + i # new version swap(lst, i, j) return lst That would be a terrible idea. Passing a searched-list and a starting-search-index is a normal thing to do. This version of the code, on the other hand, is not better in terms of readability but is worse in terms of performance since you have to make a (partial) copy of the list on every loop iteration. Clean Code says functions should do one thing / be responsible by one thing While that is true in general, I think you're too strict about this. If you start moving every single statement into a separate function, it'll only be detrimental for your code. IMO, you should only split big functions into smaller functions when you see that it becomes too complicated to reason about or when you realize that some logic could genuinely be reused in multiple places. Your swap function is 100% a poor application of this principle. Notice how I did not include it my rewrite of your code - that is because nobody does that in Python. Instead, you can simply write: lst[i], lst[j] = lst[j], lst[i]
{ "domain": "codereview.stackexchange", "id": 44447, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, algorithm, sorting, reinventing-the-wheel", "url": null }
python, python-3.x, algorithm, sorting, reinventing-the-wheel No function needed at all. Assuming find_smallest_item_position will not be reused elsewhere, I'd say there's no reason to make it a separate function too. And in case you think that your code would look ugly, with enough Python profficiency you could express it in a much more concise manner: def find_smallest_item_position(lst, current_min): return min(range(current_min, len(lst)), key=lambda x: lst[x]) Which leads to a very clean selection_sort implementation: def selection_sort(lst): for i in range(len(lst) - 1): j = min(range(i, len(lst)), key=lambda x: lst[x]) lst[i], lst[j] = lst[j], lst[i] return lst
{ "domain": "codereview.stackexchange", "id": 44447, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, algorithm, sorting, reinventing-the-wheel", "url": null }
c, linked-list Title: singly linked list optimally defined over 17 operations in C [2]? Question: Previous versions of this question First Version Second Version Changes I added these operations: Pop_back Pop_front You are not allowed to insert_sll at the front or back, but only in position i such that 0 < i < n=size-1. I also tested the functions, so everything is working! Thanks in advance for any improvement ideas! #include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node* next; } Node; Node* head = NULL; Node* tail = NULL; Node* create_node(int elm) { Node* node = malloc(sizeof * node), *exits = NULL; if (!node) return exits; node->data = elm; node->next = NULL; return node; } int is_empty_sll() { //O(1) return head == NULL; } int size_sll() { //O(n) int count = 0; Node* last = head; while (last) { count += 1; last = last->next; } return count; } Node* node_k_sll(int k) { // 0-based index int n = size_sll() - 1; if (!is_empty_sll() && (k >= 0 && k <= n)) { int i = 0; Node* node = head; while (i != k) { i += 1; node = node->next; } return node; } else { printf("Out of Index"); Node* node = NULL; return node; } } void append_sll(int elm) { //O(1) Node* cur = create_node(elm); if (!head) { head = cur; } else { tail->next = cur; } tail = cur; } void prepend_sll(int elm) { Node* updated_head = create_node(elm); if (!head) { head = updated_head; tail = head; } else { updated_head->next = head; head = updated_head; } }
{ "domain": "codereview.stackexchange", "id": 44448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list", "url": null }
c, linked-list void insert_sll(int elm, int i) { if (!is_empty_sll()) { int k = 1, size = size_sll(); // we don't prepend, so K > 0 Node* cur = create_node(elm); if (!head) { head = cur; } else { Node* last = head; if (i > 1 && i < size) { // 1 < i < size | 1:prepend, n:append while (k != i) { k += 1; last = last->next; } cur->next = last->next; last->next = cur; } else { printf("Out of Index"); } } } } void delete_sll(int elm) { int n = size_sll(); Node* node = head; if (head->data == elm) { head = head->next; free(node); } else { Node* prev = head; for (int i = 0; i < n; i++) { if (node->data != elm) { prev = node; node = node->next; } else { break; } } prev->next = node->next; free(node); } } int search_sll(int elm) { //O(n) if (!is_empty_sll()) { int i, n = size_sll(); Node* last = head; for (i = 0; i < n; i++) { if (last->data != elm) { last = last->next; } else { break; } } return i; } } void swap_sll(int i, int j) {//O(n) --swap value of position i with j Node* node_i = node_k_sll(i); Node* node_j = node_k_sll(j); int temp = node_i->data; node_i->data = node_j->data; node_j->data = temp; } void print_sll() { Node* trav = head; while (trav) { printf("%d ", trav->data); trav = trav->next; } printf("\n"); }
{ "domain": "codereview.stackexchange", "id": 44448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list", "url": null }
c, linked-list void reverse_sll() { if (!is_empty_sll()) { Node* prev = head; Node* cur = head->next, * next_node = cur; while (next_node) { next_node = cur->next; cur->next = prev; prev = cur; cur = next_node; } head->next = next_node; Node* temp = head; head = tail; tail = temp; } } //void reverse_sll() { // Node* prev = NULL, *cur = head, *next; // while (cur) { // next = cur->next; // cur->next = prev; // prev = cur; // cur = next; // } // head = prev; // Node* temp = head; // head = prev; // prev = temp; //} void clear_sll() { //O(n) while (head) { Node* temp = head; head = head->next; free(temp); } printf("List Cleared!\n"); } Node* get_tail() { // Node* tail = head; // while (tail->next != NULL) { // tail = tail->next; // } return tail; } void rotate_sll(int k) { int size = size_sll(); Node* tail = get_tail(); Node* k_node = node_k_sll(k); tail->next = head; for (int i = 0; i < size; i++) { printf("%d ", k_node->data); k_node = k_node->next; } tail->next = NULL; printf("\n"); } void pop_front_sll() { Node* node = head; head = head->next; free(node); } void pop_back_sll() { int size = size_sll(); int elm = node_k_sll(size - 1)->data; delete_sll(elm); } // void sort_sll() {// //different algorithms // }
{ "domain": "codereview.stackexchange", "id": 44448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list", "url": null }
c, linked-list // void sort_sll() {// //different algorithms // } int main() { prepend_sll(-13); append_sll(1); append_sll(2); append_sll(4); print_sll(); insert_sll(3, 2); print_sll(); prepend_sll(0); print_sll(); printf("size: %d\n", size_sll()); printf("index of 3 is: %d\n", search_sll(3)); delete_sll(2); print_sll(); swap_sll(0, 1); print_sll(); reverse_sll(); print_sll(); append_sll(0); append_sll(-1); print_sll(); rotate_sll(2); pop_front_sll(); print_sll(); pop_back_sll(); print_sll(); clear_sll(); print_sll(); return 0; }
{ "domain": "codereview.stackexchange", "id": 44448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list", "url": null }
c, linked-list Answer: What to mention first? I'll start with interface taking name decoration (xyz_sll) as an indication of trying to create something usable in separate "compilation units". Interface design is not an easy undertaking. You can sidestep the issue and implement an existing interface. With C, the options are somewhat limited: "Collection" interfaces lend themselves very well to OO modelling. Interfaces need documentation! In the code: look how the description for rotate_sll() ended up not included in above question. In C, the definition of an interface belongs in a header file. Tests are valuable. Include them in your questions - where I present a part of the code (for convenience&reference) that I don't want reviewed, I'd state that above and put the code block in a block quote. If it is nice to have a list, it got to be nicer to have more than one: The global variable head doesn't do. Define a type List and pass a value to each and every function but create_sll(); I'm with your choice to not have nodes visible on the client side of the interface. It would necessitate more functions and limit implementation choices. (Keep "global non-client names" to a minimum: declare e.g. create_node() & get_tail() static. Maybe move main() to a separate compilation unit - this would raise the question just where to put "debug support". (Java&Python put some in the main Object contract: toString()/str().)) size_sll() is "the other function" that would benefit from being kept instead of re-established. The other one is get_tail(). Keeping tailup-to-date looks quite a chase without a decent set of (automated!) tests in place: Currently, pop_back_sll() fails to update it. Keeping size instead looks a bit simpler - and helps get_tail() a bit: you can use a "counting loop" instead of checking next. You still need to "chase" all those pointers. There is a memory leak in insert_sll() when size < i. delete_sll() does not check if the node deleted equals tail. (I prefer find over search.)
{ "domain": "codereview.stackexchange", "id": 44448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list", "url": null }
c, linked-list I see one big problem with the interface so far: How will a client use a list? Establish size and use a (missing) get_sll(int position)? Define a function apply_while_sll(int *(handler(int item_value)) to call handler() with every item's value in turn until it returns false?
{ "domain": "codereview.stackexchange", "id": 44448, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, linked-list", "url": null }
c++, entity-component-system Title: Entity Component System written in C++ Question: Below is the core of an entity component system I am working on to learn more c++, the full project can be seen here: https://github.com/williamholm/IBECS. Any feedback is appreciated. The goal of this ECS is to end up with component data being sorted in such a way that for expressions which require multiple component vectors from the same entity have the same index. This is only broken if sets are sorted by different things but I believe there is no solution to that. Also the components of the same Entity Type, which are analogous to structs/classes, must be stored in sequence. Three questions in particular are: Is there a way to generate the tuple in ETData that does not require component types to be default constructable? How can the sparse set implementation be improved? Does it make more sense to move all of TypeSortedSS into EntityManager, and replace mSparses with a tuple of mCDS instead? In order to keep this shorter sorting implementation and derivation of Comp and ET has been left out. Comp.hpp #include "ET.hpp" template<Comp_ID id, typename ComponentType = typename CompInfo<id>::type> struct Comp { using type = ComponentType; static constexpr Comp_ID sortedBy = CompInfo<id>::sortedBy; static constexpr auto sparse = getCompSparse<id>(); static constexpr int noOfETsWithComp = sparse[ET_ID::MAX_ET_ID]; //array of ET_IDs which contain this component - mainly useful for testing static constexpr auto ETsWithComp = isInSparse<id, noOfETsWithComp>(); static constexpr int sortGroup = positionalArray(sortArray(), uniqueElements<noOfUniqueElements(sortArray())>(sortArray()))[id]; };
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system ET.hpp #include "ETInfo.hpp" #include "cosntexprUtility.hpp" template<ET_ID id> struct ET { //which ETs are an ET<id> (not just direct inheritors). static constexpr int noOfInheritors = noOfUniqueElements(getInheritors<id>::value); static constexpr std::array<ET_ID, noOfInheritors> inheritors = uniqueElements<noOfInheritors>(getInheritors<id>::value); //inclusive inheritors - same as inheritors but includes id, usefull for loops ect static constexpr std::array<ET_ID, noOfInheritors+1> incInheritors = concatinate(id,inheritors); //Components static constexpr int noOfComponents = noOfUniqueElements( concatinate(getComponents<id>::value, ETInfo<id>::newComponents)); static constexpr std::array<Comp_ID, noOfComponents> components = uniqueElements<noOfComponents>(concatinate(getComponents<id>::value, ETInfo<id>::newComponents)); //Sparse for getting order of components - used in ETData for ease of use static constexpr std::array<int, MAX_COMP_ID> sparse = CompSparse(components); }; ETData.hpp #include <assert.h> #include "comp.hpp" #include <tuple> template<ET_ID id, int compIndex = 0, int lastComp = ET<id>::noOfComponents - 1> //-1 for easier specialization struct ETDataTupleConstructor { using CompType = Comp<ET<id>::components[compIndex]>::type; static constexpr auto data = std::tuple_cat(std::make_tuple(CompType()), ETDataTupleConstructor<id, compIndex + 1, lastComp>::data); }; template<ET_ID id, int compIndex> struct ETDataTupleConstructor<id, compIndex, compIndex> { using CompType = Comp<ET<id>::components[compIndex]>::type; static constexpr std::tuple<CompType> data = {}; };
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system template<ET_ID id> struct ETData { using type = std::remove_const<decltype(ETDataTupleConstructor<id>::data)>::type; type data; //essentially should be std::get but with comp_id -> component position in ET mapping template<Comp_ID comp_id> constexpr Comp<comp_id>::type& get() { static_assert(ET<id>::sparse[comp_id] != Comp_ID::MAX_COMP_ID); return std::get<ET<id>::sparse[comp_id]>(data); } template<Comp_ID comp_id> constexpr Comp<comp_id>::type&& move()//is move here ok or bad? not clear when using std::get on a member of class. { static_assert(ET<id>::sparse[comp_id] != Comp_ID::MAX_COMP_ID); return std::move(std::get<ET<id>::sparse[comp_id]>(data)); } }; Entity.hpp static constexpr uint32_t maxEntityType = 0xFFF; static constexpr uint32_t maxEntityNumber = 0xFFFFF; static constexpr uint32_t entityValueBits = 20; //with this set up: max 1m entities, 4095 entity types class Entity32Bit { private: uint32_t mEntity; public: constexpr uint32_t number() const noexcept { return mEntity & maxEntityNumber; } constexpr uint32_t type() const noexcept { return (mEntity >> entityValueBits); } constexpr void addType(uint32_t type) noexcept { assert(type <= maxEntityType); mEntity |= (type << entityValueBits); } constexpr void addNumber(const uint32_t entityNum) noexcept { assert(entityNum <= maxEntityNumber); mEntity = entityNum + (this->type() << entityValueBits); } inline bool operator==(const Entity32Bit rhs) const noexcept { return this->number() == rhs.number() && this->type() == rhs.type(); } Entity32Bit() noexcept :mEntity(0) {} constexpr Entity32Bit(const uint32_t entityNumber, const uint32_t type) noexcept : mEntity(entityNumber) { assert(entityNumber < maxEntityNumber); addType(type); } };
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system These two classes together sort data so that in TypeSortedSS mpSS->mEDS[id] is a vector of all entities of the ET_ID, id and mCDS[id] which is a vector of the component data that runs parallel to mpSS->mEDS[id] . TypeSortedSS.hpp #include <vector> #include <assert.h> #include "Entity.hpp" #include "Comp.hpp" class SegSparseSet { private: std::array<std::vector<Entity32Bit>, MAX_ET_ID> mEDS; //Entity Dense Sets std::array<std::vector<uint32_t>, MAX_ET_ID> mSparses; public: inline bool entityInSet(Entity32Bit entity) noexcept { return (mSparses[entity.type()][entity.number()] != _UI32_MAX); } inline std::vector<Entity32Bit>& getEntities(const uint32_t group) { return mEDS[group]; } inline Entity32Bit& getEntity(const ET_ID group, const uint32_t index) { return mEDS[group][index]; } inline uint32_t getIndex(const Entity32Bit entity) { return mSparses[entity.type()][entity.number()]; } inline void changeIndex(const Entity32Bit entity, const uint32_t value) { mSparses[entity.type()][entity.number()] = value; }
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system void addEntity(const Entity32Bit entity) { assert(!entityInSet(entity)); changeIndex(entity, mEDS[entity.type()].size()); mEDS[entity.type()].push_back(entity); } void deleteEntity(const Entity32Bit entity) { assert(entityInSet(entity)); //change last member in group to point to deleted component; changeIndex(*(mEDS[entity.type()].end() - 1), getIndex(entity)); //swapComponent + delete EDS mEDS[entity.type()][getIndex(entity)] = *(mEDS[entity.type()].end() - 1); mEDS[entity.type()].pop_back(); //clear entity in sparse changeIndex(entity, _UI32_MAX); } uint32_t totalSize() { int size = mEDS[1].size(); //mEDS[0] is always empty for (int i = 2; i < MAX_ET_ID; ++i) { size += mEDS[i].size(); } return size; } void resizeSparse(ET_ID id, uint32_t size) { mSparses[id].resize(size); for (int i = 0; i < size; ++i) { mSparses[id][i] = _UI32_MAX; } } uint32_t size(ET_ID id) { return mEDS[id].size(); }
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system SegSparseSet() noexcept :mSparses() { for (int i = 0; i < MAX_ET_ID; ++i) { resizeSparse((ET_ID)i, maxEntityAmount()[i]); } } template<Comp_ID component> SegSparseSet(const Comp<component>& comp) noexcept :mSparses() { for (int i = 0; i < MAX_ET_ID; ++i) { if (Comp<component>::compArray[i] == true) { resizeSparse((ET_ID)i, maxEntityAmount()[i]); } } } }; template<Comp_ID mID, typename CompType = typename Comp<mID>::type> class TypeSortedSS { private: using component = Comp<mID>; std::array<std::vector<CompType>, MAX_ET_ID> mCDS; //component dense set, parallel to mEDS in segSS. SegSparseSet* mpSS; public: //checks to see if entity has this component inline bool validEntityGroup(Entity32Bit entity) noexcept { return (component::sparse[entity.type()] != 0); } void addComponent(Entity32Bit entity, const CompType& data) { assert(validEntityGroup(entity)); mCDS[entity.type()].push_back(data); } void deleteComponent(Entity32Bit entity) { //need to do this check here (atleast in debug) as entity in SharedSS is deleted after components assert(mpSS->entityInSet(entity) && validEntityGroup(entity)); mCDS[entity.type()][mpSS->getIndex(entity)] = *(mCDS[entity.type()].end() - 1); mCDS[entity.type()].pop_back(); } public: inline auto end(ET_ID id) { return mCDS[id].end(); } inline auto begin(ET_ID id) { return mCDS[id].begin(); }
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system inline uint32_t getNoOfET(ET_ID id) { return mCDS[id].size(); } inline std::vector<CompType>& getETComps(ET_ID id) { return mCDS[id]; } inline CompType& getComponent(Entity32Bit entity) { return mCDS[entity.type()][mpSS->getIndex(entity)]; } inline CompType& getComponent(uint32_t eType, uint32_t index) { return mCDS[eType][index]; } inline void addSegmentedSS(SegSparseSet* SS) { mpSS = SS; } inline Entity32Bit getEntity(uint32_t eType, uint32_t index) { return mpSS->getEntity(eType, index); } TypeSortedSS() : mpSS(nullptr) {} }; EntityManager.hpp #include "ETData.hpp" #include "TypeSortedSS.hpp" #include "Entity.hpp" template<int... ints> constexpr auto genTypesForTypeSortedTuple(std::integer_sequence<int, 0, ints...> seq) { return std::tuple<int, TypeSortedSS<(Comp_ID)ints>...>(); } typedef decltype(genTypesForTypeSortedTuple(std::make_integer_sequence<int, MAX_COMP_ID>())) TypeSortedSSTuple; class EntityManager { private: //size of array == number of sorting groups std::array<SegSparseSet,noOfUniqueElements(sortArray())> mSharedSSs; TypeSortedSSTuple mSparses; std::array<uint32_t,MAX_ET_ID> mNextEntityNum; std::array<std::vector<uint32_t>, MAX_ET_ID> mDeletedEntityNum; public: template<Comp_ID component> inline auto& sparse() { return std::get<component>(mSparses); } //for testing
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system template<ET_ID id> Entity32Bit addEntity(ETData<id>& data) { Entity32Bit entity; if (mDeletedEntityNum[id].size() == 0) { assert(mNextEntityNum[id] < maxEntityNumber); entity.addNumber(mNextEntityNum[id]++); entity.addType(id); } else { entity.addNumber(*(mDeletedEntityNum[id].end() - 1)); entity.addType(id); mDeletedEntityNum[id].pop_back(); } //this makes assumption that at least one component of each entity is unsorted. mSharedSSs[0].addEntity(entity); addData(entity, data); return entity; } template<ET_ID id> void deleteEntity(Entity32Bit entity) { removeData<id>(entity); mSharedSSs[0].deleteEntity(entity); mDeletedEntityNum[id].push_back(entity.number()); } private: template<ET_ID id, int index = ET<id>::noOfComponents - 1> void addData(Entity32Bit entity, ETData<id>& data)//go through each component in ET<id> and add data to the correct sparse { //if sorted by itself add entity to the correct sorted SharedSS if constexpr (Comp<ET<id>::components[index]>::sortedBy == ET<id>::components[index]) { mSharedSSs[Comp<ET<id>::components[index]>::sortGroup].addEntity(entity); } std::get<ET<id>::components[index]>(mSparses).addComponent(entity, data.get<ET<id>::components[index]>()); if constexpr (index != 0) { addData<id, index - 1>(entity, data); } }
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system template<ET_ID id, int index = ET<id>::noOfComponents - 1> void removeData(Entity32Bit entity)//go through each component in ET<id> and remove component from the correct sparse { std::get<ET<id>::components[index]>(mSparses).deleteComponent(entity); //if sorted by itself delete entity from the correct sorted SharedSS if constexpr (Comp<ET<id>::components[index]>::sortedBy == ET<id>::components[index]) { mSharedSSs[Comp<ET<id>::components[index]>::sortGroup].deleteEntity(entity); } if constexpr (index != 0) { removeData<id, index - 1>(entity); } } public: //both size functions assume at least one component of each ET is unsorted. inline int size() { return mSharedSSs[0].totalSize(); } inline uint32_t noOfET(ET_ID id) { return mSharedSSs[0].size(id); } //returns an iterator for dense set of the component for ET<id> template<Comp_ID component> inline auto begin(ET_ID id) { return std::get<component>(mSparses).begin(id); } template<Comp_ID component> inline auto end(ET_ID id) { return std::get<component>(mSparses).end(id); }
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system //looks simular to calling by Entity32Bit, however it bypasses looking through the sparse to get index, so is faster if you know index. template<Comp_ID component, typename ReturnType = typename Comp<component>::type> inline ReturnType& getComp(ET_ID id, uint32_t index) { return std::get<component>(mSparses).getComponent(id, index); } template<Comp_ID component, typename ReturnType = typename Comp<component>::type> inline ReturnType& getComp(Entity32Bit entity) { return std::get<component>(mSparses).getComponent(entity); } template<Comp_ID component> inline Entity32Bit getEntity(ET_ID id, uint32_t index) { return mSharedSSs[Comp<component>::sortGroup].getEntity(id, index); } private: template<int index = 1> void addSegmentedSS() { if constexpr (index < MAX_COMP_ID) { std::get<index>(mSparses).addSegmentedSS(&mSharedSSs[Comp<(Comp_ID)index>::sortGroup]); addSegmentedSS<index + 1>(); } return; } public: EntityManager() noexcept : mSharedSSs() { for (int i = 0; i < MAX_ET_ID; ++i) { mNextEntityNum[i] = 1; } addSegmentedSS(); }; }; Example #include "EntityManager.hpp" int main() { EntityManager EM; ET<PHYS_OBJ>::components; //provides array of components for reference //struct containing components of Entity Type OBJ ETData<PHYS_OBJ> physObjData; physObjData.get<STATE>() = 0; physObjData.get<POS3D>() = vec3(1, 2, 3); physObjData.get<SPEED>() = 10; physObjData.get<ORIENTATION>() = vec3(0,1,0); Entity32Bit phyObjEntity = EM.addEntity(physObjData);
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system Entity32Bit phyObjEntity = EM.addEntity(physObjData); //add 1000 PHYS_OBJ for (int i = 0; i < 1000; ++i) { EM.addEntity(physObjData); //note no need to store return if Entity is anonymous } //exmaple to update position by velocity, with unsorted position auto posIter = EM.begin<POS3D>(PHYS_OBJ); auto oriIter = EM.begin<ORIENTATION>(PHYS_OBJ); auto speedIter = EM.begin<SPEED>(PHYS_OBJ); int size = EM.noOfET(PHYS_OBJ); for (int i = 0; i < size; ++i) { posIter[i] += oriIter[i].scalarMulti(speedIter[i]); } //same example but if you have sorted positions EM.sort<POS3D>(PHYS_OBJ); Entity32Bit currentEntity; for (int i = 0; i < size; ++i) { //this retrieves Entity that contiants speedIter[i], //this is a slower way to access data so systems should avoid if possible. currentEntity = EM.getEntity<SPEED>(PHYS_OBJ, i); //as POS3D is now a sorted component you cannot rely on posVecIter[i] belonging to //same entity as ori/speedVecIter[i] EM.getComp<POS3D>(currentEntity) += oriIter[i].scalarMulti(speedIter[i]); } //you can utilize inheritance to update all PHY_OBJ and all things that inherit from it for (const auto ET : ET<PHYS_OBJ>::incInheritors) { int size = EM.noOfET(ET); posIter = EM.begin<POS3D>(ET); oriIter = EM.begin<ORIENTATION>(ET); speedIter = EM.begin<SPEED>(ET); for (int i = 0; i < size; ++i) { currentEntity = EM.getEntity<SPEED>(ET, i); EM.getComp<POS3D>(currentEntity) += oriIter[i].scalarMulti(speedIter[i]); } } } ```
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system Answer: General impression I had a very hard time reading your code. The reasons for this were poor choices of naming things, very little useful documentation for someone who doesn't already know the code well, and lots of rather complex use of templates. I'll elaborate more on these issues below. Answers to your questions Is there a way to generate the tuple in ETData that does not require component types to be default constructable? Yes. The problem is that you have data members, because you want to use decltype, because you didn't know how to concatenate tuple types, but you did know about std::tuple_cat. However, you can concatenate just using types; see this StackOverflow post. This avoids the need for the data member. How can the sparse set implementation be improved? It doesn't look very sparse to begin with: you always resize mSparses[id] to maxEntityAmount()[id]. It even says so in the comment: the first member variable of SegSparseSet is an array of "Dense Sets". Using a hash table you can also get \$O(1)\$ insertion and deletion, and \$O(N)\$ time to iterate over the \$N\$ entries it holds. Of course, it has a higher cost than your SegSparseSet. You could also consider storing the set as a std::vector<bool>, where each bit indicates whether a given entity is in the set or not. If you keep track of the highest entity number in the set, then iterating over the set can be done quite efficiently; especially if it's not sparser than 1 in every 32 numbers being in the set, you will use the same or less memory bandwidth to scan through the items in the set. Does it make more sense to move all of TypeSortedSS into EntityManager, and replace mSparses with a tuple of mCDS instead?
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system If there is a signifcant reduction in the complexity of EntityManager by moving part of that complexity into TypeSortedSS, then I would keep it like it is. Otherwise, if EntityManager is the only user of TypeSortedSS, it might indeed be better to move it into EntityManager. Naming things You are using various ways to abbreviate names in your code, and not all of them are clear. So of them are: Comp. Sure, you are writing an Entity Component System, so it probably means Component. But there are multiple IT-related words starting with "Comp", and the documentation for the STL often used comp to refer to a comparison function object (see std::sort for example). ET. Not a friendly alien of course, but an Entity Type. But many things are types in C++. Entity32Bit is a type as well. Maybe it's better to name it EntityProperties? incInheritors. The abbreviation inc is very commonly used to mean "increment". sparse. Sparse what? A sparse set perhaps? Of what? There are also the similar named functions CompSparse() and getCompSparse(). Why does one "get" and the other doesn't?
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system Avoid unnecessary abbreviations. If you do use them, be very consistent. For example, using ID for "identifier" everywhere is great. Having both SS and SparseSet is not great. Spelling is also important. You are making several spelling mistakes in the comments, but also in function names like concatinate(), which whould be concatenate(). Spelling is not everyones forte, and manually checking spelling is a lot of time. Luckily, there are spell checkers, some even dedicated to spell checking source code, like codespell. Use such a spell checker regularly. If you have a build system with a test target, make sure the spell checker is run as part of the test suite. Documentation Consider documenting every class, member function and member variable using the Doxygen format. This helps others navigate your code, but also will help you in the long run, since in only half a year you will have forgotten a lot of the details of the code you wrote. The Doxygen tools can generate output in HTML, PDF and other formats, and they can check whether you documented all the classes and members. Many IDEs also understand the Doxygen format, and can then show you a synopsis when hovering over or tab completing types, member variables and function. Your use of templates There is nothing wrong with using template; however the way you are using them seems unnecessarily complex. I think the problem stems from the fact that you are decoupling things too much, and also instead of having template parameters be types, a lot of your template parameters are numeric identifiers. If I read the declaration of ETData and want to know what ETData<PHYS_OBJ>::type is, I have to visit several layers of other templates before I could tell you what the type actually is. It would be much nicer if things are visible in one go. For example: struct PhysicsObject { using components = std::tuple<State, Position, Speed, Orientation>; … }; enum class State { … }; …
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system enum class State { … }; … Note the lack of IDs - it's purely types. PhysicsObjects lists the components it is made of using a std::tuple of component types. Now you might think: "but I need those IDs because I need to create arrays to hold the data for each type". This can also be solved using types. Instead of creating an enum listing all the possible components for example, you can write: using AllComponents = std::tuple<State, Position, Speed, Orientation, …>; So now you know that there are std::tuple_size<AllComponents> components in total (no need for a MAX_COMP_ID), and with some work you can get the index for a given type. You can do something similar for entities, and create an AllEntities type. Make range-based for loops possible In your code you have to iterate over positions like so: auto posIter = EM.begin<POS3D>(PHYS_OBJ); auto size = EM.noOfET(PHYS_OBJ); for (decltype(size) i = 0; i < size; ++i) { do_something_with(posIter[i]); } I'd rather be able to write something like: for (auto& position: EM.get<POS3D>(PHYS_OBJ)) { do_something_with(position); } It's not just that you can use a range-based for loop this way, it also enables you to use the std::ranges algorithms on your components. The get() member function should return a range, which is basically just a struct with non-templated begin() and end() member functions. Note that iterating over multiple components simultaneously is very common, so you could make get() take a template parameter pack, and return an object with begin() and end() members that return tuples of references to component data, such that one could write: for (auto& [position, orientation, speed]: EM.get<POS3D, ORIENTATION, SPEED>(PHYS_OBJ)) { position += orientation * speed; }
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
c++, entity-component-system Use std::size for sizes, counts and indices Your code uses both int and uint32_t for sizes. I would at least have expected better consistency. Also, write std::uint32_t instead of uint32_t; the latter is not guaranteed to exist in the global namespace. But even better would be to use std::size_t: it is guaranteed to exist (std::uint32_t is an optional type) and it is large enough to be able to count and index any size array that fits in memory. If you do want to stick with std::uint32_t, consider creating a type alias for it, and use the alias instead. This way, you can easily change it without having to go through your code to replace std::uint32_t with something else, with the added danger that you might have used std::uint32_t for other purposes as well.
{ "domain": "codereview.stackexchange", "id": 44449, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, entity-component-system", "url": null }
python, performance, csv, http, django Title: Faster Django CSV generation for several million database entries Question: I am writing a CSV file generator that's filtering through about seven million database entries (MySQL backend). This part is especially slow and I was wondering if there is a way to make it much faster. I was thinking of wiring to a temp file first before serving it and then deleting the file. The Station.header() returns a list with header names ['a','b','c'], etc. Is there an advantage to this? Is there a better way? def metadata_file(request): """Gets metadata for sensors""" if request.GET.has_key('all'): s101 = Station.objects.all().filter(fwy='101', dir='S', abs_pm__gte=420.80, abs_pm__lte=431.63) s280 = Station.objects.all().filter(fwy='280', dir='S', abs_pm__gte=41.16, abs_pm__lte=56.49) q = s101|s280 response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename="all_stations.csv"' writer = csv.writer(response) writer.writerow(Station().header()) for x in q: writer.writerow(x.line()) return response Answer: 1. Introduction By coincidence, I'm working on a similar problem right now, so here's a chance for me to write up an experiment I ran today, in the hope that it might prove useful. However, the solution presented below is far from ideal (see section 3). 2. The idea Processing your query results through Django's ORM and then through csv.writer is time-consuming. You can speed things up by getting the database to write the query output directly to a file and then serving that file. First, your database user needs to have FILE privilege in order to be able to write files: mysql> GRANT FILE ON *.* TO 'user'@'host';
{ "domain": "codereview.stackexchange", "id": 44450, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, csv, http, django", "url": null }
python, performance, csv, http, django Then you need to run your query with MySQL's INTO OUTFILE clause. You can get the query you need from Django by calling .query.sql_with_params(): from django.db.models import Q s101 = Q(fwy='101', dir='S', abs_pm__gte=420.80, abs_pm__lte=431.63) s280 = Q(fwy='280', dir='S', abs_pm__gte=41.16, abs_pm__lte=56.49) sql, params = Station.objects.filter(s101|s280).query.sql_with_params() Add the INTO OUTFILE clause: sql += ''' INTO OUTFILE %s FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' ''' Pick a place to put the CSV: import os.path csv_path = os.path.join(csv_directory, csv_filename) Run the query: from django.db import connection cursor = connection.cursor() cursor.execute(sql, params + (csv_path,)) Send the file (using StreamingHttpResponse which is new in Django 1.5): from django.http import StreamingHttpResponse response = StreamingHttpResponse(open(csv_path), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=' + csv_filename return response 3. Analysis In my test cases (about a million records) this is around ten times as fast as processing the data through csv.writer in Python. But there are several problems, mostly related to security:
{ "domain": "codereview.stackexchange", "id": 44450, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, csv, http, django", "url": null }
python, performance, csv, http, django This depends on the MySQL server being on the same machine as the Django web server. You can imagine working around this by some kind of reverse proxying but it all gets rather complicated. Granting FILE access to your MySQL user is dangerous because it means that a SQL injection attacker can read and write files on your disk. You might want to create a separate MySQL user just to generate these CSV files, and you'll definitely want to set MySQL's secure_file_priv variable. Even if the attacker can't inject SQL, they may be able to cause your disk to fill up with these temporary files. You need a plan for how they are going to be deleted. (Maybe using the request_finished signal?) You need to find somewhere safe to put them (a directory to which the MySQL database user has write access). 4. Update I did some more timing experiments today, trying out five different ways of generating and downloading the CSV, summarized in the table below: +------+-----------------------+-------+ | | through Django |Direct | | |Streaming|Not streaming|from DB| +------+---------+-------------+-------+ |ORM | 630| 370| N/A| +------+---------+-------------+-------+ |No ORM| 190| 125| 58| +------+---------+-------------+-------+ Notes on the table:
{ "domain": "codereview.stackexchange", "id": 44450, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, csv, http, django", "url": null }
python, performance, csv, http, django Notes on the table: Times are in seconds. This is for a query with a million rows that generates 150 MiB of CSV. "ORM" means that I passed the query results through Django's object-relational mapping system before generating the CSV. "No ORM" means that I avoided this by running a custom SQL query. "Streaming" means that I used a StreamingHttpResponse and generated the CSV one line at a time using a technique I'll describe below. "Not streaming" means that I used the technique described in the Django documentation to generate the CSV. (This involves reading the entire CSV output into memory, which is a bit painful for other processes running on the server.) "Direct" is the technique described in section 2 above, using MySQL's INTO OUTFILE clause. Clearly Django's ORM and Python's csv.writer are both significant bottlenecks. If only the INTO OUTFILE approach weren't so painful! So I would still be interested to see other suggestions for speeding up this operation. 5. Appendix: streaming CSV download Python's csv module doesn't provide an easy way to generate one record at a time, but you can coerce it into doing so like this, using io.BytesIO to capture the output: from io import BytesIO def writerow(row): """Format row in CSV format and return it as a byte string.""" bio = BytesIO() csv.writer(bio).writerow([unicode(r).encode('utf-8') for r in row]) return bio.getvalue()
{ "domain": "codereview.stackexchange", "id": 44450, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, csv, http, django", "url": null }
c++, time-limit-exceeded, pattern-matching Title: Wildcard Matching: LeetCode 44 Question: Follow up post Link to question: Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where: '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Note: The framework provides the class Solution and the method bool isMatch(string s, string p) where you are supposed to implement the solution. I modified the method slightly. class Solution { // Check if there is a match between input s and matching char p. // Note '?' matches any character: bool check(char s, char p) { return (p == '?') || (s == p); } // Check for match on star. // s: Input String // sPos: position in input string. // p: match expression. // pPos: position in match expression. // max: The maximum number of normal characters we need to match against. // This is used to limit the potential length of characters that a // star can match against (as we need at least that many characters // left to match normal characters. bool starMatch(string const& s, int sPos, string const& p,int pPos, int max) { // Max length in s we can match against. int maxLen = s.size() - sPos - max; for (int loop = 0; loop <= maxLen; ++loop) { if (tryMatch(s, sPos + loop, p, pPos + 1, max)) { return true; } } // No matter what size of match we used we did not find // a match to the following part of p. return false; }
{ "domain": "codereview.stackexchange", "id": 44451, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, time-limit-exceeded, pattern-matching", "url": null }
c++, time-limit-exceeded, pattern-matching // Do the actual work of matching. bool tryMatch(string const& s, int sPos, string const& p,int pPos, int max) { while (sPos < s.size() && pPos < p.size()) { if (p[pPos] == '*') { // A star forces a recursive call that will do sub matches // so we can exit. return starMatch(s, sPos, p, pPos, max); } // Otherwise do a single character match. if (!check(s[sPos], p[pPos])) { return false; } ++sPos; ++pPos; --max; } // We can run out of characters in s // But the p expression can still be a `*` as that can match with // zero characters. if (pPos < p.size() && p[pPos] == '*') { ++pPos; } return sPos == s.size() && pPos == p.size(); } public: // Start point bool isMatch(string const& s, string const& p) { std::string save; //save.resereve(s.size()); // Count the maxnumber of normal characters we can match against. // Also remove consecutive '*' as that is meaningless. int max = 0; bool lastStar = false; for (char x: p) { if (x != '*') { ++max; save.append(1, x); lastStar = false; } else if (!lastStar) { save.append(1, x); lastStar = true; } } // Now try and do the match. return tryMatch(s, 0, save, 0, max); } }; The code works. Problem it exceeds the time limit on one of the test cases. s = "abbabaaabbabbaababbabbbbbabbbabbbabaaaaababababbbabababaabbababaabbbbbbaaaabababbbaabbbbaabbbbababababbaabbaababaabbbababababbbbaaabbbbbabaaaabbababbbbaababaabbababbbbbababbbabaaaaaaaabbbbbaabaaababaaaabb" p = "**aa*****ba*a*bb**aa*ab****a*aaaaaa***a*aaaa**bbabb*b*b**aaaaaaaaa*a********ba*bbb***a*ba*bb*bb**a*b*bb"
{ "domain": "codereview.stackexchange", "id": 44451, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, time-limit-exceeded, pattern-matching", "url": null }
c++, time-limit-exceeded, pattern-matching I tried to cheat with: class Solution { public: bool isMatch(string const& s, string const& p) { std::string reg; reg.append("^"); bool seenStar = false; for (auto const& c: p) { if (c == '?') { reg.append("."); seenStar = false; } else if (c == '*') { if (!seenStar) { reg.append(".*"); } seenStar = true; } else { reg.append(1, c); seenStar = false; } } reg.append("$"); return std::regex_match(s, std::regex(reg)); } }; But this also exceeds the time limit. I tried to work out how to use a FSM with a state table but could not work out how to represent *. Answer: Nice code, good identifiers. if (tryMatch(s, sPos + loop, p, pPos + 1, max)) { In starMatch, don't we maybe get to reduce max ? if (tryMatch(s, sPos + loop, p, pPos + 1, max - loop)) { When I look at p = "*aa*ba*a*bb*aa*ab*a*aaaaaa*a*aaaa*bbabb*b*b*aa?aaaaaa*a*ba*...bb" I see a vector of words: ["aa", "ba", "a", "bb", "aa", "ab", "a", "aa?aaa", ...] Here are some ways to exploit that. We wish to find anchors.
{ "domain": "codereview.stackexchange", "id": 44451, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, time-limit-exceeded, pattern-matching", "url": null }
c++, time-limit-exceeded, pattern-matching For each word, scan s to count occurrences of the word. If count is exactly one then word is an unambiguous anchor. Use that to partition into a pair of smaller subproblems. For each word, to treat it as a candidate anchor, compute a list of the word's candidate starting indexes, and find the length of that list. Order words by that length. Use that to drive down the combinatorics. Similar to (2.) but without the concept of a "word". Find the s alphabet and let its size be S. Compute n-grams for both s and p, preserving the input offset. If a p word contains a ?, then emit S entries for it, permitting any possible match. Order both the p and the s lists of n-grams by frequency. Now start treating n-grams as candidate anchors and let a mergesort of the lists drive the combinatorics. It feels like the n-gram indexes should induce a partial ordering, and then we could topo sort the poset. Sorry; not seeing how to get there.
{ "domain": "codereview.stackexchange", "id": 44451, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, time-limit-exceeded, pattern-matching", "url": null }
python, python-3.x, object-oriented, comparative-review, python-requests Title: Excluding attributes entirely vs. setting them to None Question: I am making a program that parses profiles from a website. Some profiles are "public" and others are "private" with limited information. Public profiles contain a lot more data and have ~15 more attributes. Should I have one Profile class and set all unobtainable attributes to None? Or should I have 2 different classes and simply exclude unobtainable attributes if a profile is private? Option #1 import requests from bs4 import BeautifulSoup from dataclasses import dataclass @dataclass class Profile: url: str is_private: bool summary: str = None level: int = None class Parser: def __init__(self): self.session = requests.Session() def get_profile(self, url): resp = self.session.get(url) soup = BeautifulSoup(resp.text, "html.parser") profile_is_private = bool(soup.find("div", {"class": "profile_private_info"})) if profile_is_private: return Profile(url=url, is_private=profile_is_private) summary=soup.find("div", {"class": "profile_summary"}).text, level=int(soup.find("span", {"class": "friendPlayerLevelNum"}).text) return Profile(url=url, is_private=profile_is_private, summary=summary, level=level) parser = Parser() public_profile = parser.get_profile("https://steamcommunity.com/id/afarnsworth") print(public_profile) private_profile = parser.get_profile("https://steamcommunity.com/id/private") print(private_profile) Option #2 import requests from bs4 import BeautifulSoup from dataclasses import dataclass @dataclass class BaseProfile: url: str is_private: bool @dataclass class ExtendedProfile(BaseProfile): summary: str = None level: int = None class Parser: def __init__(self): self.session = requests.Session()
{ "domain": "codereview.stackexchange", "id": 44452, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, comparative-review, python-requests", "url": null }
python, python-3.x, object-oriented, comparative-review, python-requests class Parser: def __init__(self): self.session = requests.Session() def get_profile(self, url): resp = self.session.get(url) soup = BeautifulSoup(resp.text, "html.parser") profile_is_private = bool(soup.find("div", {"class": "profile_private_info"})) if profile_is_private: return BaseProfile(url=url, is_private=profile_is_private) summary=soup.find("div", {"class": "profile_summary"}).text, level=int(soup.find("span", class_="friendPlayerLevelNum").text) return ExtendedProfile(url=url, is_private=profile_is_private, summary=summary, level=level) parser = Parser() public_profile = parser.get_profile("https://steamcommunity.com/id/afarnsworth") print(public_profile) private_profile = parser.get_profile("https://steamcommunity.com/id/private") print(private_profile) Both options seem to have downsides. In option #1, the function returns a Profile object that might have over 15 attributes set to None because the profile was private and they couldn't be obtained. In option #2, the function returns an entirely different object each time. So the user would have to manually check which object the function returned--either BaseProfile or ExtendedProfile Which is better practice for a public API? Or are there better alternatives for these kind of designs. Answer: Definitely avoid #1. Something something billion dollar mistake: if you don't need nulls, eliminate them. Option #2 is okay-ish. Why are summary and level still nullable? First, as you have them, their typehint is incorrect because it would be Optional[str] instead; but I don't see how those would ever be None (that's the whole reason you're using #2). Don't bool(soup.find). Explicitly write soup.find() is not None. get_profile should be hinted as get_profile(self, url: str) -> Union[BaseProfile, ExtendedProfile] - or use a pipe if you're fancy.
{ "domain": "codereview.stackexchange", "id": 44452, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, object-oriented, comparative-review, python-requests", "url": null }
c#, .net, task-parallel-library, timeout Title: Request-response model over sockets/websockets Question: This is a request-response model over sockets/websockets (like HTTP) where you technically match request id to response id and return the response. In addition to that, there is timeout in case that message is never matched. It does its job but the implementation is not disposing the CancellationTokenSource and TaskCompletionSource. It may even be done in a better way, so here is why I want a code review. Example usage var requestManager = new RequestManager(); var input = JsonSerializer.Serialize(new Test { Message = "Hello World" }); var pending = requestManager.AddPendingRequest(x => { var text = x.Deserialize<Test>(); return text?.Message == "Hello World"; }, TimeSpan.FromSeconds(5)); await Task.Delay(4000); var jsonElement = JsonSerializer.Deserialize<JsonElement>(input); if (requestManager.TryMatchRequest(jsonElement)) { Console.WriteLine("Found"); } public class Test { public string Message { get; set; } } Code to review public class PendingRequest { private readonly CancellationTokenSource _cts; public PendingRequest(Func<JsonElement, bool> handler, TimeSpan timeout) { Handler = handler; Event = new AsyncResetEvent(false, false); Timeout = timeout; _cts = new CancellationTokenSource(timeout); _cts.Token.Register(Fail, false); } public Func<JsonElement, bool> Handler { get; } public JsonElement? Result { get; private set; } public bool Completed { get; private set; } public AsyncResetEvent Event { get; } public TimeSpan Timeout { get; } public bool CheckData(JsonElement data) { if (Handler(data)) { Result = data; Completed = true; Event.Set(); return true; } return false; } public void Fail() { Completed = true; Event.Set(); } }
{ "domain": "codereview.stackexchange", "id": 44453, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, task-parallel-library, timeout", "url": null }
c#, .net, task-parallel-library, timeout public void Fail() { Completed = true; Event.Set(); } } public class RequestManager { private readonly IList<PendingRequest> _pendingRequests = new List<PendingRequest>(); public PendingRequest AddPendingRequest(Func<JsonElement, bool> handler, TimeSpan timeout) { var pending = new PendingRequest(handler, timeout); lock (_pendingRequests) { _pendingRequests.Add(pending); } return pending; } public void FailAllPendingRequests() { lock (_pendingRequests) { foreach (var pendingRequest in _pendingRequests.ToList()) { pendingRequest.Fail(); _pendingRequests.Remove(pendingRequest); } } } public IList<PendingRequest> GetAllPendingRequests() { lock (_pendingRequests) { return _pendingRequests; } } public bool TryMatchRequest(JsonElement tokenData) { lock (_pendingRequests) { foreach (var request in _pendingRequests) { if (!request.CheckData(tokenData)) { continue; } _pendingRequests.Remove(request); return true; } } return false; } public void RemoveTimedOutRequests() { PendingRequest[] requests; lock (_pendingRequests) { requests = _pendingRequests.ToArray(); } foreach (var request in requests.Where(r => r.Completed)) { lock (_pendingRequests) { _pendingRequests.Remove(request); } } } }
{ "domain": "codereview.stackexchange", "id": 44453, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, task-parallel-library, timeout", "url": null }
c#, .net, task-parallel-library, timeout /// <summary> /// Async auto reset based on Stephen Toub`s implementation /// https://devblogs.microsoft.com/pfxteam/building-async-coordination-primitives-part-2-asyncautoresetevent/ /// </summary> public sealed class AsyncResetEvent : IDisposable { private static readonly Task<bool> Completed = Task.FromResult(true); private readonly Queue<TaskCompletionSource<bool>> _waits = new(); private readonly bool _reset; private bool _signaled; /// <summary> /// New AsyncResetEvent /// </summary> /// <param name="initialState"></param> /// <param name="reset"></param> public AsyncResetEvent(bool initialState = false, bool reset = true) { _signaled = initialState; _reset = reset; } /// <summary> /// Dispose /// </summary> public void Dispose() { _waits.Clear(); } /// <summary> /// Wait for the AutoResetEvent to be set /// </summary> /// <returns></returns> public Task<bool> WaitAsync(TimeSpan? timeout = null) { lock (_waits) { if (_signaled) { if (_reset) { _signaled = false; } return Completed; } var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); if (timeout != null) { var cancellationSource = new CancellationTokenSource(timeout.Value); cancellationSource.Token.Register(() => { tcs.TrySetResult(false); }, false); } _waits.Enqueue(tcs); return tcs.Task; } }
{ "domain": "codereview.stackexchange", "id": 44453, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, task-parallel-library, timeout", "url": null }
c#, .net, task-parallel-library, timeout _waits.Enqueue(tcs); return tcs.Task; } } /// <summary> /// Signal a waiter /// </summary> public void Set() { lock (_waits) { if (!_reset) { // Act as ManualResetEvent. Once set keep it signaled and signal everyone who is waiting _signaled = true; while (_waits.Count > 0) { var toRelease = _waits.Dequeue(); toRelease.TrySetResult(true); } } else { // Act as AutoResetEvent. When set signal 1 waiter if (_waits.Count > 0) { var toRelease = _waits.Dequeue(); toRelease.TrySetResult(true); } else if (!_signaled) { _signaled = true; } } } } } ``` Answer: PendingRequest Public interface I would suggest to try to minimize the public surface of this class. I think only Completed and Result should be exposed as properties, others could remain as private fields. private readonly CancellationTokenSource _cancellationSignal; private readonly Func<JsonElement, bool> _handler; private readonly AsyncResetEvent _completionSignal = new(false, false); public JsonElement? Result { get; private set; } public bool Completed { get; private set; } As in the above example, I would suggest to use better naming than _cts and Event. Guard expression vs Early exit In the CheckData it might make sense to use an early exit to streamline the code if (!_handler(data)) return false; Result = data; Completed = true; _completionSignal.Set(); return true; Code duplication These two lines are executed both inside the CheckData and in the Fail Completed = true; _completionSignal.Set();
{ "domain": "codereview.stackexchange", "id": 44453, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, task-parallel-library, timeout", "url": null }
c#, .net, task-parallel-library, timeout Depending on the use case I might rename the Fail to CompleteImmediately/CompleteNow and use it inside the CheckData OR extract that code and use it multiple places For the sake of completeness here is the entire class public class PendingRequest { private readonly CancellationTokenSource _cancellationSignal; private readonly Func<JsonElement, bool> _handler; private readonly AsyncResetEvent _completionSignal = new(false, false); public JsonElement? Result { get; private set; } public bool Completed { get; private set; } public PendingRequest(Func<JsonElement, bool> handler, TimeSpan timeout) { _handler = handler; _cancellationSignal = new CancellationTokenSource(timeout); _cancellationSignal.Token.Register(CompleteNow, false); } public bool CheckData(JsonElement data) { if (!_handler(data)) return false; Result = data; CompleteNow(); return true; } public void Fail() => CompleteNow(); private void CompleteNow() { Completed = true; _completionSignal.Set(); } } RequestManager Method naming IMHO adding everywhere Request or PendingRequest as a method suffix is unnecessary. From the class name and from the methods' parameters it should clear what we are talking about. Thread-safe collection vs lock If possible I would suggest to use one of the concurrent collections because they are thread-safe for sure and they might utilize lock-free algorithms. Because you need to add and remove items from the collection I would suggest to use ConcurrentDictionary. (ConcurrentBag might be tempting at the first glance, but it does not really support arbitrary item removal.) private ConcurrentDictionary<Guid, PendingRequest> _requests = new();
{ "domain": "codereview.stackexchange", "id": 44453, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, task-parallel-library, timeout", "url": null }
c#, .net, task-parallel-library, timeout I've removed readonly, because we will set a new value for it in multiple methods. Add public PendingRequest Add(Func<JsonElement, bool> handler, TimeSpan timeout) { var pending = new PendingRequest(handler, timeout); _requests.TryAdd(Guid.NewGuid(), pending); return pending; } The key does not matter here, we just need to make sure that it is unique. FailAll / CompleteAllNow public void FailAll() { foreach (var (_ ,pendingRequest) in _requests) pendingRequest.Fail(); _requests = new(); } First we complete all requests right away then we empty the _requests collection. GetAll public IList<PendingRequest> GetAll() => _requests.Select(kv => kv.Value).ToList(); Because we use a Dictionary that's why we need to transform the KeyValuePair elements. TryMatch If my understanding is correct then you want to remove the first match (not all the matches) public bool TryMatch(JsonElement tokenData) { var request = _requests.FirstOrDefault(r => r.Value.CheckData(tokenData)); if (request.Equals(default(KeyValuePair<Guid, int>))) return false; return _requests.TryRemove(request); } Here you can't use the == default or is default for the KeyValuePair struct. RemoveTimedOut public void RemoveTimedOut() { var completed = _requests.Where(r => r.Value.Completed); _requests = new(_requests.Except(completed)); } Here we create a new collection without those requests which are already completed. For the sake of completeness here is the entire class public class RequestManager { private ConcurrentDictionary<Guid, PendingRequest> _requests = new(); public PendingRequest Add(Func<JsonElement, bool> handler, TimeSpan timeout) { var pending = new PendingRequest(handler, timeout); _requests.TryAdd(Guid.NewGuid(), pending); return pending; }
{ "domain": "codereview.stackexchange", "id": 44453, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, task-parallel-library, timeout", "url": null }
c#, .net, task-parallel-library, timeout public void FailAll() { foreach (var (_ ,pendingRequest) in _requests) pendingRequest.Fail(); _requests = new(); } public IList<PendingRequest> GetAll() => _requests.Select(kv => kv.Value).ToList(); public bool TryMatch(JsonElement tokenData) { var request = _requests.FirstOrDefault(r => r.Value.CheckData(tokenData)); if (request.Equals(default(KeyValuePair<Guid, int>))) return false; return _requests.TryRemove(request); } public void RemoveTimedOut() { var completed = _requests.Where(r => r.Value.Completed); _requests = new(_requests.Except(completed)); } }
{ "domain": "codereview.stackexchange", "id": 44453, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, task-parallel-library, timeout", "url": null }
c#, performance, collections, bitwise Title: Divide group of numbers into two groups of which the sums are equal Question: I have a piece of code that divides a group of numbers into two groups of numbers of which the sums are equal. I created this because of a Stack Overflow question: For example: {10,15,20,5} will result in: {10,15} + {20,5} {1,2,3,4} will result in: {1,4} + {2,3} {5,5,5,15} will result in: {5,5,5} + {15} {5, 6} will fail. This is the code: static public bool Partition(IList<int> numbers, out IList<int> group0, out IList<int> group1) { if (numbers == null) throw new ArgumentNullException("numbers"); group0 = group1 = null; if (numbers.Count <= 1) return false; int totalSum = numbers.Sum(); if (totalSum % 2 != 0) return false; int desiredSum = totalSum / 2; BitArray groupPerNumber = new BitArray(numbers.Count); while (true) { groupPerNumber.Increase(); // Increate the numberic value of the BitArray. if (groupPerNumber.IsEmpty()) // If all bits are zero, all iterations have been done. return false; // Fill the groups. The bit in the groups-array determines in which group a number will be place. int sumGroup1 = 0; for (int index = 0; index < numbers.Count; index++) { int number = numbers[index]; if (groupPerNumber[index]) sumGroup1 += number; } // If both sums are equal, exit. if (sumGroup1 == desiredSum) { group0 = new List<int>(); group1 = new List<int>(); for (int index = 0; index < numbers.Count; index++) { int number = numbers[index]; if (!groupPerNumber[index]) group0.Add(number); else group1.Add(number); } return true; } } }
{ "domain": "codereview.stackexchange", "id": 44454, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, collections, bitwise", "url": null }
c#, performance, collections, bitwise I created some supporting extension methods: static public class BitSetExtensions { /// <summary> /// Treats the bits as a number (like Int32) and increases it with one. /// </summary> static public void Increase(this BitArray bits) { for (int i = 0; i < bits.Length; i++) { if (!bits[i]) { bits[i] = true; bits.SetAll(0, i - 1, false); return; } bits[i] = false; } bits.SetAll(false); } /// <summary> /// Sets the subset of bits from the start position till length with the given value. /// </summary> static public void SetAll(this BitArray bits, int start, int length, bool value) { while (length-- > 0) bits[start++] = value; } /// <summary> /// Returns true if all bits in the collection are false. /// </summary> static public bool IsEmpty(this BitArray bits) { for (int i = 0; i < bits.Length; i++) if (bits[i]) return false; return true; } } Criteria: The group of numbers must have any size. Only two sets have to be found. The order of the numbers may be mixed up. So sorting is allowed. The numbers must be greater than 0. The real question is: How can this code be made any faster? Results so far: Original posting (by myself): 3.657.559 ticks = factor 1.0 (baseline) All combined trics (answer of myself): 8.563 ticks = factor 427.1 Code of Ivan: 12.969 ticks = factor 282,0 Code of Stephen: 34.415 ticks = factor 106,3 Code of Jesse: 1.743.905 ticks = factor 2,097 Code of Eren: 16.108.289 ticks = factor 0,2270 Code of Servy: 225.239.100 ticks = factor 0,01623 Code of Bobson: 49.663.859.000 ticks = factor 0,000074 Things I have learned so far:
{ "domain": "codereview.stackexchange", "id": 44454, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, collections, bitwise", "url": null }
c#, performance, collections, bitwise Things I have learned so far: Try to avoid interfaces if you have access to the real class. So int[] is faster than IList<int>. Try to avoid complex structures in you have a basic structure. So bool[] is faster than BitArray. Try to avoid any memory operations (like new). Try to avoid foreach. Use for. Every time you use foreach an IEnumerator is created, resulting in a memory operation. Try to avoid LINQ. LINQ is based on already existing methods. It is just one extra call. Further it relies on IEnumerable, which will create an IEnumerable at every call, resulting in a memory operation. My original code analyzed ALL combinations. The early out algorithm in my second posting saved me a lot of time. Skip on iteration by using the first number as a starting sum, instread of 0. Use for-loops counting back to 0. The test I use a few arrays of numbers: var arrays = new int[][] { new[]{ 1, 12, 10, 2, 23 }, new[] {14,10,20,4}, new[] {5, 5, 15, 5}, new[] {1, 5, 30}, // Will fail. new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, // Will fail. new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, }; The time of a Partion-function is measured as follows: Stopwatch st0 = Stopwatch.StartNew(); for (int i = iterations - 1; i >= 0; i--) for (int n = arrays.Length - 1; n >= 0; n--) if (PartitionOriginal(arrays[n], out list0, out list1)) sum = list0.Sum() + list1.Sum(); st0.Stop(); The value iterations is a constant, by default set with 1000. If the partition succeeds, the first result result set (some functions return more than one result set) are summed. The reason behind this summing is to ensure that all search work is done. Sometimes when an IEnumerable is returned, code (using yield return) still needs to be executed.
{ "domain": "codereview.stackexchange", "id": 44454, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, collections, bitwise", "url": null }
c#, performance, collections, bitwise Answer: The main idea is to find a biggest element, place it in the first bin and start recursion from the second element saving lots of tree spanning. UPDATED CODE Main Method public static class ASolution { public static bool TryPartitionBySum(int[] values, out int[] fstBin, out int[] scndBin) { #region Part I if (values == null) throw new ArgumentNullException("values"); fstBin = scndBin = null; if (values.Length <= 1) return false; int totalSum = 0; int maxIdx = -1; int maxVal = -1; for (int i = 0; i < values.Length; i++) { int tmp = values[i]; if (tmp <= 0) throw new ArgumentException("Numbers is not allowed to contain values less than one."); if (tmp > maxVal) { maxVal = tmp; maxIdx = i; } totalSum += tmp; } #endregion if (totalSum % 2 != 0) return false; // Put max val at the first place values[maxIdx] = values[0]; values[0] = maxVal; var activeIdx = new bool[values.Length]; activeIdx[0] = true; int targetSum = totalSum / 2 - maxVal; if (targetSum < 0) return false; bool isSuccess = targetSum == 0 || RecursiveTryPartition(values, activeIdx, 1, targetSum); #region PART III if (isSuccess) { int fstBinIdx = 0, scndBinIdx = 0; int size = 0; for (int i = 0; i < activeIdx.Length; i++) { if (activeIdx[i]) size++; } fstBin = new int[size]; scndBin = new int[activeIdx.Length - size];
{ "domain": "codereview.stackexchange", "id": 44454, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, collections, bitwise", "url": null }
c#, performance, collections, bitwise for (int i = 0; i < activeIdx.Length; i++) { if (activeIdx[i]) fstBin[fstBinIdx++] = values[i]; else scndBin[scndBinIdx++] = values[i]; } } #endregion return isSuccess; } private static bool RecursiveTryPartition(int[] numbers, bool[] isActive, int headIdx, int sumLeft) { if (headIdx == numbers.Length) return false; int currVal = numbers[headIdx]; isActive[headIdx] = true; if (currVal < sumLeft && RecursiveTryPartition(numbers, isActive, headIdx + 1, sumLeft - currVal)) return true; if (currVal == sumLeft) return true; isActive[headIdx] = false; return RecursiveTryPartition(numbers, isActive, headIdx + 1, sumLeft); } } TEST ITEM Unfortunately you need to plug-in your method to which defines whether a sequence is partitionable. public class TestCase { private const string Delim = ","; public int ExperimentsCount { get { return Values.Length; } } public int VectorSize { get { return Values[0].Length; } } public int PartitionableCount { get; private set; } private int[][] Values { get; set; } private TestCase() { } public IEnumerable<int[]> TestSample { get { return Values.Select(f => f.ToArray()); } } public void ToFile(string path) { System.IO.File.WriteAllText(path, PartitionableCount + "\n"); System.IO.File.AppendAllLines(path, Values.Select(f => string.Join(Delim, f))); }
{ "domain": "codereview.stackexchange", "id": 44454, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, collections, bitwise", "url": null }
c#, performance, collections, bitwise public TestCase Read(string path) { var lines = System.IO.File.ReadAllLines(path); return new TestCase { PartitionableCount = int.Parse(lines[0]), Values = lines.Skip(1) .Select(line => line.Split(Delim[0]) .Select(int.Parse) .ToArray()) .ToArray() }; } public static TestCase CreateSample(int experimentsCount, int vectorSize, double targetedSuccessRate , Func<int[], bool> isPartitionable) { if (targetedSuccessRate < 0 || targetedSuccessRate > 1) throw new ArgumentException("Success rate must be a percentage value", "targetedSuccessRate"); if (experimentsCount < 0) throw new ArgumentException("Experiments count must be a positive number"); if (vectorSize < 5) throw new ArgumentException("Vector size should be at least 5"); var rnd = new Random(); var tmp = new TestCase { Values = new int[experimentsCount][], PartitionableCount = (int)(targetedSuccessRate * experimentsCount) }; var successTriesLeft = tmp.PartitionableCount; int successIdx = experimentsCount - successTriesLeft; int failIdx = successIdx - 1; while (successIdx < experimentsCount || failIdx >= 0) { var vec = Enumerable.Range(0, vectorSize) .Select(_ => rnd.Next(1, vectorSize * 3)) .ToArray();
{ "domain": "codereview.stackexchange", "id": 44454, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, collections, bitwise", "url": null }
c#, performance, collections, bitwise if (isPartitionable(vec)) { if (successIdx < experimentsCount) { tmp.Values[successIdx++] = vec; } } else { if (failIdx >= 0) { tmp.Values[failIdx--] = vec; } } } return tmp; } } TEST RUNNER public static class TestRunner { public delegate bool Partitioner(int[] values, out int[] fstBin, out int[] scndBin); public static long RunTest(TestCase testData, Partitioner function) { var vals = testData.TestSample.ToArray(); var sw = System.Diagnostics.Stopwatch.StartNew(); int count = 0; foreach (var vector in vals) { int[] fstBin, sndBin; if (function(vector, out fstBin, out sndBin)) { count++; //System.Diagnostics.Trace.Assert(fstBin.Sum() == sndBin.Sum()); } } sw.Stop(); //System.Diagnostics.Trace.Assert(count == testData.PartitionableCount); return sw.ElapsedTicks; } } SAMPLE OF CODE USAGE var iterCount = 10000; var vectorSizes = new[] { 5, 10, 25, 50}; var successRate = new[] { 0, 0.2, 0.5, 0.8, 1.0}; var testList = vectorSizes.SelectMany(v => successRate.Select(r => new { VectorSize = v, SuccessRate = r }));
{ "domain": "codereview.stackexchange", "id": 44454, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, collections, bitwise", "url": null }
c#, performance, collections, bitwise Console.WriteLine("{0,-10}{1,-10}{2,10}{3,10}", "Rate,%", "Size", "M sol", "I sol"); foreach (var item in testList) { int[] a, b; var tmp = TestCase.CreateSample(iterCount, item.VectorSize, item.SuccessRate, vals => Mulders.Partition(vals, out a, out b)); //var tmp = TestCase.Read("MySavedCase.csv"); Console.WriteLine("{0,-10:P}{1,-10}{2,10:N0}{3,10:N0}", (double)tmp.PartitionableCount / tmp.ExperimentsCount, tmp.VectorSize, TestRunner.RunTest(tmp, Mulders.Partition), TestRunner.RunTest(tmp, ASolution.TryPartitionBySum)); } Hope it'll help to run some tests for all solutions.
{ "domain": "codereview.stackexchange", "id": 44454, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, performance, collections, bitwise", "url": null }