text
stringlengths
1
2.12k
source
dict
python, console, mvp def add_selected_player(self, player_name: str) -> None: """Adds a player to selected players. Raises ValueError if player doesn't exist or player already selected.""" if player_name not in self._player_names: raise ValueError(f"player '{player_name}' doesn't exist") elif player_name in self._selected_players: raise ValueError(f"player '{player_name}' already selected") else: self._selected_players.add(player_name) #view.py from collections.abc import Callable from typing import Optional class View: def __init__(self): self.on_command: Optional[Callable] = None def display_text(self, text: str) -> None: """Displays given text to the user.""" print(text) def get_command(self, prompt: str) -> None: """Retrieves a command from the user and passes it to the on_command function.""" command = input(prompt).lower() self.on_command(command) def enter_to_continue(self, text: str) -> None: """Displays the given text to the user and waits for them to press Enter.""" input(text) def clear(self) -> None: """Clears the console by printing 80 newline characters.""" print("\n" * 80) #presenter.py from collections.abc import Callable import re import textwrap from typing import Optional from model import Model from table_formatter import TableFormatter from view import View DEBUG = False class Presenter: def __init__(self, model: Model, view: View): self.model = model self.view = view self.table_formatter = TableFormatter() self.view.on_command = self.handle_user_command self.current_page_number: int = 1 self.current_table: str = "" self.current_status: str = "STATUS:"
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
python, console, mvp @property def amount_pages(self) -> int: """Calculates the total number of pages needed to display all players, based on the number of names that can be displayed per page.""" return 1 + (self.model.amount_all_players // self.table_formatter.names_per_page) def start(self) -> None: """Initiates the interaction with the user, by updating the view and prompting for user command.""" self._update_table() self._update_view() self._get_command() def handle_user_command(self, user_input: str) -> None: """Handles user command by parsing it, executing the corresponding function and updating the view.""" try: function = self._get_function(user_input) valid_status_info = function(self._strip_command(user_input)) except Exception as e: if DEBUG: raise self._update_invalid_status(user_input, str(e)) else: self._update_table() self._update_valid_status(valid_status_info) self._update_view() self._get_command() def _get_command(self) -> None: """Asks user for a command.""" self.view.get_command("Input command here (type ? for help): ") def _get_function(self, user_input: str) -> Optional[Callable]: """Maps user input to corresponding function, if any. Raises ValueError if command is not recognized.""" user_commands = ( (re.compile(r'^\?$'), self._give_help), (re.compile(r'^new .*'), self._add_new_player), (re.compile(r'^select \d+$'), self._select_player_by_index), (re.compile(r'^select .*'), self._select_player_by_name), (re.compile(r'^goto \d+$'), self._goto_by_page_num), (re.compile(r'^goto .*'), self._goto_by_search) )
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
python, console, mvp for regex, function in user_commands: if regex.search(user_input): return function raise ValueError(f"no matching command for '{user_input}'") def _strip_command(self, user_input: str) -> str | None: """Removes the command from the user's input, leaving only the argument.""" try: _, argument = user_input.split(maxsplit=1) return argument except ValueError: return def _give_help(self, user_input=None) -> None: """Displays help text containing available commands and their usage.""" help_text = textwrap.dedent(""" HELP ---- Available Commands: new: Add a new player to the database. Usage: 'new NAME' (e.g., 'new john cleese') select: Select a player to participate in the game. Usage: 'select INDEX' or 'select NAME' (e.g., 'select 24' or 'select michael palin') goto: Navigate to a specific page. Usage: 'goto PAGE' or 'goto TERM' (e.g., 'goto 5' to go to page 5, or 'goto er' to go to the first page with a name starting with 'er' or the closest match if there's no exact match) Press enter to continue... """) self.view.clear() self.view.enter_to_continue(help_text) def _add_new_player(self, player_name: str) -> str: """Adds a new player to the model. Raises ValueError if player already exists.""" self.model.add_new_player(player_name) player_index = self.model.get_index_by_name(player_name) return f"new player '{player_name}' added (index: {player_index})"
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
python, console, mvp def _select_player_by_index(self, player_index: int | str) -> str: """Selects a player based on the provided index. Raises IndexError if index out of range or ValueError if player already selected.""" player_name = self.model.get_player_by_index(int(player_index)) self.model.add_selected_player(player_name) player_num = self.model.amount_selected_players return f"{player_name} selected (player {player_num})" def _select_player_by_name(self, player_name: str) -> str: """Selects a player based on the provided name. Raises ValueError if player doesn't exist or player already selected.""" self.model.add_selected_player(player_name) player_num = self.model.amount_selected_players return f"{player_name} selected (player {player_num})" def _goto_by_page_num(self, page_num: str | int) -> None: """Move to a specific page number. Raises IndexError if page number out of range.""" if not 0 < int(page_num) <= self.amount_pages: raise IndexError(f"page number {page_num} is out of range") else: self.current_page_number = int(page_num) def _goto_by_search(self, search: str) -> None | str: """Navigates to the page containing the first player name that starts with the given search string. If no exact prefix match is found, navigates to the closest match instead.""" bisect_result = self.model.players_binary_search(search) page_num = self._page_num_from_index(bisect_result) self._goto_by_page_num(page_num) if not self.model.index_startswith(bisect_result, search): return f"no exact prefix-match found for '{search}'" def _page_num_from_index(self, player_index: int) -> int: """Converts a player's index into the corresponding page number.""" return 1 + ((1 + player_index) // self.table_formatter.names_per_page)
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
python, console, mvp def _update_table(self) -> None: """Updates the current table of players, considering currently selected players and the current page.""" player_names = self.model.get_slice_all_players(*self._calc_page_indexes()) selected_players = self.model.get_selected_players() new_table = self.table_formatter.create_table(player_names=player_names, selected_players=selected_players, page_number=self.current_page_number, total_pages=self.amount_pages ) self.current_table = new_table def _calc_page_indexes(self) -> tuple[int, int]: """Calculates the starting and ending indexes for the current page.""" start = self.table_formatter.names_per_page * (self.current_page_number - 1) end = self.table_formatter.names_per_page * self.current_page_number return start, end def _update_valid_status(self, information: str | None = None) -> None: """Updates the status message after a successful operation.""" if information: self.current_status = f"STATUS: {information}." else: self.current_status = "STATUS:" def _update_invalid_status(self, user_input: str | None = None, information: str | None = None) -> None: """Updates the status message after an unsuccessful operation.""" if information: self.current_status = f"STATUS: INVALID INPUT ({information})." else: self.current_status = f"STATUS: INVALID INPUT '{user_input}'."
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
python, console, mvp def _update_view(self) -> None: """Updates the view with the current table of players and status message.""" new_view = ( f"PLAYER SELECT\n" f"-------------\n\n" f"{self.current_table}\n\n" f"{self.current_status}\n" ) self.view.clear() self.view.display_text(new_view) #table_formatter.py from itertools import zip_longest from wcwidth import wcswidth class TableFormatter: """ Initializes the table formatter with the given settings. Args: num_columns (int): The number of columns in the table. col_length (int): The maximum length of each column. col_width (int): The width of each column. col_spacing (int): The amount of spacing between columns. truncate_amount (int): The amount of characters to truncate in case of overflow. """ def __init__(self, num_columns: int = 3, col_length: int = 8, col_width: int = 24, col_spacing: int = 3, truncate_amount: int = 3 ): self.num_columns = num_columns self.col_length = col_length self.col_width = col_width self.col_spacing = col_spacing self.truncate_amount = truncate_amount @property def names_per_page(self) -> int: """Returns the total number of names that can fit on a single page.""" return self.num_columns * self.col_length def create_table(self, player_names: list[str], selected_players: set[str], page_number: int, total_pages: int, ) -> str: """ Generates a formatted table of player names with pagination.
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
python, console, mvp Args: player_names (list[str]): List of all player names. selected_players (set[str]): Set of selected player names. page_number (int): The current page number. total_pages (int): The total number of pages. Returns: str: A string representation of the table. """ formatted_players = self._format_players(player_names, selected_players, page_number) player_table = self._format_table(formatted_players, len(player_names)) page_info = self._format_page_info(total_pages, page_number) return player_table + "\n" + page_info def _format_players(self, player_names: list, selected_players: set, page_number: int) -> list[str]: """Formats player names into a table, displaying their index and name. Truncates name if longer than the column width, adds strikethrough to selected players, pads index and end of name (if necessary).""" table_entries = [] for i, player_name in enumerate(player_names, start=self._calc_start_index(page_number)): entry = f"{self._pad_index(i)}: {player_name}" entry = self._truncate(entry) entry = self._strikethrough(entry, player_name, selected_players) entry = self._pad_end(entry) table_entries.append(entry) return table_entries def _format_table(self, table_entries: list[str], player_amount: int) -> str: """Divides table entries into rows, joins rows in a string, adds empty rows to keep table size consistent (if necessary).""" rows = self._divide_into_rows(table_entries) table = self._join_rows(rows) table = self._add_empty_rows(table, player_amount) return table def _format_page_info(self, total_pages: int, page_number: int) -> str: """Creates a string showing the current page number and total pages.""" return f"page {page_number} of {total_pages}"
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
python, console, mvp def _calc_start_index(self, page_number: int) -> int: """Calculates the first index of the page""" return self.names_per_page * (page_number - 1) def _pad_index(self, name_index: int) -> str: """Adds a whitespace to an index if there are wider indexes in the same column.""" last_index_of_column = name_index + (self.col_length - 1) - (name_index % self.col_length) if len(str(name_index)) < len(str(last_index_of_column)): return str(name_index) + " " return str(name_index) def _truncate(self, entry: str) -> str: """Truncates name if it is longer than column with, adds trailing ...""" if len(entry) > self.col_width: truncated_width = self.col_width - self.truncate_amount return entry[:truncated_width] + ("." * self.truncate_amount) return entry def _strikethrough(self, entry: str, player_name: str, selected_players: set[str]) -> str: """Adds strikethrough to selected player.""" strike_char = '\u0336' if player_name in selected_players: return strike_char.join(entry) + strike_char return entry def _pad_end(self, entry: str) -> str: """Pads the end of the string to match column width and adds whitespaces for column spacing.""" if wcswidth(entry) < self.col_width: amount_whitespaces = self.col_width - wcswidth(entry) + self.col_spacing return entry + (" " * amount_whitespaces) return entry + (" " * self.col_spacing) def _divide_into_rows(self, table_entries: list[str]) -> list[tuple[str, ...]]: """Divides the table entries into rows.""" columns_on_page = 1 + (len(table_entries) // self.col_length) columns = [[] for _ in range(columns_on_page)] for i, name in enumerate(table_entries): columns[i // self.col_length].append(name) return list(zip_longest(*columns, fillvalue=""))
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
python, console, mvp def _join_rows(self, rows: list[tuple[str, ...]]) -> str: """Joins the rows into a table string.""" table = "" for row in rows: table += "".join(row) + "\n" return table def _add_empty_rows(self, table: str, amount_players: int) -> str: """Pads table with empty rows if the amount of players on the page is smaller than the column length.""" empty_rows = self.col_length - amount_players if empty_rows > 0: table += "\n" * empty_rows return table #main.py # Generates random names for the example program, names will eventually be stored in a database. import random from model import Model from presenter import Presenter from view import View first_names = ['sara', 'sofie', 'julia', 'myla', 'zofia', 'emma', 'zoey', 'yarah', 'olivia', 'tess', 'milou', 'lotte', 'saar', 'hannah', 'liv', 'eva', 'anna', 'noor', 'nina', 'lauren', 'lois', 'emily', 'lieke', 'isa', 'elynn', 'maud', 'fien', 'roos', 'lina', 'luna', 'ella', 'nova', 'hailey', 'mia', 'fleur', 'julie', 'fenna', 'beau', 'noa', 'lilly', 'esmee', 'puck', 'cato', 'maeve', 'noah', 'lucas', 'luka', 'levi', 'sem', 'daan', 'mylan', 'james', 'muhammed', 'mees', 'adam', 'sam', 'bram', 'zayn', 'mads', 'benjamin', 'jesse', 'max', 'boaz', 'siem', 'teun', 'kay', 'julian', 'thomas', 'vinz', 'jaxx', 'gijs', 'thijs', 'seb', 'olivier', 'lars', 'guus', 'joep', 'jack', 'ayden', 'seff', 'owen', 'jan', 'hugo', 'morris', 'david']
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
python, console, mvp last_names = ['jong', 'jansen', 'vries', 'berg', 'dijk', 'bakker', 'janssen', 'visser', 'smit', 'meyer', 'boer', 'mulder', 'groot', 'bos', 'vos', 'peters', 'hendriks', 'leeuwen', 'dekker', 'brouwer', 'wit', 'dijkstra', 'smits', 'graaf', 'meer', 'linden', 'kok', 'jacobs', 'haan', 'vermeulen', 'heuvel', 'veen', 'broek', 'bruijn', 'bruin', 'heijden', 'schouten', 'beek', 'willems', 'vliet', 'ven', 'hoekstra', 'maas', 'verhoeven', 'koster', 'dam', 'wal', 'prins', 'blom', 'huisman'] def generate_names(amount: int) -> list[str]: return [f"{random.choice(first_names)} {random.choice(last_names)}" for _ in range(amount)] model = Model(generate_names(150)) view = View() presenter = Presenter(model, view) presenter.start() Answer: Has the Model-View-Presenter been implemented well? Are the responsibilities divided up as they should? I decided to link the view with the presenter through a simple callback method, is this a good idea? Your implementation looks closer to MVC (Model-View-Controller) than MVP. The main problem of MVC is that the Controller (called Presenter in your code) does too much: it works with the Model handling incoming requests and it tells the View what to display. In MVP the latter is done in the View, thus freeing the Presenter from this responsibility. You can tell there is a problem by comparing the size of the View class with the Presenter. Here is a great read on the topic. It's about Android but you can draw parallels. Are the classes structured in a logical way and are the methods readable? I generally try to adhere to the Single Responsibility Principle, and find it relatively intuitive for functions, but find it harder for classes. Main area of concern is the Presenter class: I've already split out the logic for formatting the player table, but the class is still quite large. Is this a problem?
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
python, console, mvp Let's elaborate on the previous paragraph. Your View class is very abstract: it doesn't know anything about what is to be displayed. This abstraction would make sense if you're planning another way of displaying things, e.g. a GUI. In this case you can turn this logic into a dependency of the main View class: interface UI with 2 implementations - existing CLI that prints lines into the console and a hypothetical GUI that draws them on the screen. View, which is responsible for constructing strings from the information provided by the Presenter, calls to the UI when it needs to display something. Method names are all very good. I'm still rather inexperienced at exception handling, has it been dealt with correctly? It was done very well, however there is one problem: def _strip_command(self, user_input: str) -> str | None: """Removes the command from the user's input, leaving only the argument.""" try: _, argument = user_input.split(maxsplit=1) return argument except ValueError: return Here you use exceptions to differentiate between functions that take one parameter and those that zero. Never use exceptions for handling normal logic, they are for cases when something doesn't go according to plan. Every time I use the "help" command this exception will fire and you have to use a stub (user_input=None) in the signature of _give_help in order for things to work properly. If you ever need a function that takes 2 parameters, this entire logic will have to be rewritten. The right thing would be to pass the number of expected arguments as a parameter to _strip_command and get rid of exception handling in the method (it will be guaranteed to succeed because of the regexp).
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
python, console, mvp How detailed should the docstrings be? I used ChatGPT to generate some of the docstrings as I find this difficult to do, and decided to use ChatGPT's more detailed docstrings for the main methods, and wrote my own less detailed docstrings for the "sub-methods". Is this the right way to go? If the class / function is not a public API (other developers won't be using it), don't bother at all. Your code should speak for itself. Otherwise it's important that the following things are clear: what the function / class is for? does the function have side-effects? what does the function return? what does the function expect to be passed in its parameters? If the purpose is unclear without a comment, change the name to describe it better. Random nitpicks: True if self._player_names[index].startswith(search) else False can be replaced with just self._player_names[index].startswith(search) def generate_names(amount: int) -> list[str]: return [f"{random.choice(first_names)} {random.choice(last_names)}" for _ in range(amount)] This can produce duplicate names. player_names: Iterable Iterable of what? If you're using typehints, use them to the fullest, otherwise it seems like this player_names can be filled with anything. self.table_formatter = TableFormatter() This dependency should be injected along with the others, not created inside the dependant. You are using DI everywhere else in the code, so I assume it's just a mistake. Extremely good code for a beginner, keep it up! Upd: here is a before / after scheme for a potential refactoring:
{ "domain": "codereview.stackexchange", "id": 44816, "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, console, mvp", "url": null }
java, benchmarking Title: Performance testing app in Java Question: I wrote a basic app for measuring time it takes to execute any given block of code. What do you think? @NoArgsConstructor public class Measurer { private LoggingType loggingType = LoggingType.DISABLED; public Measurer(LoggingType loggingType) { this.loggingType = loggingType; } public long measure(MeasuredProcedure measuredProcedure) { long start = System.nanoTime(); measuredProcedure.run(); long finish = System.nanoTime(); long nanosTaken = finish - start; if (loggingType.equals(LoggingType.ENABLED)) { logMeasurement(measuredProcedure, nanosTaken); } return nanosTaken; } public long compare(MeasuredProcedure firstProcedure, MeasuredProcedure secondProcedure) { long nanosTakenByFirstProcedure = measure(firstProcedure); long nanosTakenBySecondProcedure = measure(secondProcedure); long signedDifference = nanosTakenByFirstProcedure - nanosTakenBySecondProcedure; if (loggingType.equals(LoggingType.ENABLED)) { logDifferenceBetween(firstProcedure, nanosTakenByFirstProcedure) .and(secondProcedure, nanosTakenBySecondProcedure); } return signedDifference; } private void logMeasurement(MeasuredProcedure measuredProcedure, long nanosTaken) { String timeTaken = renderReadable(nanosTaken); System.out.println(measuredProcedure + " took: " + timeTaken); } private ComparisonLoggingIntermediary logDifferenceBetween(MeasuredProcedure firstProcedure, long firstProcedureNanos) { return new ComparisonLoggingIntermediary(firstProcedure, firstProcedureNanos); }
{ "domain": "codereview.stackexchange", "id": 44817, "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": "java, benchmarking", "url": null }
java, benchmarking private static String renderReadable(long nanos) { var r = new NanoProcessor().process(nanos); TimeUnit[] timeUnits = {r.minutes(), r.seconds(), r.millis(), r.nanos()}; var joiner = new StringJoiner(", "); for (int i = 0; i < timeUnits.length; i++) { TimeUnit unit = timeUnits[i]; if (unit.value() == 0) { continue; } String suffix = (unit.value() % 10 == 1) ? "" : "s"; joiner.add(unit.value() + " " + unit.name() + suffix); } return joiner.toString(); } public enum LoggingType { ENABLED, DISABLED } static class NanoProcessor { NanoProcessingResult process(long nanos) { long minutes = extractLooseMinutes(nanos); long seconds = extractLooseSeconds(nanos); long milliseconds = extractLooseMilliseconds(nanos); long nanoseconds = extractLooseNanoseconds(nanos); return new NanoProcessingResult( new TimeUnit(TimeUnitName.MINUTE, minutes), new TimeUnit(TimeUnitName.SECOND, seconds), new TimeUnit(TimeUnitName.MILLISECOND, milliseconds), new TimeUnit(TimeUnitName.NANOSECOND, nanoseconds) ); } private long extractLooseMinutes(long nanos) { return nanos / 60_000_000_000L; } private long extractLooseSeconds(long nanos) { return nanos % 60_000_000_000L / 1_000_000_000L; } private long extractLooseMilliseconds(long nanos) { return nanos % 1_000_000_000L / 1_000_000L; } private long extractLooseNanoseconds(long nanos) { return nanos % 1_000_000L; } record NanoProcessingResult(TimeUnit minutes, TimeUnit seconds, TimeUnit millis, TimeUnit nanos) { }
{ "domain": "codereview.stackexchange", "id": 44817, "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": "java, benchmarking", "url": null }
java, benchmarking record TimeUnit(TimeUnitName name, long value) { enum TimeUnitName { MINUTE, SECOND, MILLISECOND, NANOSECOND; @Override public String toString() { return name().toLowerCase(); } } } } private record ComparisonLoggingIntermediary(MeasuredProcedure firstProcedure, long firstProcedureNanos) { void and(MeasuredProcedure secondProcedure, long secondProcedureNanos) { MeasuredProcedure fastestProcedure = (firstProcedureNanos < secondProcedureNanos) ? firstProcedure : secondProcedure; MeasuredProcedure slowestProcedure = fastestProcedure.equals(firstProcedure) ? secondProcedure : firstProcedure; long difference = Math.abs(firstProcedureNanos - secondProcedureNanos); long percentage = fastestProcedure.equals(firstProcedure) ? difference / (secondProcedureNanos / 100) : difference / (firstProcedureNanos / 100); String renderedDifference = renderReadable(difference); System.out.println(fastestProcedure + " has shown better performance: it is faster than " + slowestProcedure + " by " + percentage + "% (" + renderedDifference + ")"); } } } abstract class MeasuredProcedure { protected String name; protected MeasuredProcedure(String name) { this.name = name; } abstract void run(); @Override public String toString() { return name; } }
{ "domain": "codereview.stackexchange", "id": 44817, "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": "java, benchmarking", "url": null }
java, benchmarking public final class MeasuredProcedureFactory { public static final MeasuredProcedure MILLION_INTS_TO_ARRLIST_NO_PREALLOCATION = new MeasuredProcedure("MILLION_INTS_TO_ARRLIST_NO_PREALLOCATION") { @Override public void run() { int numOfElements = 1_000_000; List<Integer> intList = new ArrayList<>(); addRandomInts(intList, numOfElements); } }; public static final MeasuredProcedure MILLION_INTS_TO_ARRLIST_WITH_PREALLOCATION = new MeasuredProcedure("MILLION_INTS_TO_ARRLIST_WITH_PREALLOCATION") { @Override public void run() { int numOfElements = 1_000_000; List<Integer> intList = new ArrayList<>(numOfElements); addRandomInts(intList, numOfElements); } }; public static final MeasuredProcedure PLUS_CONCATENATION_OF_THOUSAND_LETTERS = new MeasuredProcedure("PLUS_CONCATENATION_OF_THOUSAND_LETTER") { @Override void run() { String res = ""; String[] alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); for(int i = 0; i < 1_000; i++) { int randomIndex = Util.randomInt(alphabet.length); res += alphabet[randomIndex]; } } }; public static final MeasuredProcedure STRING_BUILDING_OF_THOUSAND_LETTERS = new MeasuredProcedure("STRING_BUILDING_OF_THOUSAND_LETTERS") { @Override void run() { StringBuilder sb = new StringBuilder(); String[] alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); for(int i = 0; i < 1_000; i++) { int randomIndex = Util.randomInt(alphabet.length);
{ "domain": "codereview.stackexchange", "id": 44817, "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": "java, benchmarking", "url": null }
java, benchmarking int randomIndex = Util.randomInt(alphabet.length); sb.append(alphabet[randomIndex]); } sb.toString(); } }; public static final MeasuredProcedure STRING_BUFFERING_OF_THOUSAND_LETTERS = new MeasuredProcedure("STRING_BUFFERING_OF_THOUSAND_LETTERS") { @Override void run() { StringBuffer sb = new StringBuffer(); String[] alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); for(int i = 0; i < 1_000; i++) { int randomIndex = Util.randomInt(alphabet.length); sb.append(alphabet[randomIndex]); } sb.toString(); } };
{ "domain": "codereview.stackexchange", "id": 44817, "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": "java, benchmarking", "url": null }
java, benchmarking private MeasuredProcedureFactory() { } private static void addRandomInts(List<Integer> intList, int numOfElements) { for (int i = 0; i < numOfElements; i++) { int randomInt = Util.randomInt(numOfElements); intList.add(randomInt); } } } Example of usage: public class App { public static void main(String[] args) { Measurer measurer = new Measurer(LoggingType.ENABLED); measurer.compare( MeasuredProcedureFactory.STRING_BUFFERING_OF_THOUSAND_LETTERS, MeasuredProcedureFactory.STRING_BUILDING_OF_THOUSAND_LETTERS ); } } STRING_BUFFERING_OF_THOUSAND_LETTERS took: 2 milliseconds, 384700 nanoseconds STRING_BUILDING_OF_THOUSAND_LETTERS took: 416800 nanoseconds STRING_BUILDING_OF_THOUSAND_LETTERS has shown better performance: it is faster than STRING_BUFFERING_OF_THOUSAND_LETTERS by 82% (1 millisecond, 967900 nanoseconds)
{ "domain": "codereview.stackexchange", "id": 44817, "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": "java, benchmarking", "url": null }
java, benchmarking Answer: It seems like a very complex way to make what is essentially "toy code" to test how long an algorithm runs. I would perhaps concentrate on writing the algorithms first in a usefule manner and then figure out a way to measure their running time so that minimal changes to the algorithm is needed in order to measure it. Along the lines of what Martin Frank already suggested, maybe wrap the code to be measured in a lambda and pass that to the timer. But as an exercise in how to write a library, let's see... Managing logging levels should not be a concern of your library. Use a logging framework and let the caller worry about setting the logging level in the configuration. Since you are already using Lombok, consider @Slf4j. ComparisonLoggingIntermediary breaks the record contract. A record is a data container that shouldn't contain complex logic. It breaks the single responsibility principle since it's a record for one measurement result, a comparator for two measurement results and an output formatter. That's three responsibilities. The and method adds another way to represent measurement results, the method parameters. What if you want to add another metric to the results? You would have to change both the record class and the method signature. That's a sign of duplicate code. My suggestion is to remove the and method, it's name is fairly bad as it doesn't tell anything about what it does and rename the class to MeasurementResult.
{ "domain": "codereview.stackexchange", "id": 44817, "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": "java, benchmarking", "url": null }
java, benchmarking Maybe consider changing the compare method so that instead of two, it can accept any number of methods to measure (using varargs for example). That will force you to rethink your methods and data structures so that they become more generic and making mistakes like the ComparisonLoggingIntermediary becomes easier to spot as the code would be a lot more complicated. To remove the need to have a dedicated class just for providing a procedure name, maybe separate the registration of procedures and the measurement to separate methods. If you like fluent interfaces and builders, maybe something like: final List<MeasurementResult> result = Masurer.builder() .register("NO PREALLOCATION", new NoPreallocation()) .register("WITH PREALLOCATION", new WithPreallocation()) .measure();
{ "domain": "codereview.stackexchange", "id": 44817, "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": "java, benchmarking", "url": null }
java, benchmarking There's a bit of redundancy in the registration methods there and you could use class names too, but if you want to use functional interfaces and lambdas, then class names aren't very useful. Follow single responsibility principle. Make the Measurer only responsible for measuring the execution time. Create a MeasurementResultComparator for sorting out a collection of MeasurementResult objects. Then you can make another comparator if you want to sort them by longest time or some other metric you decide to collect later. Then for outputting the results, create a class for printing out a set of results to a PrintStream. You might not always be using a console so incorporating the concole output to your library would place unnecessary restrictions on the users who want to use your library from a graphical user interface. And for measuring algorithm performance, simply taking the start and end time from a single execution is very error prone and will not produce useful results. It allows other processes to interfere with the execution. You may have a garbage collector running during one measurement but not the other. You should be running the measured code multiple times and recording statics from the execution times. Calculate average and mean times, etc (that's the kind of information you could put in the MeasurementResult record).
{ "domain": "codereview.stackexchange", "id": 44817, "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": "java, benchmarking", "url": null }
javascript, performance, ecmascript-6, html5, canvas Title: Create and store the level data for a remake of Super Mario Bros game Question: I am trying to remake Super Mario Bros. in JavaScript and I am trying to figure out if there is a more efficient/shorter way to create and store the level data. I have created 1-1 and here's what the code looks like: const repeatBlock = (block, start, end, array) => { let newData = { "tp1": "tlp", "tp0": "trp", "p1": "lp", "p0": "rp" }; for (let i = start; i <= end; i++) { let oldBlock = block; if (newData.hasOwnProperty(block+(end-i))) { block = newData[block+(end-i)]; } array[i] = block; block = oldBlock; } } let level1_1Overworld = []; for (let i = 0; i <= 14; i++) { level1_1Overworld[i] = []; repeatBlock("", 0, 227, level1_1Overworld[i]); } level1_1Overworld[2][198] = "f"; level1_1Overworld[5][22] = "q c"; repeatBlock("b", 80, 87, level1_1Overworld[5]); repeatBlock("b", 91, 93, level1_1Overworld[5]); level1_1Overworld[5][94] = "q c"; level1_1Overworld[5][109] = "q p"; repeatBlock("b", 121, 123, level1_1Overworld[5]); level1_1Overworld[5][128] = "b"; repeatBlock("q c", 129, 130, level1_1Overworld[5]); level1_1Overworld[5][131] = "b"; repeatBlock("s", 188, 189, level1_1Overworld[5]); repeatBlock("s", 187, 189, level1_1Overworld[6]); repeatBlock("s", 186, 189, level1_1Overworld[7]); level1_1Overworld[8][65] = "h"; repeatBlock("", 66, 184, level1_1Overworld[8]); repeatBlock("s", 185, 189, level1_1Overworld[8]); level1_1Overworld[8][202] = "C";
{ "domain": "codereview.stackexchange", "id": 44818, "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, performance, ecmascript-6, html5, canvas", "url": null }
javascript, performance, ecmascript-6, html5, canvas level1_1Overworld[9][16] = "q c"; level1_1Overworld[9][20] = "b"; level1_1Overworld[9][21] = "q p"; level1_1Overworld[9][22] = "b"; level1_1Overworld[9][23] = "q c"; level1_1Overworld[9][24] = "b"; repeatBlock("tp", 46, 47, level1_1Overworld[9]); repeatBlock("tp", 57, 58, level1_1Overworld[9]); level1_1Overworld[9][77] = "b"; level1_1Overworld[9][78] = "q p"; level1_1Overworld[9][79] = "b"; level1_1Overworld[9][94] = "b m"; level1_1Overworld[9][100] = "b"; level1_1Overworld[9][101] = "b s"; level1_1Overworld[9][106] = "q c"; level1_1Overworld[9][109] = "q c"; level1_1Overworld[9][112] = "q c"; level1_1Overworld[9][118] = "b"; repeatBlock("b", 129, 130, level1_1Overworld[9]); level1_1Overworld[9][137] = "s"; level1_1Overworld[9][140] = "s"; repeatBlock("s", 151, 152, level1_1Overworld[9]); level1_1Overworld[9][155] = "s"; repeatBlock("b", 168, 169, level1_1Overworld[9]); level1_1Overworld[9][170] = "q c"; level1_1Overworld[9][171] = "b"; repeatBlock("", 172, 183, level1_1Overworld[9]); repeatBlock("s", 184, 189, level1_1Overworld[9]); repeatBlock("tp", 38, 39, level1_1Overworld[10]); repeatBlock("p", 46, 47, level1_1Overworld[10]); repeatBlock("p", 57, 58, level1_1Overworld[10]); repeatBlock("s", 136, 137, level1_1Overworld[10]); repeatBlock("s", 140, 141, level1_1Overworld[10]); repeatBlock("s", 150, 152, level1_1Overworld[10]); repeatBlock("s", 155, 156, level1_1Overworld[10]); repeatBlock("s", 183, 189, level1_1Overworld[10]);
{ "domain": "codereview.stackexchange", "id": 44818, "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, performance, ecmascript-6, html5, canvas", "url": null }
javascript, performance, ecmascript-6, html5, canvas repeatBlock("tp", 28, 29, level1_1Overworld[11]); repeatBlock("p", 38, 39, level1_1Overworld[11]); repeatBlock("p", 46, 47, level1_1Overworld[11]); repeatBlock("p", 57, 58, level1_1Overworld[11]); repeatBlock("s", 135, 137, level1_1Overworld[11]); repeatBlock("s", 140, 142, level1_1Overworld[11]); repeatBlock("s", 149, 152, level1_1Overworld[11]); repeatBlock("s", 155, 157, level1_1Overworld[11]); repeatBlock("tp", 163, 164, level1_1Overworld[11]); repeatBlock("tp", 179, 180, level1_1Overworld[11]); repeatBlock("s", 182, 189, level1_1Overworld[11]); repeatBlock("p", 28, 29, level1_1Overworld[12]); repeatBlock("p", 38, 39, level1_1Overworld[12]); repeatBlock("p", 46, 47, level1_1Overworld[12]); repeatBlock("p", 57, 58, level1_1Overworld[12]); repeatBlock("s", 134, 137, level1_1Overworld[12]); repeatBlock("s", 140, 143, level1_1Overworld[12]); repeatBlock("s", 148, 152, level1_1Overworld[12]); repeatBlock("s", 155, 158, level1_1Overworld[12]); repeatBlock("p", 163, 164, level1_1Overworld[12]); repeatBlock("p", 179, 180, level1_1Overworld[12]); repeatBlock("s", 181, 189, level1_1Overworld[12]); level1_1Overworld[12][198] = "s"; for (let i = 13; i <= 14; i++) { repeatBlock("g", 0, 68, level1_1Overworld[i]); repeatBlock("g", 71, 85, level1_1Overworld[i]); repeatBlock("g", 89, 152, level1_1Overworld[i]); repeatBlock("g", 155, 227, level1_1Overworld[i]); } //1-1 Bonus 16x15 let level1_1Bonus = []; for (let i = 0; i <= 15; i++) { level1_1Bonus[i] = []; repeatBlock("", 0, 15, level1_1Bonus[i]); } for (let i = 2; i <= 12; i++) { level1_1Bonus[i][0] = "b"; if (i < 11) { level1_1Bonus[i][15] = "lp"; } } repeatBlock("b", 4, 10, level1_1Bonus[2]); repeatBlock("c", 5, 9, level1_1Bonus[5]); repeatBlock("c", 4, 10, level1_1Bonus[7]); repeatBlock("c", 4, 10, level1_1Bonus[9]); for (let i = 10; i <= 12; i++) { repeatBlock("b", 4, 10, level1_1Bonus[i]); }
{ "domain": "codereview.stackexchange", "id": 44818, "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, performance, ecmascript-6, html5, canvas", "url": null }
javascript, performance, ecmascript-6, html5, canvas for (let i = 10; i <= 12; i++) { repeatBlock("b", 4, 10, level1_1Bonus[i]); } level1_1Bonus[11][13] = "spul"; level1_1Bonus[11][14] = "spum"; level1_1Bonus[11][15] = "spur"; level1_1Bonus[12][13] = "spll"; level1_1Bonus[12][14] = "splm"; level1_1Bonus[12][15] = "splr"; for (let i = 13; i <= 14; i++) { repeatBlock("g", 0, 15, level1_1Bonus[i]); } After the arrays I have a function that translates each index of the array to what it's corresponding type would be. This code works and I am able to render everything properly but I feel like there could be a better way to create this data especially when this is only the first level. Any ideas? Answer: Creating complex maps. Your method That is some very ugly looking code you have. Just to move an item would take a lot of work, and could potentially break the game each time you make changes. I am way to old for Super Mario Bros (it was a kids game to me at the time) so I am not sure of what should be what in your code. I have no clue what your map looks like and what each block is (apart from "g" which I guess is ground) Visual editor Ideally you would write a custom map editor. That is a lot of extra work, but there are other ways to visually create 2D arrays of data. Abstract blocks Image editor You can use a basic image editor, where each pixel represents a block (abstracted blocks as pixels). For example. Create an image that is the size of the map. Eg 228 by 15 px. Match a set of colors to each block. Eg transparent is empty block, orange is ground, etc... Load the image, scan each pixel and add the corresponding block for each color.
{ "domain": "codereview.stackexchange", "id": 44818, "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, performance, ecmascript-6, html5, canvas", "url": null }
javascript, performance, ecmascript-6, html5, canvas This is easy to do in JavaScript via the DOM's CanvasRenderingContext2D. But do note that image editors can very slightly modify pixel RGBA values, so each colour representing a block should be a range of colors. Text editor You can do the same with a text editor. Have a single character represent a block, and visually create the map in the editor. If the map is too wide, make it in sections. Example using text editor NOTE The code below is untested and likely has typos. It is meant as an example only, to be safe you should write and test your own code. The map is created as an array of string, each character represents a block. To match characters to blocks an object is create lookup the block by character blockTypes A text map below mapA is part of a level map.
{ "domain": "codereview.stackexchange", "id": 44818, "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, performance, ecmascript-6, html5, canvas", "url": null }
javascript, performance, ecmascript-6, html5, canvas //=================================================================================================================================================================================================== // Columns -> 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 // 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| | // | 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| const mapA = [// | | | | | | | | | | | | | | | | | | | /* 0 */ ` ', /* 1 */ ` ', /* 2 */ ` ', /* 3 */ ` ', /* 4 */ ` ',
{ "domain": "codereview.stackexchange", "id": 44818, "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, performance, ecmascript-6, html5, canvas", "url": null }
javascript, performance, ecmascript-6, html5, canvas /* 5 */ ` C ', /* 6 */ ` ++++.++++++.++++++++ +++.+++.+++ +++++.+++++++++.++++++.++++++ ', /* 7 */ ` ???????? + ', /* 8 */ ` ++++ ???????? ', /* 9 */ ` ^ +++++++ ++ ', /* 10 */ ` ^ - ++++++++++ ^ ^ ++++ ^ ^ ', /* 11 */ ` ^ - - +++++++++++++ ^ - ^ - ++++ - ^ - ^ +++', /* 12 */ ` - C - C - +++++++++++++++ - C - C C - - ++++ - - C C - - h+++', /* 13 */ `#################################################################### ############## ################################################################ ##########################', /* 14 */ `#################################################################### ############## ################################################################ ##########################',
{ "domain": "codereview.stackexchange", "id": 44818, "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, performance, ecmascript-6, html5, canvas", "url": null }
javascript, performance, ecmascript-6, html5, canvas // ^ | | | | | | | | | | | | | | | | | | | // Rows | | 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| // 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| 0123456789| | // 0 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 ];
{ "domain": "codereview.stackexchange", "id": 44818, "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, performance, ecmascript-6, html5, canvas", "url": null }
javascript, performance, ecmascript-6, html5, canvas An object to lookup block types.. const blockTypes = { " ": "", "#": "g", ".": "f", "^": "q c", "-": "q p", b: "b", s: "s", h: "h", c: "C", p: "p", t: "tp", "?": "b m", "+": "b s", }; And some functions to do the work. First create an empty level map... function CreateEmptyMap(width, height, block = "") { const map = []; while (height-- > 0) { const row = []; let i = width; while (i-- > 0) { row.push(block); } map.push(row) } return map; } And a function that adds a text map to the level map. The text map can be any size, as can the level map. The text map is added to the level map at the position left, top. function AddMap(level, left, top, map, blocks = blockTypes) { var x, y = 0; const height = level.length; if (height) { const width = level[0].length; if (width) { for (const row of map) { if (top + y >= 0 && top + y < height) { x = 0; for (const char of row) { if (left + x >= 0 && left + x < width) { level[top + y][left +x] = blockTypes[char] ?? blockTypes[" "]; } x ++; } } y++ } } } return level; } Then to create the level... const level1_1Overworld = CreateEmptyMap(228, 15); // Create empty map AddMap(level1_1Overworld, 0, 0, mapA); // add mapA to level map
{ "domain": "codereview.stackexchange", "id": 44818, "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, performance, ecmascript-6, html5, canvas", "url": null }
c++, template-meta-programming, enum Title: C++ enum to string conversion utility Question: I needed to find a way to convert a bunch of enums to string for displaying in C++. The two main ways I found when searching was using dark magic macros or voodoo magic template metaprogramming. As I don't know much about any of them I thought building something myself would be a good opportunity to learn new things. Here are the features I wanted: enum to string only (no string to enum) can be added on top of legacy code (no change in enum declaration) mapping generated at compile time can use __PRETTY_FUNCTION__ (clang/gcc) or __FUNCSIG__ (msvc), but with a fallback displaying something somewhat useful on compilers without them works on enum declared inside a class works on enum with duplicate values (ok to return identical strings) use as little macro as possible, and limited to "simple" ones (e.g. defining a function is ok, defining 64 int-postfixed macros chains is not) can be used for small contiguous enums as well as ones with large arbitrary gaps between values fully automatic mapping, or at least don't crash at runtime if enum was updated with new value and the string conversion call was not be as simple as possible so future me will still be able to understand what's is going on Here is the result! I'm strill trying to simplify the declaration process to remove the macro and/or allow calling it right below the enum declaration in a header file but I haven't figured it out yet. Live example Usage example #include <iostream> enum class Test : char { neg = -8, a = 0, more_a = a, b = 3, c }; // Looks like someone forgot to update after adding Test::c, no problem DEFINE_ENUM_STRINGIFYER_RANGE(Test, Test::neg, Test::b);
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, template-meta-programming, enum enum class Test2 : unsigned short { a = 1 << 0, b = 1 << 1, c = 1 << 2, d = 1 << 3, e = 1 << 4, f = 1 << 5, g = 1 << 6, h = 1 << 7, i = 1 << 8, j = 1 << 9, }; DEFINE_ENUM_STRINGIFYER_LIST(Test2, Test2::a, Test2::b, Test2::c, Test2::d, Test2::e, // forgot f, everything is still fine Test2::g, Test2::h, Test2::i, Test2::j); int main() { std::cout << Test::neg << '\n' // Test::neg << Test::a << '\n' // Test::a << Test::more_a << '\n' // Test::a << Test::b << '\n' // Test::b << Test::c << '\n' // (Test)4 << '\n' << Test2::a << '\n' // Test2::a << Test2::b << '\n' // Test2::b << Test2::c << '\n' // Test2::c << Test2::d << '\n' // Test2::d << Test2::e << '\n' // Test2::e << Test2::f << '\n' // (Test2)32 << Test2::g << '\n' // Test2::g << Test2::h << '\n' // Test2::h << Test2::i << '\n' // Test2::i << Test2::j << '\n'; // Test2::j } enum_stringifyer.hpp #pragma once #ifndef ENUM_STRINGIFYER_HPP_ #define ENUM_STRINGIFYER_HPP_ #include <type_traits> #include <string_view> #include <array> #include <utility> #include <algorithm> namespace enum_stringifyer { template <auto V> constexpr auto enum_value_name() noexcept { static_assert(std::is_enum_v<decltype(V)>, "enum_value_name requires enum value");
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, template-meta-programming, enum // Extract value from macros, with a -1 on the size cause we don't need the last \0 in a string_view #if defined(__clang__)// "auto enum_value_name() [V = XXXXXX::XXXXX::XXXXX]" constexpr std::string_view header = "auto enum_stringifyer::enum_value_name() [V = "; constexpr std::string_view footer = "]"; return std::string_view{ __PRETTY_FUNCTION__ + header.size(), sizeof(__PRETTY_FUNCTION__) - 1 - header.size() - footer.size() }; #elif defined(__GNUC__)// "constexpr auto enum_value_name() [with auto V = XXXXXX::XXXXX::XXXXX]" constexpr std::string_view header = "constexpr auto enum_stringifyer::enum_value_name() [with auto V = "; constexpr std::string_view footer = "]"; return std::string_view{ __PRETTY_FUNCTION__ + header.size(), sizeof(__PRETTY_FUNCTION__) - 1 - header.size() - footer.size() }; #elif defined(_MSC_VER) // "auto __cdecl enum_value_name<XXXXXX::XXXXX::XXXXX>(void) noexcept" constexpr std::string_view header = "auto __cdecl enum_stringifyer::enum_value_name<"; constexpr std::string_view footer = ">(void) noexcept"; return std::string_view{ __FUNCSIG__ + header.size(), sizeof(__FUNCSIG__) - 1 - header.size() - footer.size() }; #else static_assert(false, "enum_value_name requires either __PRETTY_FUNCTION__ or __FUNCSIG__ to be available"); #endif } template <class F, class T, T ... Is> constexpr void constexpr_for(F&& f, std::integer_sequence<T, Is...> const&) { ((f(std::integral_constant<T, Is>())), ...); } template<class Enum, Enum m, Enum M> struct EnumMapperRange { static_assert(static_cast<std::underlying_type_t<Enum>>(M) >= static_cast<std::underlying_type_t<Enum>>(m), "M must be >= m");
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, template-meta-programming, enum constexpr EnumMapperRange() : mapping(), start(static_cast<std::underlying_type_t<Enum>>(m)), end(static_cast<std::underlying_type_t<Enum>>(M)) { // Same as a for loop, but with constexpr friendly i //for (auto i = 0; i < end - start + 1; ++i) //{ // mapping[i] = enum_value_name<static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(m) + i)>(); //} constexpr_for([this](auto i) { mapping[i] = enum_value_name<static_cast<Enum>(static_cast<std::underlying_type_t<Enum>>(m) + i)>(); }, std::make_integer_sequence<std::underlying_type_t<Enum>, static_cast<std::underlying_type_t<Enum>>(M) - static_cast<std::underlying_type_t<Enum>>(m) + 1>{}); } std::array<std::string_view, static_cast<std::underlying_type_t<Enum>>(M) - static_cast<std::underlying_type_t<Enum>>(m) + 1> mapping; const std::underlying_type_t<Enum> start; const std::underlying_type_t<Enum> end; }; template<class Enum, Enum... pack> constexpr std::array<std::pair<Enum, std::string_view>, sizeof...(pack)> GetNamedEnum() { return { std::make_pair(pack, enum_value_name<pack>())... }; } } #define DECLARE_ENUM_STRINGIFYER(Enum) std::ostream& operator <<(std::ostream& os, const Enum v)
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, template-meta-programming, enum #define DECLARE_ENUM_STRINGIFYER(Enum) std::ostream& operator <<(std::ostream& os, const Enum v) #if defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER) #define DEFINE_ENUM_STRINGIFYER_RANGE(Enum, min_value, max_value) \ std::ostream& operator <<(std::ostream& os, const Enum v) \ { \ static_assert(std::is_same_v<decltype(min_value), Enum>, "min_value must be "#Enum); \ static_assert(std::is_same_v<decltype(max_value), Enum>, "max_value must be "#Enum); \ static constexpr auto mapper = enum_stringifyer::EnumMapperRange<Enum, min_value, max_value>(); \ if (static_cast<std::underlying_type_t<Enum>>(v) < mapper.start || \ static_cast<std::underlying_type_t<Enum>>(v) > mapper.end) \ { \ return os << '(' << #Enum << ')' << static_cast<int>(v); \ } \ return os << mapper.mapping[static_cast<std::underlying_type_t<Enum>>(v) - mapper.start]; \ } static_assert(true, "") /* To require a ; after macro call */ #else // min_value and max_value are not necessary, but keep them to get the same interface #define DEFINE_ENUM_STRINGIFYER_RANGE(Enum, min_value, max_value) \ std::ostream& operator <<(std::ostream& os, const Enum v) \ { \ return os << '(' << #Enum << ')' << static_cast<int>(v); \ } static_assert(true, "") /* To require a ; after macro call */ #endif
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, template-meta-programming, enum #if defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER) #define DEFINE_ENUM_STRINGIFYER_LIST(Enum, ...) \ std::ostream& operator <<(std::ostream& os, const Enum v) \ { \ static constexpr auto mapper = enum_stringifyer::GetNamedEnum<Enum, __VA_ARGS__>(); \ const auto it = std::find_if(mapper.begin(), mapper.end(), \ [v](const std::pair<Enum, std::string_view>& p) { return p.first == v; }); \ if (it == mapper.end()) \ { \ return os << '(' << #Enum << ')' << static_cast<int>(v); \ } \ return os << it->second; \ } static_assert(true, "") /* To require a ; after macro call */ #else // value list is not necessary, but keep it to get the same interface #define DEFINE_ENUM_STRINGIFYER_LIST(Enum, ...) \ std::ostream& operator <<(std::ostream& os, const Enum v) \ { \ return os << '(' << #Enum << ')' << static_cast<int>(v); \ } static_assert(true, "") /* To require a ; after macro call */ #endif #endif
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, template-meta-programming, enum #endif Answer: Given the requirement that this code needs to work with already declared enums which's definitions you cannot change, there really is no way other than __PRETTY_FUNCTION__ or using an experimental implementation of static reflections, like reflexpr. Your implementation of enum_value_name() makes sense, but everything past that could use a massive re-design. Let's focus on various minor issues first: Repetition of static_cast<std::underlying_type_t<E>> C++23 has added std::to_underlying() to eliminate this pattern, and you can easily implement it yourself: template <typename E> constexpr std::underlying_type_t<E> to_underlying(E e) noexcept { return static_cast<std::underlying_type_t<E>>(e); } Repetition in enum_value_name(), misuse of static_assert The way you obtain the enum name between header and footer is self-documenting, so the comments are redundant. Also, you do the same thing for every compiler, but repeat your math for finding the right substring. Also, static_assert(false) will always trigger (until C++23, in some situations), so basically you're failing to compile with something other than GCC, clang, or MSVC. Here is how you can solve these problems: #if defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER) inline constexpr bool has_pretty_name = true; #else inline constexpr bool has_pretty_name = false; #endif template <auto V> constexpr auto enum_value_name() noexcept { static_assert(std::is_enum_v<decltype(V)>, "enum_value_name requires enum value"); // V == V makes the expression dependent on V. // The assertion only evaluates if the function template is instantiated. static_assert(V == V && has_pretty_name, "enum_value_name requires either __PRETTY_FUNCTION__ or __FUNCSIG__ to be available");
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, template-meta-programming, enum #if defined(__clang__) constexpr std::string_view header = "auto enum_stringifyer::enum_value_name() [V = "; constexpr std::string_view footer = "]"; constexpr std::string_view name = __PRETTY_FUNCTION__; #elif defined(__GNUC__) constexpr std::string_view header = "constexpr auto enum_stringifyer::enum_value_name() [with auto V = "; constexpr std::string_view footer = "]"; constexpr std::string_view name = __PRETTY_FUNCTION__; #elif defined(_MSC_VER) constexpr std::string_view header = "auto __cdecl enum_stringifyer::enum_value_name<"; constexpr std::string_view footer = ">(void) noexcept"; constexpr std::string_view name = __FUNCSIG__; #endif // extract everything between header and footer return name.substr(header.size(), name.length() - header.length() - footer.length()); } Notice that no matter whether we use __PRETTY_FUNCTION__ or __FUNCSIG__, we can always capture this string literal in a std::string_view, which simplifies this code a bit. Multiple Issues with EnumMapperRange The beginning and end of the range are template parameters m and M. No one forces you to use single-character identifiers, let alone same-single-character identifiers with different case. The convention in the C++ standard is for all template parameters to be PascalCase, with sane names. EnumMapperRange has non-static data members, but all of them are compile-time properties. Making them static inline constexpr would make more sense. Your code is needlessly generic. You have made a constexpr_for that works with any function and any integer sequence, but you only need it in a single place, doing exactly one thing, with an integer sequence of std::size_t. Let's fix those problems: template<class Enum, Enum Begin, Enum End> struct EnumMapperRange { using underlying_type = std::underlying_type_t<Enum>;
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, template-meta-programming, enum static inline constexpr underlying_type begin = to_underlying(Begin); static inline constexpr underlying_type end = to_underlying(End); static_assert(end >= begin, "end must be >= m"); using array_type = std::array<std::string_view, end - begin + 1>; template <std::size_t ... Is> static constexpr array_type make_mapping(std::index_sequence<Is...>) { array_type result{}; ((result[Is] = enum_value_name<static_cast<Enum>(begin + Is)>()), ...); return result; } static inline constexpr array_type mapping = make_mapping(std::make_index_sequence<array_type{}.size()>{}); };
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, template-meta-programming, enum Insufficient macro sanitization Part of why macros are so evil is that they can be used anywhere, even in namespaces where someone has defined their own namespace xyz::enum_stringifyer or namespace xyz::std. All non-local symbols should be accessed using their fully qualified names: #define DEFINE_ENUM_STRINGIFYER_RANGE(Enum, min_value, max_value) \ std::ostream& operator <<(std::ostream& os, const Enum v) \ { \ static_assert(::std::is_same_v<decltype(min_value), Enum>, "min_value must be "#Enum); \ static_assert(::std::is_same_v<decltype(max_value), Enum>, "max_value must be "#Enum); \ using mapper = ::enum_stringifyer::EnumMapperRange<Enum, min_value, max_value>; \ if (::enum_stringifyer::to_underlying(v) < mapper::begin \ || ::enum_stringifyer::to_underlying(v) > mapper::end) \ { \ return os << '(' << #Enum << ')' << static_cast<int>(v); \ } \ return os << mapper::mapping[::enum_stringifyer::to_underlying(v) - mapper::begin]; \ } static_assert(true, "") /* To require a ; after macro call */
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, template-meta-programming, enum Fundamental Redesign As we go further down in the code, we end up in a macro hell where operator overloads are defined in macros. Macros should generally be minimal crutches that help us deal with minor problems that templates cannot overcome. The implementation of operator<< doesn't need to be a macro at all. We can write the following: template <typename Enum> auto operator<<(std::ostream& os, const Enum v) -> std::enable_if_t<std::is_enum_v<Enum> && enum_stringifyer::has_enum_traits<Enum>::value, std::ostream&> { using namespace enum_stringifyer; if constexpr (has_enum_traits_list<Enum>::value) { static constexpr auto names = make_listed_names<Enum>(); for (std::size_t i = 0; i < std::size(enum_traits<Enum>::list); ++i) { if (v == enum_traits<Enum>::list[i]) { return os << names[i]; } } } else if constexpr (has_enum_traits_range<Enum>::value) { static constexpr auto names = make_range_names<Enum>(); constexpr auto begin = to_underlying(enum_traits<Enum>::begin); constexpr auto end = to_underlying(enum_traits<Enum>::end); auto underlying = to_underlying(v); if (underlying >= begin && underlying <= end) { return os << names[underlying - begin]; } } // zero_name should be Enum::ZERO, or (Enum)0 static constexpr std::string_view zero_name = enum_value_name<Enum{0}>(); static constexpr std::string_view fallback_name = enum_value_enum_name(zero_name); return os << '(' << fallback_name << ')' << +to_underlying(v); } We need the following to make this happen: create an enum_traits template which acts as a customization point, similar to std::iterator_traits add some "member detector idioms" to detect what static members the user has defined in the traits refactor the stringification of name lists and name ranges into function templates:
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, template-meta-programming, enum make_listed_names which converts the list of enums into a list of std::string_view make_range_names which converts the range of enums into a list of std::string_view an enum_value_enum_make function that maps Enum::ZERO onto Enum The customization on the user's end looks like this: template <> struct enum_stringifyer::enum_traits<Test> { static inline constexpr Test begin = Test::neg; static inline constexpr Test end = Test::b; }; and template <> struct enum_stringifyer::enum_traits<Test2> { static inline constexpr std::array list = { Test2::a, Test2::b, Test2::c, Test2::d, Test2::e, Test2::g, Test2::h, Test2::i, Test2::j }; }; See live implementation
{ "domain": "codereview.stackexchange", "id": 44819, "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++, template-meta-programming, enum", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel Title: Unit testing a Linked List implementation in C++ Question: Recently I wanted to use the gtest library to unit test my program but for some reason, it's incredibly hard to make it work and configure (at least for me it was), so I decided to make my own, following the style Google uses. I set a goal for this summer and it is to make a Linked List library similar to std::list. I think I am getting there slowly and making some good progress on the way. So far I've implemented about 20 methods and there is more to come. I decided to use the TEST class to test it and it worked well I think. Currently, I am using bubble sort to sort my list which runs in O(n^2), so an implementation of an O(nlogn) is on the todo list I am also using recursion in some places which will probably gobble up all my space for larger inputs. I am working on an iterative solution and comparing results to see if it's even worth it... (recursive code looks cleaner IMHO) I am also missing iterators to traverse the list but when I thought about implementing them I saw they exceed my knowledge of C++ (for now) No restrictions, this is a personal project I would like to know where I can improve my code and make it faster for larger input. I would also like to know if there are some major design flaws I should be aware of before proceeding, some code is repetitive but that's because I don't fully understand how std::function() works. Is there a better way to write Makefiles? I have been CmdC + CmdV the same exact one since I started working with classes in C++. (not a joke) I built the project in XCode but I also wrote a MakeFile so it should compile. For me, it compiles with [compiler]: Apple LLVM 14.0.3 (clang-1403.0.22.14.1) P.S.:
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel I know std::list is a doubly linked list...mine is not and I am planning on making one later on, that's why I used a namespace to distinguish them. Please let me know if this is not the right approach and if some other OOP method would be a better fit. I eventually want to avoid namespace pollution since most of the methods would have the same name. Perhaps making all of the methods in one class static? (doesn’t sound productive but could it work?) There are some #include "___.cpp" which might come as cringe to some more experienced programmers but I had some linking issues and kept getting an assembly error, including .cpp instead of .h fixed my issue. I am aware that grabbing and pasting the whole code base is considered unpractical. Edit: I see my question hasn't been answered for a while, is it perhaps not specific enough? I set a bounty hoping it would help. main.cpp // // main.cpp // linked_list_xcode // // Created by Jakob Balkovec on 13/06/2023. // #include <iostream> #include "single_l.h" #include "test.h" // { // Un-comment test macro to run all tests // } // #define TEST // { // Un-comment example macro to run example // } // #define EXAMPLE // { // { // Simple LL problem implemented in the example function // } // Problem Name: Merge Two Sorted Lists // You are given two sorted linked lists, list1 and list2, where each list is sorted // in non-decreasing order. Your task is to merge these two lists into a single // sorted linked list and return the head of the merged list. // Example: // Input: // list1: 1 -> 2 -> 3 // list2: 4 -> 5 -> 6 // Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 // Write a function mergeSortedLists that takes two sorted linked lists list1 and list2 // as parameters and returns the new merged list. // You can assume the following:
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel // You can assume the following: // The linked lists are non-empty. // The nodes of each list contain data of type T. // The lists are already sorted in non-decreasing order. // Note: You should not modify the original lists; instead, // you should create a new list with the merged elements. // } /** { * Displays information about the last compilation of the file. * @return void } **/ static inline void show_last_compiled() { std::cout << "\n[file]: " << __FILE__ << '\n' << "[compiled on]: " << __DATE__ << " at " << __TIME__ << '\n' << "[compiler]: " << __VERSION__ << '\n' << "[timestamp]: " << __TIMESTAMP__ << '\n'; } /** * The main function of the C++ program. It runs either the tests or the example * depending on the macros defined. If no macros are defined, it prints a message * to the console. * * @param argc the number of command line arguments * @param argv an array of the command line argument strings * * @return integer value EXIT_SUCCESS (0) upon successful execution * * @throws None */ int main(int argc, const char * argv[]) { show_last_compiled(); #ifdef TEST bool all_passed = run_tests(); if(all_passed) std::cout << "\n\n[all tests passed]\n\n"; else std::cout << "\n\n[some tests failed, check and see which]\n\n" #endif #ifdef EXAMPLE run_example(); #endif #ifndef TEST #ifndef EXAMPLE std::cout << "\n[Un-comment a macro to run]\n\n"; #endif #endif return EXIT_SUCCESS; } single_l.cpp // // single_l.cpp // linked_list_xcode // // Created by Jakob Balkovec on 13/06/2023. // #include <iostream> #include <unordered_set> #include <stdexcept> #include "single_l.h" namespace single { /** * Creates a new single linked list * @throws None */ template <class T> single_l<T>::single_l() : head(nullptr) {}
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Creates a new single linked list with the elements from the * specified initializer list. * @param initList the initializer list containing the elements to add * @throws None */ template <class T> single_l<T>::single_l(std::initializer_list<T> initList) : head(nullptr) { for (const T& value : initList) { push_back(value); } } /** * Destructor for the single_l class. * @param None * @return None * @throws None */ template <class T> single_l<T>::~single_l() { clear(); } /** * Constructs a new single linked list by copying all elements of another * linked list. * @param other The linked list to copy from. * @throws None */ template <class T> single_l<T>::single_l(const single_l& other) : head(nullptr) { const single_l<T>::node* current = other.head; while (current != nullptr) { push_back(current->data_); current = current->next_; } } /** * Constructs a single linked list by moving the contents of another single * linked list, setting its head pointer to null afterwards. * @param other the single linked list to move from * @return none * @throws none */ template <class T> single_l<T>::single_l(single_l&& other) : head(nullptr) { head = other.head; other.head = nullptr; } /** * @brief Assignment operator for the single_l class. * @tparam T The type of elements in the list. * @param other The list to be assigned. * @return Reference to the modified list. */ template <class T> single_l<T>& single_l<T>::operator=(const single_l& other) { if (this != &other) { clear();
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel const single_l<T>::node* current = other.head; while (current != nullptr) { push_back(current->data_); current = current->next_; } } return *this; } /** * @brief Move assignment operator for the single_l class. * @tparam T The type of elements in the list. * @param other The list to be moved. * @return Reference to the modified list. */ template <class T> single_l<T>& single_l<T>::operator=(single_l&& other) { if (this != &other) { clear(); head = other.head; other.head = nullptr; } return *this; } /** * Adds a new node with the given data to the end of the linked list. * @param data the data to be added to the linked list * @return void * @throws none */ template <class T> void single_l<T>::push_back(const T& data) { single_l<T>::node* new_node = new single_l<T>::node{ data, nullptr }; if (head == nullptr) { head = new_node; } else { single_l<T>::node* current = head; while (current->next_ != nullptr) { current = current->next_; } current->next_ = new_node; } return; } /** * Adds a new node to the front of the linked list. * @param data The data to be stored in the new node. * @return void. * @throws None. */ template <class T> void single_l<T>::push_front(const T& data) { single_l<T>::node* new_node = new single_l<T>::node{ data, head }; head = new_node; return; }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Removes the last element of the single linked list. Throws a runtime error * if the list is empty. * @throws std::runtime_error [pop_back()] [list is empty] */ template <class T> void single_l<T>::pop_back() { try { if (head == nullptr) { throw std::runtime_error("[pop_back()] [list is empty]\n"); } else if (head->next_ == nullptr) { delete head; head = nullptr; } else { single_l<T>::node* current = head; while (current->next_->next_ != nullptr) { current = current->next_; } delete current->next_; current->next_ = nullptr; } } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; } return; } /** * Pops the first element from the list. * @param None * @return None * @throws std::runtime_error if the list is empty */ template <class T> void single_l<T>::pop_front() { try { if (head == nullptr) { throw std::runtime_error("[pop_front()] [list is empty]\n"); } single_l<T>::node* temp = head; head = head->next_; delete temp; } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; } return; } /** * Recursively prints the linked list in reverse order, starting from the given node. * @param current pointer to the current node being processed * @return void * @throws none */ template <class T> void single_l<T>::print_reverse_helper(single_l<T>::node* current) { if (current == nullptr) { return; } print_reverse_helper(current->next_); std::cout << current->data_ << " "; }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Recursively prints the data of each node in a single linked list, starting from * the given node. * @param current the node to start printing from * @return void */ template <class T> void single_l<T>::print_helper(single_l<T>::node* current) { if (current == nullptr) { return; } std::cout << current->data_ << " "; print_helper(current->next_); } /** * Prints the contents of the list in reverse order. * @throws std::runtime_error if the list is empty */ template <class T> void single_l<T>::print_reverse() { try { if (head == nullptr) { throw std::runtime_error("[print_reverse()] [list is empty]"); } std::cout << "{ "; print_reverse_helper(head); std::cout << "}"; std::cout << std::endl; } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; } } /** * Prints the elements of the single linked list. * @throws std::runtime_error if the list is empty. */ template <class T> void single_l<T>::print() { try { if (head == nullptr) { throw std::runtime_error("[print()] [list is empty]"); } std::cout << "{ "; print_helper(head); std::cout << "}"; std::cout << std::endl; } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; } } /** * Clears the linked list by deleting all nodes. Starts from the head of the * linked list and deletes each node until the list is empty. * @param None * @return None * @throws None */ template <class T> void single_l<T>::clear() { while (head != nullptr) { single_l<T>::node* temp = head; head = head->next_; delete temp; } }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Swaps the head of this list with another list's head. * @param other The other list to swap heads with. * @throws None */ template <class T> void single_l<T>::swap(single_l& other) { std::swap(head, other.head); } /** * Determines whether the single_l<T> object is empty. * @return true if the object is empty, false otherwise */ template <class T> bool single_l<T>::empty() { return (head == nullptr) ? true : false; } /** * Returns the number of nodes in the linked list. * @param None * @return size_t The number of nodes in the linked list. * @throws None */ template <class T> size_t single_l<T>::size() { size_t count = 0; single_l<T>::node* current = head; while (current != nullptr) { count++; current = current->next_; } return count; } /** * @brief Returns a reference to the first element in the list. * @tparam T The type of elements in the list. * @return Reference to the first element. * @throw std::runtime_error If the list is empty. */ template <class T> T& single_l<T>::front() { try { if (head == nullptr) { throw std::runtime_error("[front()] [list is empty]"); } return head->data_; } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; } static T default_value; return default_value; }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * @brief Returns a reference to the last element in the list. * @tparam T The type of elements in the list. * @return Reference to the last element. * @throw std::runtime_error If the list is empty. */ template <class T> T& single_l<T>::back() { try { if (head == nullptr) { throw std::runtime_error("[back()] [list is empty]"); } single_l<T>::node* current = head; while (current->next_ != nullptr) { current = current->next_; } return current->data_; } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; } static T default_value; return default_value; } /** * @brief Returns a const reference to the first element in the list. * @tparam T The type of elements in the list. * @return Const reference to the first element. * @throw std::runtime_error If the list is empty. */ template <class T> const T& single_l<T>::front() const { try { if (head == nullptr) { throw std::runtime_error("[front() cosnt] [list is empty]"); } return head->data_; } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; } static T default_value; return default_value; }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * @brief Returns a const reference to the last element in the list. * @tparam T The type of elements in the list. * @return Const reference to the last element. * @throw std::runtime_error If the list is empty. */ template <class T> const T& single_l<T>::back() const { try { if (head == nullptr) { throw std::runtime_error("[back() cosnt] [list is empty]"); } single_l<T>::node* current = head; while (current->next_ != nullptr) { current = current->next_; } return current->data_; } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; } static T default_value; return default_value; } /** * @brief Accesses the element at the specified index in the list. * @tparam T The type of elements in the list. * @param index The index of the element to access. * @return Reference to the element at the specified index. * @throw std::runtime_error If the list is empty. * @throw std::out_of_range If the index is out of range. */ template <class T> T& single_l<T>::operator[](size_t index) { try { if (head == nullptr) { throw std::runtime_error("[operator[]] [list is empty]"); } single_l<T>::node* current = head; size_t count = 0; while (current != nullptr) { if (count == index) { return current->data_; } current = current->next_; count++; } throw std::out_of_range("[operator[]] [index out of range]"); } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; } static T default_value; return default_value; }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * @brief Accesses the element at the specified index in the list (const version). * @tparam T The type of elements in the list. * @param index The index of the element to access. * @return Const reference to the element at the specified index. * @throw std::runtime_error If the list is empty. * @throw std::out_of_range If the index is out of range. */ template <class T> const T& single_l<T>::operator[](size_t index) const { try { if (head == nullptr) { throw std::runtime_error("[operator[] const] [list is empty]"); } single_l<T>::node* current = head; size_t count = 0; while (current != nullptr) { if (count == index) { return current->data_; } current = current->next_; count++; } throw std::out_of_range("[operator[] const] [index out of range]"); } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; } } /** * @brief Accesses the element at the specified index in the list. * @tparam T The type of elements in the list. * @param index The index of the element to access. * @return Reference to the element at the specified index. * @throw std::runtime_error If the list is empty. * @throw std::out_of_range If the index is out of range. */ template <class T> T& single_l<T>::at(size_t index) { try { if (head == nullptr) { throw std::runtime_error("[at()] [list is empty]"); } single_l<T>::node* current = head; size_t count = 0; while (current != nullptr) { if (count == index) { return current->data_; } current = current->next_; count++; } throw std::out_of_range("[at()] [index out of range]"); } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; } static T default_value; return default_value; }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * @brief Deletes the element at the specified index in the list. * @tparam T The type of elements in the list. * @param index The index of the element to delete. * @throw std::runtime_error If the list is empty. * @throw std::out_of_range If the index is out of range. */ template <class T> void single_l<T>::delete_at(size_t index) { try { if (head == nullptr) { throw std::runtime_error("[delete_at()] [list is empty]"); } if (index == 0) { pop_front(); return; } single_l<T>::node* current = head; single_l<T>::node* previous = nullptr; size_t count = 0; while (current != nullptr) { if (count == index) { if (previous != nullptr) { previous->next_ = current->next_; } else { head = current->next_; } delete current; return; } previous = current; current = current->next_; count++; } throw std::out_of_range("[delete_at()] [index out of range]"); } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; throw; // rethrow the exception to propagate it } } /** * @brief Deletes the first occurrence of the specified value in the list. * @tparam T The type of elements in the list. * @param data The value to delete. * @throw std::runtime_error If the list is empty or the value is not found. */ template <class T> void single_l<T>::delete_value(const T& data) { try { if (head == nullptr) { throw std::runtime_error("[delete_value()] [list is empty]"); } single_l<T>::node* current = head; single_l<T>::node* previous = nullptr;
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel single_l<T>::node* current = head; single_l<T>::node* previous = nullptr; while (current != nullptr) { if (current->data_ == data) { if (previous == nullptr) { head = current->next_; } else { previous->next_ = current->next_; } delete current; return; } previous = current; current = current->next_; } throw std::runtime_error("[delete_value()] [value not found]"); } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; throw; // rethrow the exception to propagate it } } /** * Searches for the given data element in the single linked list and returns * the index of the first occurrence. If the element is not found, it returns * -1. * @param data The element to search in the linked list. * * @return The index of the first occurrence of the element in the linked list. * If the element is not found, it returns -1. * @throws None */ template <class T> size_t single_l<T>::search(const T& data) { size_t index = 0; single_l<T>::node* current = head; while (current != nullptr) { if (current->data_ == data) { return index; } current = current->next_; index++; } return static_cast<size_t>(-1); // return -1 if value not found for clarity }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Inserts a new node with given data at the specified position in the linked list. * @param position_data the data to be inserted at the specified position * @param position the position at which the new node is to be inserted * @throws std::runtime_error if the list is empty * @throws std::out_of_range if the position is out of range */ template <class T> void single_l<T>::at_position(const T& position_data, size_t position) { try { if (head == nullptr) { throw std::runtime_error("[at_position()] [list is empty]"); } single_l<T>::node* current = head; single_l<T>::node* previous = nullptr; size_t count = 0; while (current != nullptr) { if (count == position) { single_l<T>::node* new_node = new single_l<T>::node; new_node->data_ = position_data; new_node->next_ = current; if (previous == nullptr) { head = new_node; } else { previous->next_ = new_node; } return; } previous = current; current = current->next_; count++; } throw std::out_of_range("[at_position()] [position out of range]"); } catch (const std::exception& e) { std::cerr << "{error}: " << e.what() << std::endl; throw; // rethrow the exception to propagate it } } /** * Reverses the order of the nodes in a singly linked list. * @param none * @return void * @throws none */ template <class T> void single_l<T>::reverse() { if (head == nullptr || head->next_ == nullptr) { return; } single_l<T>::node* current = head; single_l<T>::node* previous = nullptr; single_l<T>::node* next = nullptr; while (current != nullptr) { next = current->next_; current->next_ = previous; previous = current; current = next; } head = previous; }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel head = previous; } /** * Sorts the linked list in ascending order using bubble sort algorithm. * @param None. * @return None. * @throws None. */ template <class T> void single::single_l<T>::sort() { if (head == nullptr || head->next_ == nullptr) { return; } bool swapped; single_l<T>::node* current; single_l<T>::node* last = nullptr; do { swapped = false; current = head; while (current->next_ != last) { if (current->data_ > current->next_->data_) { std::swap(current->data_, current->next_->data_); swapped = true; } current = current->next_; } last = current; } while (swapped); } /** * Removes duplicates from a singly linked list. * @param None * @return None * @throws None */ template <class T> void single_l<T>::remove_duplicates() { if (head == nullptr || head->next_ == nullptr) { return; } std::unordered_set<T> unique_value; single_l<T>::node* current = head; single_l<T>::node* previous = nullptr; while (current != nullptr) { if (unique_value.count(current->data_) > 0) { previous->next_ = current->next_; delete current; current = previous->next_; } else { unique_value.insert(current->data_); previous = current; current = current->next_; } } } /** * Resizes the list to contain n elements. * @param n the new size of the list * @return void * @throws None */ template <class T> void single::single_l<T>::resize(size_t n) { if (n == 0) { clear(); } else if (n > size()) { size_t additional_nodes = n - size(); if (head == nullptr) { head = new node; head->next_ = nullptr; additional_nodes--; } node* current = head; while (current->next_ != nullptr) { current = current->next_; }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel for (size_t i = 0; i < additional_nodes; i++) { node* new_node = new node; new_node->next_ = nullptr; current->next_ = new_node; current = new_node; } } else if (n < size()) { node* current = head; node* previous = nullptr; for (size_t i = 0; i < n; i++) { previous = current; current = current->next_; } while (current != nullptr) { node* next_node = current->next_; delete current; current = next_node; } previous->next_ = nullptr; } } } //namespace single single_l.h // // single_l.h // linked_list_xcode // // Created by Jakob Balkovec on 13/06/2023. // #ifndef single_l_h #define single_l_h #include <iostream> namespace single { template <class T> class single_l final { private: struct node { T data_; node* next_; }; struct node* head; public: single_l(); single_l(std::initializer_list<T>_init_); ~single_l(); single_l(const single_l&); single_l(single_l&&); single_l& operator=(const single_l&); single_l& operator=(single_l&&); void push_back(const T&); void push_front(const T&); void pop_back(); void pop_front(); void print(); void print_reverse(); void print_helper(single_l<T>::node* current); void print_reverse_helper(single_l<T>::node* current); void clear(); void swap(single_l&); bool empty(); size_t size(); T& front(); T& back(); const T& front() const; const T& back() const; T& operator[](size_t); const T& operator[](size_t) const; T& at(size_t index); //inserts at index void delete_at(size_t index); void delete_value(const T &data); size_t search(const T &data); void at_position(const T& data, size_t position); //inserts at specific spot void reverse(); void sort(); void remove_duplicates(); void resize(size_t n); }; } //namespace single
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel #endif /* single_l_h */ test_file.h // // test_file.h // linked_list_xcode // // Created by Jakob Balkovec on 13/06/2023. // #ifndef test_file_h #define test_file_h #include <iostream> #include <string>
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel template <class T> class TEST { private: /** * Prints a test passing message with an optional function name. * @param func_name an optional name of the function being tested * @return void * @throws none */ static void PRINT_PASS(const std::string& func_name = "") { std::cout << "[TEST " << func_name << " PASSED]" << std::endl; } /** * Prints a failure message for a test, including an optional message and function name. * @param message the message to include in the failure message (optional) * @param func_name the name of the function being tested (optional) * @return void * @throws none */ static void PRINT_FAIL(const std::string& message, const std::string& func_name = "") { std::cout << "[TEST " << func_name << " FAILED]"; if (!message.empty()) { std::cout << " " << message; } std::cout << std::endl; } public: /** * A function that checks a boolean condition, prints a pass message if the condition is true, * otherwise prints a fail message with an optional custom message and function name. * @param condition the boolean condition to check * @param message an optional custom message to print in the fail message * @param func_name an optional function name to print in the fail message * @throws no exceptions thrown */ static void ASSERT(bool condition, const std::string& message = "", const std::string& func_name = "") { if (condition) { PRINT_PASS(func_name); } else { PRINT_FAIL(message, func_name); } } /** * Compares the expected and actual values and prints a pass or fail * message with an optional custom message along with the expected and actual values. * @tparam T the data type of the expected and actual values * @param expected the expected value * @param actual the actual value * @param message an optional message to print on failure
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel * @param actual the actual value * @param message an optional message to print on failure * @param func_name an optional function name to print in the pass or fail message * @return void */ static void ASSERT_EQUAL(const T& expected, const T& actual, const std::string& message = "", const std::string& func_name = "") { if (expected == actual) { PRINT_PASS(func_name); } else { PRINT_FAIL(message, func_name); std::cout << "\n[expected]: " << expected << " -> [actual]: " << actual << std::endl; } } /** * Compares the given actual and expected values and prints a pass message if they are not equal. * Otherwise, prints a fail message and the actual and not expected values. * @param notExpected the expected value * @param actual the actual value to be compared with the expected value * @param message an optional message to print if the comparison fails * @param func_name an optional name of the function for debugging purposes * @throws none */ static void ASSERT_NOT_EQUAL(const T& notExpected, const T& actual, const std::string& message = "", const std::string& func_name = "") { if (notExpected != actual) { PRINT_PASS(func_name); } else { PRINT_FAIL(message, func_name); std::cout << "\n[not expected]: " << notExpected << " -> [actual]: " << actual << std::endl; } } /** * A function that asserts whether a condition is true. If the condition is true, * prints a pass message; otherwise, prints a fail message. * @param condition a boolean representing the condition to be tested * @param message optional message to be printed in the event of a failure * @param func_name optional name of the function being tested * @throws none */ static void ASSERT_TRUE(bool condition, const std::string& message = "", const std::string& func_name = "") { if (condition) { PRINT_PASS(func_name); } else { PRINT_FAIL(message, func_name);
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel if (condition) { PRINT_PASS(func_name); } else { PRINT_FAIL(message, func_name); } } /** * Checks if a given condition is false and prints either a pass message or a fail * message with a given function name and message. * @param condition boolean expression to check * @param message optional message to print if the condition is true * @param func_name optional function name to print with the fail message * @throws none */ static void ASSERT_FALSE(bool condition, const std::string& message = "", const std::string& func_name = "") { if (!condition) { PRINT_PASS(func_name); } else { PRINT_FAIL(message, func_name); } } /** * Runs a statement and catches any exceptions of type ExceptionType. * If an exception of type ExceptionType is caught, the function will print a pass message. * If another type of exception is caught, the function will print a fail message * and the type of exception thrown. * If no exception is thrown, the function will print a fail message. * @param statement the statement to run * @param message an optional message to print if the statement fails * @param func_name an optional name of the function being tested * * @throws ExceptionType if the statement throws an exception of this type */ template <typename ExceptionType> static void ASSERT_THROW(const std::function<void()>& statement, const std::string& message = "", const std::string& func_name = "") { try { statement(); PRINT_FAIL(message, func_name); } catch (const ExceptionType&) { PRINT_PASS(func_name); } catch (...) { PRINT_FAIL(message, func_name); std::cout << "[expected exception type]: " << typeid(ExceptionType).name() << std::endl; } } /** * Method that takes in a std::function object, * a string message, and a string function name. It attempts to execute the provided statement,
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel * a string message, and a string function name. It attempts to execute the provided statement, * and if an exception of type ExceptionType is thrown, it prints a failed message and an * optional error message and function name. If any other type of exception is thrown, it * prints a failed message and an optional error message and function name. * @param statement The std::function object that is to be executed. * @param message Optional string error message to print alongside the failed message. * @param func_name Optional string function name to print alongside the failed message. * @throws ExceptionType If this type of exception is thrown by the statement. */ template <typename ExceptionType> static void ASSERT_NO_THROW(const std::function<void()>& statement, const std::string& message = "", const std::string& func_name = "") { try { statement(); PRINT_PASS(func_name); } catch (const ExceptionType&) { PRINT_FAIL(message, func_name); std::cout << "[unexpected exception type]: " << typeid(ExceptionType).name() << std::endl; } catch (...) { PRINT_FAIL(message, func_name); } } /** * Compares the given value with a given threshold and prints a pass * or fail message based on the comparison. * @param value the value to be compared * @param threshold the threshold value to compare against * @param message an optional message to be printed in case of a fail * @param func_name the name of the calling function * @throws None */ static void GREATER(const T& value, const T& threshold, const std::string& message = "", const std::string& func_name = "") { if (value > threshold) { PRINT_PASS(func_name); } else { PRINT_FAIL(message, func_name); std::cout << "[value]: " << value << " -> [threshold]: " << threshold << std::endl; } } /** * Compares the given value with the given threshold and prints a message based on the result.
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel * Compares the given value with the given threshold and prints a message based on the result. * @param value the value to compare with the threshold * @param threshold the threshold to compare the value with * @param message an optional message to print if the comparison fails * @param func_name an optional function name to print in the pass/fail message * @throws N/A */ static void SMALLER(const T& value, const T& threshold, const std::string& message = "", const std::string& func_name = "") { if (value < threshold) { PRINT_PASS(func_name); } else { PRINT_FAIL(message, func_name); std::cout << "[value]: " << value << " -> [threshold]: " << threshold << std::endl; } } };
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel #endif /* test_file_h */ test_file.cpp // // test_file.cpp // linked_list_xcode // // Created by Jakob Balkovec on 13/06/2023. // #include "single_l.cpp" #include "test_file.h" #include "test.h" #include <string> #include <iostream> // { // Follow the arrange, act, assert principle // } /** * Tests the default constructor of the 'single_l' template class using 'TEST' assertions. * @param None * @return Void * @throws None */ void test_constructor() { single::single_l<int> list1; TEST<bool>::ASSERT_TRUE(list1.empty(), "[list should be empty]","DEF_CONSTRUCTOR {1}"); TEST<bool>::ASSERT_EQUAL(0, list1.size(), "[list size should be 0]", "DEF_CONSTRUCTOR {2}"); } /** * This function tests the destructor of single_l<int> class. It creates a * single_l<int> object, adds two elements to it and then calls the clear() * method which in turn calls the destructor. It then uses the TEST macro to * check that the list is empty and its size is 0. * @param None * @return None * @throws None */ void test_destructor() { single::single_l<int> list1; list1.push_back(10); list1.push_back(20); list1.clear(); //destructor calls clear TEST<bool>::ASSERT_TRUE(list1.empty(), "[list should be empty]", "DESTRUCTOR {1}"); TEST<bool>::ASSERT_TRUE(list1.size() == 0, "[size should be 0]", "DESTRUCTOR {2}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Tests the copy constructor of the single_l class in the single namespace. * @param None * @return None * @throws None */ void test_copy_constructor() { single::single_l<int> list1; list1.push_back(10); list1.push_back(20); single::single_l<int> list2(list1); TEST<bool>::ASSERT_FALSE(list2.empty(), "[list should not be empty]", "CPY_CONSTRUCTOR {1}"); TEST<bool>::ASSERT_EQUAL(2, list2.size(), "[list size should be 2]", "CPY_CONSTRUCTOR {2}"); TEST<bool>::ASSERT_EQUAL(list1.front(), list2.front(), "[front elements should be equal]", "CPY_CONSTRUCTOR {3}"); TEST<bool>::ASSERT_EQUAL(list1.back(), list2.back(), "[back elements should be equal]", "CPY_CONSTRUCTOR {4}"); } /** * Tests the move constructor of a single linked list. * @param None * @return None * @throws None */ void test_move_constructor() { single::single_l<int> list1; list1.push_back(10); list1.push_back(20); single::single_l<int> list2(std::move(list1)); TEST<bool>::ASSERT_TRUE(list1.empty(), "[source list should be empty]", "MV_CONSTRUCTOR {1}"); TEST<bool>::ASSERT_FALSE(list2.empty(), "[destination list should not be empty]", "MV_CONSTRUCTOR {2}"); TEST<bool>::ASSERT_EQUAL(2, list2.size(), "[list size should be 2]", "MV_CONSTRUCTOR {3}"); TEST<bool>::ASSERT_EQUAL(10, list2.front(), "[front element should be 10]", "MV_CONSTRUCTOR {4}"); TEST<bool>::ASSERT_EQUAL(20, list2.back(), "[back element should be 20]", "MV_CONSTRUCTOR {5}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Tests the copy assignment operator of the single_l class. * @param None * @return None * @throws None */ void test_copy_assignment_operator() { single::single_l<int> list1; list1.push_back(10); list1.push_back(20); single::single_l<int> list2; list2.push_back(30); list2 = list1; TEST<bool>::ASSERT_FALSE(list2.empty(), "[list should not be empty]", "CPY_ASSGN_OP {1}"); TEST<bool>::ASSERT_EQUAL(2, list2.size(), "[list size should be 2]", "CPY_ASSGN_OP {2}"); TEST<bool>::ASSERT_EQUAL(list1.front(), list2.front(), "[front elements should be equal]", "CPY_ASSGN_OP {3}"); TEST<bool>::ASSERT_EQUAL(list1.back(), list2.back(), "[back elements should be equal]", "CPY_ASSGN_OP {4}"); } /** * Test the move assignment operator of a single linked list. * @param None * @return None * @throws None */ void test_move_assignment_operator() { single::single_l<int> list1; list1.push_back(10); list1.push_back(20); single::single_l<int> list2; list2.push_back(30); list2 = std::move(list1); TEST<bool>::ASSERT_TRUE(list1.empty(), "[source list should be empty]", "MV_ASSGN_OP {1}"); TEST<bool>::ASSERT_FALSE(list2.empty(), "[destination list should not be empty]", "MV_ASSGN_OP {2}"); TEST<bool>::ASSERT_EQUAL(2, list2.size(), "[list size should be 2]", "MV_ASSGN_OP {3}"); TEST<bool>::ASSERT_EQUAL(10, list2.front(), "[front element should be 10]", "MV_ASSGN_OP {4}"); TEST<bool>::ASSERT_EQUAL(20, list2.back(), "[back element should be 20]", "MV_ASSGN_OP {5}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Tests the push_back() function of a single linked list implementation * @param None * @return None * @throws None */ void test_push_back() { single::single_l<int> list1; int values[] = {10, 20, 30, 40, 50}; for (int i = 0; i < sizeof(values) / sizeof(values[0]); i++) { list1.push_back(values[i]); } TEST<bool>::ASSERT_FALSE(list1.empty(), "[list not should be empty]", "PUSH_BACK {1}"); TEST<bool>::ASSERT_TRUE(list1[0] == 10, "[first element should be 10]", "PUSH_BACK {2}"); TEST<bool>::ASSERT_TRUE(list1[1] == 20, "[second element should be 20]", "PUSH_BACK {3}"); TEST<bool>::ASSERT_TRUE(list1[2] == 30, "[third element should be 30]", "PUSH_BACK {4}"); TEST<bool>::ASSERT_TRUE(list1[3] == 40, "[fourth element should be 40]", "PUSH_BACK {5}"); TEST<bool>::ASSERT_TRUE(list1[4] == 50, "[fifth element should be 50]", "PUSH_BACK {6}"); TEST<bool>::ASSERT_TRUE(list1.size() == 5, "[size should be 5]", "PUSH_BACK {7}"); } /** * Tests the push_front method of the single_l list implementation. * @param None * @return None * @throws None */ void test_push_front() { single::single_l<int> list1; int values[] = {10, 20, 30, 40, 50}; for (int i = 0; i < sizeof(values) / sizeof(values[0]); i++) { list1.push_front(values[i]); } TEST<bool>::ASSERT_FALSE(list1.empty(), "[list not should be empty]", "PUSH_FRONT {1}"); TEST<bool>::ASSERT_TRUE(list1[0] == 50, "[first element should be 50]", "PUSH_FRONT {2}"); TEST<bool>::ASSERT_TRUE(list1[1] == 40, "[second element should be 40]", "PUSH_FRONT {3}"); TEST<bool>::ASSERT_TRUE(list1[2] == 30, "[third element should be 30]", "PUSH_FRONT {4}"); TEST<bool>::ASSERT_TRUE(list1[3] == 20, "[fourth element should be 20]", "PUSH_FRONT {5}"); TEST<bool>::ASSERT_TRUE(list1[4] == 10, "[fifth element should be 10]", "PUSH_FRONT {6}"); TEST<bool>::ASSERT_TRUE(list1.size() == 5, "[size should be 5]", "PUSH_FRONT {7}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Tests the pop_back method of a single linked list implementation by removing * elements from the end of the list and asserting the expected values and sizes. * @param none * @return void * @throws none */ void test_pop_back() { single::single_l<int> list1; int values[] = {10, 20, 30, 40, 50}; for (int i = 0; i < sizeof(values) / sizeof(values[0]); i++) { list1.push_back(values[i]); } list1.pop_back(); TEST<bool>::ASSERT_EQUAL(40, list1[3], "[fourth element should be 40]", "POP_BACK {1}"); TEST<bool>::ASSERT_FALSE(list1.size() == 5, "[size shoudl be 4]", "POP_BACK {2}"); list1.pop_back(); TEST<bool>::ASSERT_EQUAL(30, list1[2], "[fourth element should be 40]", "POP_BACK {1}"); TEST<bool>::ASSERT_FALSE(list1.size() == 4, "[size shoudl be 4]", "POP_BACK {2}"); list1.pop_back(); list1.pop_back(); list1.pop_back(); TEST<bool>::ASSERT_TRUE(list1.empty(), "[list should be empty]", "POP_BACK {5}"); TEST<bool>::ASSERT_TRUE(list1.size() == 0, "[size should be 0]", "POP_BACK {6}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Tests the pop_front() method of the single_l class by creating a list of * integers and removing the first element multiple times while checking * the state of the list after each removal. * @param None * @return None * @throws None */ void test_pop_front() { single::single_l<int> list1; int values[] = {10, 20, 30, 40, 50}; for (int i = 0; i < sizeof(values) / sizeof(values[0]); i++) { list1.push_back(values[i]); } list1.pop_front(); TEST<bool>::ASSERT_FALSE(list1[0] == 10, "[first element should not be 10]", "POP_FRONT {1}"); TEST<bool>::ASSERT_TRUE(list1[0] == 20, "[first element should be 20]", "POP_FRONT {2}"); list1.pop_front(); TEST<bool>::ASSERT_FALSE(list1[0] == 20, "[first element should not be 40]", "POP_FRONT {3}"); TEST<bool>::ASSERT_TRUE(list1[0] == 30, "[first element should be 30]", "POP_FRONT {4}"); list1.pop_front(); list1.pop_front(); list1.pop_front(); TEST<bool>::ASSERT_TRUE(list1.empty(), "[list should be empty]", "POP_FRONT {5}"); TEST<bool>::ASSERT_TRUE(list1.size() == 0, "[size should be 0]", "POP_FRONT {6}"); } /** * Tests the clear() method, the method clears the content of a single linked list and checks if the size is 0 and * the list is empty. * @param None * @return None * @throws None */ void test_clear() { single::single_l<int> list1; int values[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; for (int i = 0; i < sizeof(values) / sizeof(values[0]); i++) { list1.push_back(values[i]); } list1.clear(); TEST<bool>::ASSERT_EQUAL(0, list1.size(), "[size should be 0]", "CLEAR {1}"); TEST<bool>::ASSERT_EQUAL(true, list1.empty(), "[list should be empty]", "CLEAR {2}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Executes a test swapping two linked lists of integers. * @param None * @return None * @throws None */ void test_swap() { single::single_l<int> list1; int values1[] = {10, 20, 30, 40, 50}; for (int i = 0; i < sizeof(values1) / sizeof(values1[0]); i++) { list1.push_back(values1[i]); } TEST<bool>::ASSERT_EQUAL(10, list1[0], "[list1 first element should be 10]", "SWAP {1}"); TEST<bool>::ASSERT_EQUAL(20, list1[1], "[lsit1 second element should be 20]", "SWAP {1}"); single::single_l<int> list2; int values2[] = {60, 70, 80, 90, 100}; for (int i = 0; i < sizeof(values2) / sizeof(values2[0]); i++) { list2.push_back(values2[i]); } TEST<bool>::ASSERT_EQUAL(60, list2[0], "[list2 first element should be 60]", "SWAP {3}"); TEST<bool>::ASSERT_EQUAL(70, list2[1], "[list2 second element should be 70]", "SWAP {4}"); //swaps two lists list1.swap(list2); TEST<bool>::ASSERT_EQUAL(60, list1[0], "[list1 first element should be 60]", "SWAP {5}"); TEST<bool>::ASSERT_EQUAL(70, list1[1], "[list1 second element should be 70]", "SWAP {6}"); TEST<bool>::ASSERT_EQUAL(10, list2[0], "[list2 first element should be 10]", "SWAP {7}"); TEST<bool>::ASSERT_EQUAL(20, list2[1], "[list2 second element should be 20]", "SWAP {8}"); TEST<bool>::ASSERT(list1.size() == list2.size(), "[list1 and list2 size should be equal]", "SWAP {9}"); } /** * Tests if the given single linked list is empty. * @param None * @return void * @throws None */ void test_empty() { single::single_l<int> list1; int values1[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; for (int i = 0; i < sizeof(values1) / sizeof(values1[0]); i++) { list1.push_back(values1[i]); } TEST<bool>::ASSERT_FALSE(list1.empty(), "[list should not be empty]", "EMPTY {1}"); list1.clear(); TEST<bool>::ASSERT_TRUE(list1.empty(), "[list should be empty]", "EMPTY {2}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel void test_size() { single::single_l<int> list1; int values1[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; for (int i = 0; i < sizeof(values1) / sizeof(values1[0]); i++) { list1.push_back(values1[i]); } TEST<bool>::ASSERT_EQUAL(static_cast<size_t>(10), static_cast<int>(const_cast<single::single_l<int>&>(list1).size()), "[size should be 10]", "SIZE {1}"); list1.pop_back(); TEST<bool>::ASSERT_EQUAL(static_cast<size_t>(9), static_cast<int>(const_cast<single::single_l<int>&>(list1).size()), "[size should be 9]", "SIZE {2}"); } /** * Tests whether the front element of a single linked list is correct after * several push and pop operations. * @return void * @throws None */ void test_front() { single::single_l<int> list1; int values1[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; for (int i = 0; i < sizeof(values1) / sizeof(values1[0]); i++) { list1.push_back(values1[i]); } TEST<bool>::ASSERT_EQUAL(10, list1.front(), "[front should be 10]", "FRONT {1}"); list1.pop_back(); TEST<bool>::ASSERT_EQUAL(10, list1.front(), "[front should be 10]", "FRONT {2}"); list1.pop_front(); TEST<bool>::ASSERT_EQUAL(20, list1.front(), "[front should be 20]", "FRONT {3}"); for(auto i = 0; i < 7; i++) { list1.pop_front(); } TEST<bool>::ASSERT_EQUAL(90, list1.front(), "[front should be 90]", "FRONT {4}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Tests the back() method of the single_l<int> class. * @param None * @return None * @throws None */ void test_back() { single::single_l<int> list1; int values1[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; for (int i = 0; i < sizeof(values1) / sizeof(values1[0]); i++) { list1.push_back(values1[i]); } TEST<bool>::ASSERT_EQUAL(100, list1.back(), "[back should be 100]", "BACK {1}"); list1.pop_front(); TEST<bool>::ASSERT_EQUAL(100, list1.back(), "[back should be 100]", "BACK {2}"); list1.pop_back(); TEST<bool>::ASSERT_EQUAL(90, list1.back(), "[back should be 90]", "BACK {3}"); for(auto i = 0; i < 7; i++) { list1.pop_back(); } TEST<bool>::ASSERT_EQUAL(20, list1.back(), "[back should be 20]", "BACK {4}"); } /** * Tests the front() function of the single_l class with const objects. * @param None * @return None * @throws None */ void test_front_const() { const single::single_l<int> list1{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; TEST<bool>::ASSERT_EQUAL(10, list1.front(), "[front should be 10]", "FRONT CONST {1}"); const single::single_l<int> list2{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TEST<bool>::ASSERT_EQUAL(1, list2.front(), "[front should be 1]", "FRONT CONST {2}"); } /** * Tests the back() method of the single::single_l class when the list is const. * @param None * @return None * @throws None */ void test_back_const() { const single::single_l<int> list1{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; TEST<bool>::ASSERT_EQUAL(100, list1.back(), "[front should be 100]", "BACK CONST {1}"); const single::single_l<int> list2{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TEST<bool>::ASSERT_EQUAL(10, list2.back(), "[front should be 10]", "BACK CONST {2}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Test the subscript operator of a single linked list. * @param None * @return None * @throws None */ void test_sub_operator() { single::single_l<int> list1{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; TEST<bool>::ASSERT_EQUAL(100, list1[list1.size()-1], "[should return 100]", "SUB_OP {1}"); single::single_l<int> list2{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; TEST<bool>::ASSERT_EQUAL(4, list2[3], "[should return 4]", "SUP_OP {2}"); } /** * Tests the at() function of a single_l<int> list. It asserts that the * values returned by at() match the expected values at all positions. * @param None * @return None * @throws None */ void test_at() { single::single_l<int> list1{1, 2, 3, 4, 5}; TEST<bool>::ASSERT_EQUAL(1, list1.at(0), "[first element should be 1]", "AT {1}"); TEST<bool>::ASSERT_EQUAL(2, list1.at(1), "[first element should be 2]", "AT {2}"); TEST<bool>::ASSERT_EQUAL(3, list1.at(2), "[first element should be 3]", "AT {3}"); TEST<bool>::ASSERT_EQUAL(4, list1.at(3), "[first element should be 4]", "AT {4}"); TEST<bool>::ASSERT_EQUAL(5, list1.at(4), "[first element should be 5]", "AT {5}"); } /** * Tests the delete_at() method of a single_l list. * @param None * @return None * @throws None */ void test_delete_at() { single::single_l<int> list1{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; list1.delete_at(4); TEST<bool>::ASSERT_FALSE(list1.at(4) == 50, "[element should not be 50]", "DELETE_AT {1}"); TEST<bool>::ASSERT_TRUE(list1.size() == 9, "[size should be 9]", "DELETE_AT {2}"); list1.delete_at(3); TEST<bool>::ASSERT_FALSE(list1.at(3) == 40, "[element should not be 40]", "DELETE_AT {3}"); TEST<bool>::ASSERT_TRUE(list1.size() == 8, "[size should be 8]", "DELETE_AT {4}"); TEST<bool>::ASSERT_TRUE(list1.at(3) == 60, "[list1 at i = 3 should be 60]", "DELETE_AT {4}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Tests the delete_value method of the single_l class. * @param None * @return None * @throws None */ void test_delete_value() { single::single_l<int> list1{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; list1.delete_value(10); TEST<bool>::ASSERT_EQUAL(-1, list1.search(100), "[100 should not be in the list]", "DELETE_VAL {1}"); list1.delete_value(90); TEST<bool>::ASSERT_EQUAL(-1, list1.search(90), "[90 should not be in the list]", "DELETE_VAL {2}"); list1.delete_value(80); TEST<bool>::ASSERT_EQUAL(-1, list1.search(80), "[80 should not be in the list]", "DELETE_VAL {3}"); TEST<bool>::ASSERT(list1.size() == 7, "[size should be 7]", "DELETE_VAL {4}"); } /** * Tests the search method of the single_l class. * @return void * @throws None */ void test_search() { single::single_l<int> list1{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; TEST<bool>::ASSERT_EQUAL(0, list1.search(10), "[10 should be at i = 0]", "SEARCH {1}"); TEST<bool>::ASSERT_EQUAL(5, list1.search(60), "[60 should be at i = 5]", "SEARCH {2}"); TEST<bool>::ASSERT_EQUAL(-1, list1.search(120), "[120 should not be int the list]", "SEARCH {3}"); TEST<bool>::ASSERT_EQUAL(-1, list1.search(8), "[8 should not be int the list]", "SEARCH {4}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Tests the at_position() function of the single_l class. * @param None * @return None * @throws None */ void test_at_position() { single::single_l<int> list1{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; TEST<bool>::ASSERT_EQUAL(1, list1.search(20), "[20 should be at i = 1]", "AT_POSITION {1}"); TEST<bool>::ASSERT_EQUAL(2, list1.search(30), "[30 should be at i = 2]", "AT_POSITION {2}"); list1.at_position(12, 2); TEST<bool>::ASSERT_EQUAL(2, list1.search(12), "[12 should be at i = 2]", "AT_POSITION {3}"); TEST<bool>::ASSERT_EQUAL(1, list1.search(20), "[20 should be at i = 1]", "AT_POSITION {4}"); TEST<bool>::ASSERT_EQUAL(3, list1.search(30), "[30 should be at i = 3]", "AT_POSITION {5}"); TEST<bool>::ASSERT(list1.size() == 11, "[size should be 11]", "AT_POSITION {6}"); } /** * Tests the reverse function of single_l class. * @param None * @return None * @throws None */ void test_reverse() { single::single_l<int> list1{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; TEST<bool>::ASSERT_EQUAL(10, list1[0], "[first element should be 10]", "REVERSE {1}"); TEST<bool>::ASSERT_EQUAL(100, list1[list1.size()-1], "[last element should be 100]", "REVERSE {2}"); list1.reverse(); TEST<bool>::ASSERT_EQUAL(100, list1[0], "[first element should be 100]", "REVERSE {3}"); TEST<bool>::ASSERT_EQUAL(10, list1[list1.size()-1], "[last element should be 10]", "REVERSE {4}"); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Tests if the single linked list is properly sorted. * @param None * @return None * @throws None */ void test_sort() { single::single_l<int> list1{95, 7, 86, 44, 43, 63, 46, 45, 13, 2, 19, 4, 84, 100, 5, 63, 53, 56, 85, 95, 48, 88, 9, 6, 65}; list1.sort(); TEST<int>::GREATER(list1[1], list1[0], "[list should be dsorted]", "SORT {1}"); TEST<int>::GREATER(list1[2], list1[1], "[list should be dsorted]", "SORT {2}"); TEST<int>::GREATER(list1[3], list1[2], "[list should be dsorted]", "SORT {3}"); TEST<int>::GREATER(list1[4], list1[3], "[list should be dsorted]", "SORT {4}"); TEST<int>::SMALLER(list1[5], list1[6], "[list should be sorted]", "SORT {5}"); TEST<int>::SMALLER(list1[1], list1[10], "[list should be sorted]", "SORT {6}"); TEST<int>::SMALLER(list1[18], list1[22], "[list should be sorted]", "SORT {7}"); TEST<int>::SMALLER(list1[23], list1[24], "[list should be sorted]", "SORT {8}"); } /** * Tests the functionality of removing duplicates from a single linked list. * @param None * @return None * @throws None */ void test_remove_duplicates() { single::single_l<int> list1{1, 1, 1, 1, 1, 1, 1, 3}; list1.remove_duplicates(); TEST<bool>::ASSERT(list1.size() == 2, "[size should be 2]", "REM_DUP {1}"); TEST<bool>::ASSERT(list1[0] == 1, "[first element should be 1]", "REM_DUP {1}"); } /** * Tests resizing of single_l list. * @param None * @return None * @throws None */ void test_resize() { single::single_l<int> list1; TEST<bool>::ASSERT(list1.size() == 0, "[size should be 0]", "RESIZE {1}" ); list1.resize(5); TEST<bool>::ASSERT(list1.size() == 5, "[size should be 5]", "RESIZE {2}" ); list1.resize(10); TEST<bool>::ASSERT(list1.size() == 10, "[size should be 10]", "RESIZE {3}" ); }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Solves the problem from my textbook described in main.cpp * @param list1 first list to be merged * @param list2 second list to be merged * @return a new single linked list that contains all elements from the input * lists in non-decreasing order * @throws None */ template <typename T> single::single_l<T> merge_lists(const single::single_l<T>& list1, const single::single_l<T>& list2) { single::single_l<T> merged_list; single::single_l<T> temp_list1 = list1; single::single_l<T> temp_list2 = list2; while (!temp_list1.empty() && !temp_list2.empty()) { if (temp_list1.front() <= temp_list2.front()) { merged_list.push_back(temp_list1.front()); temp_list1.pop_front(); } else { merged_list.push_back(temp_list2.front()); temp_list2.pop_front(); } } while (!temp_list1.empty()) { merged_list.push_back(temp_list1.front()); temp_list1.pop_front(); } while (!temp_list2.empty()) { merged_list.push_back(temp_list2.front()); temp_list2.pop_front(); } return merged_list; } /** * Runs an example function. * @param None * @return None * @throws None */ void run_example() { single::single_l<int> list1{1, 2, 3, 4, 5, 6}; single::single_l<int> list2{7, 8, 9, 10, 11}; std::cout << "\n[first list]: "; list1.print(); std::cout << "\n[second list]: "; list2.print(); single::single_l<int> merged_list = merge_lists(list1, list2); std::cout << "\n[merged list]: "; merged_list.print(); std::cout << "\n"; }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel /** * Runs a series of tests for the LinkedList class to ensure proper functionality. * @return true if all tests pass, false otherwise * @throws std::exception if any test fails */ bool run_tests() { try { test_constructor(); std::cout << std::endl; test_destructor(); std::cout << std::endl; test_move_constructor(); std::cout << std::endl; test_move_assignment_operator(); std::cout << std::endl; test_copy_constructor(); std::cout << std::endl; test_copy_assignment_operator(); std::cout << std::endl; test_push_back(); std::cout << std::endl; test_push_front(); std::cout << std::endl; test_pop_back(); std::cout << std::endl; test_pop_front(); std::cout << std::endl; test_clear(); std::cout << std::endl; test_swap(); std::cout << std::endl; test_empty(); std::cout << std::endl; test_size(); std::cout << std::endl; test_front(); std::cout << std::endl; test_back(); std::cout << std::endl; test_front_const(); std::cout << std::endl; test_back_const(); std::cout << std::endl; test_sub_operator(); std::cout << std::endl; test_at(); std::cout << std::endl; test_delete_at(); std::cout << std::endl; test_delete_value(); std::cout << std::endl; test_search(); std::cout << std::endl; test_at_position(); std::cout << std::endl; test_reverse(); std::cout << std::endl; test_sort(); std::cout << std::endl; test_remove_duplicates(); std::cout << std::endl; test_resize(); std::cout << std::endl; }catch (std::exception &e) { std::cerr << "{error}: " << e.what() << std::endl; return false; } return true; } test.h // // test.h // linked_list_xcode // // Created by Jakob Balkovec on 14/06/2023. // // { // This file defines a series of test functions implemented in @file test_file.h // } #ifndef test_h #define test_h
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel #ifndef test_h #define test_h #include "single_l.h" void test_constructor(); void test_destructor(); void test_move_constructor(); void test_move_assignment_operator(); void test_copy_constructor(); void test_copy_assignment_operator(); void test_push_back(); void test_push_front(); void test_pop_back(); void test_pop_front(); void test_clear(); void test_swap(); void test_empty(); void test_size(); void test_front(); void test_back(); void test_front_const(); void test_back_const(); void test_sub_operator(); void test_at(); void test_delete_at(); void test_delete_value(); void test_search(); void test_at_position(); void test_reverse(); void test_sort(); void test_remove_duplicates(); void test_resize(); template <typename T> single::single_l<T> merge_lists(); void run_example(); bool run_tests(); #endif /* test_h */ MakeFile CC = g++ CFLAGS = -std=c++17 -Wall all: prog prog: single_l.o main.o test_file.o $(CC) $(CFLAGS) $^ -o $@ single_l.o: single_l.cpp single_l.h $(CC) $(CFLAGS) -c $< main.o: main.cpp single_l.h test_file.h test.h $(CC) $(CFLAGS) -c $< test_file.o: test_file.cpp test_file.h single_l.h test.h $(CC) $(CFLAGS) -c $< clean: rm -f *.o prog
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel clean: rm -f *.o prog Answer: General Observations I am recommending that you take some time to follow the suggestion here and then post a follow up question. What should be handled immediately is the re-partitioning of the classes and files. You should also consider a rewrite of the TEST class. In the main() function rather than force the user to make a choice at compile time, allow them to choose between TEST and EXAMPLE at run time. This would also allow you to create a menu to run each test individually if that is necessary. C++ is generally a portable language, but __VERSION__ in main.cppis not portable, __cplusplus is portable. static inline void show_last_compiled() { std::cout << "\n[file]: " << __FILE__ << '\n' << "[compiled on]: " << __DATE__ << " at " << __TIME__ << '\n' << "[compiler]: " << __cplusplus << '\n' << "[timestamp]: " << __TIMESTAMP__ << '\n'; }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel It isn't clear why you are using the inline specification for the above function. If it is for optimization purposes then the -O3 switch can determine if the function should be inlined better than a programmer can. It might be better if the merge_list() function was a member of the list class. Rather than using XCODE it would be better to use gcc, since it is more portable and will compile on all systems the same way. If you are just starting out with automating builds, prefer CMake over Makefiles, it will automate more of the process for you making the automation less work. The file and class partitioning needs more design work. File Partitioning and Naming All of the Test member functions in test_file.h should be defined in a .cpp file. The function prototypes declared in test.h should be declared in test_file.h since the body of the functions are in test_file.cpp. Missing Include Directive The file test_file.h is missing the #include <functional> statement. On my computer using my compiler (not Apple or XCODE) this file does not compile. Adding the missing include directive allows the file to compile. Use of std::endl versus use of "\n" The code is inconsistent, sometimes it ends the output with "\n" such as this line in main.cpp std::cout << "\n\n[all tests passed]\n\n"; and sometimes it ends an output line with std::endl such as this function in test_file.h static void ASSERT_EQUAL(const T& expected, const T& actual, const std::string& message = "", const std::string& func_name = "") { if (expected == actual) { PRINT_PASS(func_name); } else { PRINT_FAIL(message, func_name); std::cout << "\n[expected]: " << expected << " -> [actual]: " << actual << std::endl; } }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel Throughout your code you should always be consistent, choose one or the other. A second consideration to make is that std::endl will slow down your program each time you call it, because std:endl calls std::flush to flush the output buffer. The fail path of the function ASSERT_EQUAL calls std::flush twice because the function PRINT_FAIL() also contains an std::endl. This is unnecessary. If you need to flush the outout buffer after each test call std::flush at the end of each test, but that probably isn't necessary. Naming Conventions In the C programming language as well as the C++ programming language ALL CAPITALS is generally reserved for symbolic constants that are defined using #define or const (and constexpr). Class names generally start with a capital, function and variables start with lower case letters. Short Example // // test_file.h // linked_list_xcode // // Created by Jakob Balkovec on 13/06/2023. // #ifndef test_file_h #define test_file_h #include <functional> #include <iostream> #include <string> template <class T> class Test { private: /** * Prints a test passing message with an optional function name. * @param func_name an optional name of the function being tested * @return void */ static void print_pass(const std::string& func_name = "") noexcept { std::cout << "[TEST " << func_name << " PASSED]" << std::endl; } /** * Prints a failure message for a test, including an optional message and function name. * @param message the message to include in the failure message (optional) * @param func_name the name of the function being tested (optional) * @return void */ static void print_fail(const std::string& message, const std::string& func_name = "") noexcept { std::cout << "[TEST " << func_name << " FAILED]"; if (!message.empty()) { std::cout << " " << message; } std::cout << std::endl; } ... } // End class Test
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel ... } // End class Test Static Member Methods It isn't clear why the all of the methods in the TEST class are static methods, to be honest it isn't clear why any of the member functions of the TEST class are declared as static member functions. This might have been the cause of your linking errors. Static class members have a very special usage. No Throw Many of the functions comments contain @throws None. There is actually a C++ way to indicate this in the function declaration so that it doesn't need to be in the comments. You need the noexcept keyword in the function declarations. /** * Tests resizing of single_l list. * @param None * @return None * @throws None */ void test_resize() noexcept { single::single_l<int> list1; Test<bool>::assert(list1.size() == 0, "[size should be 0]", "RESIZE {1}"); list1.resize(5); Test<bool>::assert(list1.size() == 5, "[size should be 5]", "RESIZE {2}"); list1.resize(10); Test<bool>::assert(list1.size() == 10, "[size should be 10]", "RESIZE {3}"); } /** * Solves the problem from my textbook described in main.cpp * @param list1 first list to be merged * @param list2 second list to be merged * @return a new single linked list that contains all elements from the input * lists in non-decreasing order * @throws None */ template <typename T> single::single_l<T> merge_lists(const single::single_l<T>& list1, const single::single_l<T>& list2) noexcept { single::single_l<T> merged_list; single::single_l<T> temp_list1 = list1; single::single_l<T> temp_list2 = list2; while (!temp_list1.empty() && !temp_list2.empty()) { if (temp_list1.front() <= temp_list2.front()) { merged_list.push_back(temp_list1.front()); temp_list1.pop_front(); } else { merged_list.push_back(temp_list2.front()); temp_list2.pop_front(); } }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
c++, linked-list, unit-testing, reinventing-the-wheel while (!temp_list1.empty()) { merged_list.push_back(temp_list1.front()); temp_list1.pop_front(); } while (!temp_list2.empty()) { merged_list.push_back(temp_list2.front()); temp_list2.pop_front(); } return merged_list; }
{ "domain": "codereview.stackexchange", "id": 44820, "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, unit-testing, reinventing-the-wheel", "url": null }
python, simulation, physics Title: Molecular simulation: Minimum Image Convention Question: Can you review the following code to check to see if the Minimum Image Convention is properly implemented? import random import math import matplotlib.pyplot as plt polymer_chain_vec = [] N = 9 sigma = 2 epsilon = 2 periodic_boundary_int = 5 # size of the periodic box in A temperature_float = 2 # temperature of the simulation min_atom_distance_float = 1 max_atom_distance_float = 3.8 k = 1 sim_steps_int = 10000 write_steps_int = 10 def polymer_to_str(): return ' '.join([f'({round(point_pt[0], 2)},{round(point_pt[1], 2)})' for point_pt in polymer_chain_vec]) def plot_energies(energies): plt.plot(range(len(energies)), energies) plt.ylabel('E') plt.xlabel('step') plt.show() def apply_boundary_condition(point_pt): x, y = point_pt x = x % periodic_boundary_int y = y % periodic_boundary_int return [x, y] def get_distance(point_one_pt, point_two_pt): dx = point_one_pt[0] - point_two_pt[0] dy = point_one_pt[1] - point_two_pt[1] dx -= periodic_boundary_int * round(dx / periodic_boundary_int) dy -= periodic_boundary_int * round(dy / periodic_boundary_int) return math.sqrt(dx**2 + dy**2) def get_point_at_radius(current_point_pt, radius_double): angle = random.random() * math.pi * 2 x = (math.cos(angle) * radius_double) + current_point_pt[0] y = (math.sin(angle) * radius_double) + current_point_pt[1] return apply_boundary_condition([x, y]) def morse_potential_func(r_float): return math.exp(-2 * sigma * (r_float - min_atom_distance_float)) \ - 2 * math.exp(-sigma * (r_float - min_atom_distance_float)) def lj_energy_func(r_float): return 4 * epsilon * ((sigma ** 12 / r_float ** 12) - (sigma ** 6 / r_float ** 6)) def harmonic_energy_func(r_float): return k * ((r_float - max_atom_distance_float) ** 2)
{ "domain": "codereview.stackexchange", "id": 44821, "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, simulation, physics", "url": null }
python, simulation, physics def harmonic_energy_func(r_float): return k * ((r_float - max_atom_distance_float) ** 2) def square_well_func(r_float): d = r_float en = 0 if d < min_atom_distance_float: en += 10000000 elif d < max_atom_distance_float: en += -1 return en def get_potential(index_int): bead_potential_float = 0 harmonic_potential_float = 0 current_loc_pt = polymer_chain_vec[index_int] for i, other_loc_pt in enumerate(polymer_chain_vec): if i != index_int: r_float = get_distance(current_loc_pt, other_loc_pt) bead_potential_float += morse_potential_func(r_float) if index_int >= 1: # 1....8 r_float = get_distance(current_loc_pt, polymer_chain_vec[index_int - 1]) harmonic_potential_float += harmonic_energy_func(r_float) if index_int < len(polymer_chain_vec) - 1: # 0....7 r_float = get_distance(current_loc_pt, polymer_chain_vec[index_int + 1]) harmonic_potential_float += harmonic_energy_func(r_float) return bead_potential_float + harmonic_potential_float def get_total_potential(): harmonic_float = 0 pair_float = 0 for i in range(len(polymer_chain_vec) - 1): bead_i = polymer_chain_vec[i] bead_i_plus_1 = polymer_chain_vec[i + 1] r_float = get_distance(bead_i, bead_i_plus_1) harmonic_float += harmonic_energy_func(r_float) for j in range(i + 1, len(polymer_chain_vec), 1): bead_j = polymer_chain_vec[j] r_float = get_distance(bead_i, bead_j) pair_float += morse_potential_func(r_float) return harmonic_float + pair_float def initialize_polymer(): current_point_pt = [0, 0] polymer_chain_vec.append(current_point_pt) for _ in range(N - 1): new_loc_pt = get_point_at_radius(current_point_pt, max_atom_distance_float) polymer_chain_vec.append(new_loc_pt) current_point_pt = new_loc_pt
{ "domain": "codereview.stackexchange", "id": 44821, "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, simulation, physics", "url": null }
python, simulation, physics def run_simulation(steps_int): for _ in range(steps_int): rand_index_int = random.randint(0, len(polymer_chain_vec) - 1) before_loc_pt = polymer_chain_vec[rand_index_int] before_pot_float = get_potential(rand_index_int) new_loc_pt = get_point_at_radius(before_loc_pt, max_atom_distance_float) polymer_chain_vec[rand_index_int] = new_loc_pt after_pot_float = get_potential(rand_index_int) pot_diff_float = after_pot_float - before_pot_float if pot_diff_float < 0: pass else: rand_float = random.random() if math.exp(-pot_diff_float / temperature_float) > rand_float: pass else: polymer_chain_vec[rand_index_int] = before_loc_pt if __name__ == '__main__': initialize_polymer() total_pot_vec = [] for ii in range(1, sim_steps_int, 1): run_simulation(write_steps_int) total_pot_double = round(get_total_potential()) total_pot_vec.append(total_pot_double) plt.plot(range(len(total_pot_vec)), total_pot_vec) plt.show() Answer: periodic_boundary_int = 5 # size of the periodic box in A temperature_float = 2 # temperature of the simulation Thank you for the first comment, that's lovely, very helpful. (Might as well spell it "Å".) I read the second comment, and frankly I am not yet enlightened. Maybe it's °R? Maybe it's slightly above freezing point of water? I would like to assume it's kelvins, but I really want you to tell me that explicitly. The _vec / _int / _float suffix is distracting, especially those last two. Best to elide it. We have perfectly nice ways of annotating as an aid to the Reader and mypy: periodic_boundary: int = 5 temperature: float = 2
{ "domain": "codereview.stackexchange", "id": 44821, "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, simulation, physics", "url": null }
python, simulation, physics Definitely avoid the redundancy of e.g. point_pt. As far as the atom distances go, I'm perfectly confident they are in ångströms, but it wouldn't hurt to group the three distances together. It's just a tiny nit. Consider expressing the number of simulation steps as 10_000, for slightly improved readability. That k global really frightens me. It's a short identifier, easy to confuse as a typo in e.g. i, j, k loops. I encourage you to rename it to something longer, perhaps harmonic_k. Or make it an optional keyword arg in lj_energy_func's signature. Similar remarks for epsilon, sigma. And N is certainly a bit worrying. The polymer chain is a mutable global list. That might motivate introducing a class which stores the chain as an object attribute. def polymer_to_str(): I can't say I'm very fond of that signature. Rather than implicit coupling to a global, please explicitly spell out the relationship: def polymer_to_str(polymer_chain: list) -> str: You offered a Minimum Image link which framed it for me as being a problem about 3-space physics. But then the code seems to be about a 2-space simplification which the author introduced for didactic purposes. It's worth at least a one-line comment to explain the constraints we choose to put on this particular implementation, to help folks understand what is currently in- or out-of-scope. There's a bunch of obvious copy-n-paste boiler plate to treat the y dimension similar to the x dimension. There will be more of it if we expand upwards into z. Consider adopting numpy vectors, so software engineers can write about and think about quantities using familiar notation from mathematics and the sciences. Or at least write a one-line comment explaining the reason we chose to reject numpy's ndarrays.
{ "domain": "codereview.stackexchange", "id": 44821, "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, simulation, physics", "url": null }
python, simulation, physics The plot_energies() function is nice enough. Based on the Y label I assume the units are joules; it wouldn't hurt to make that explicit. Nothing calls this, so we might consider deleting it. The plt.show() is fine, but you might find yourself deleting it later, or choosing to save to an output file. Often a paper will have small multiples of similar charts. Creating a chart and displaying a chart are separate concerns. apply_boundary_condition() ends with return [x, y] No. Please don't do that. Pythonic code would prefer to model "point" with a tuple rather than a list. We use tuples for items with a fixed number of elements, where the index conveys the meaning. Here [0] says "x coordinate" and [1] says "y". Think of a tuple as sort of an immutable C struct. Use a dataclass instead if you need mutability. We use lists for an arbitrary number of the "same" thing, for example: names: list[str] = ["Alice", "Bob"] points: list[tuple] = [(0, 0), (1, 1), (5, 5)] Similarly in places like the last line of get_point_at_radius. Kudos on starting that function with a nice tuple unpack, BTW. Rather than get_distance(), maybe we want to call it get_lattice_distance()? Or maybe the cited reference offers some domain term for that concept? It is, on purpose, clearly different from simple Euclidean distance. A """docstring""" could spell that out. In the get_point_at_radius() signature, radius_double is an especially unfortunate identifier, as on first reading I interpreted it as diameter. Perhaps we should name it get_random_point_at_radius()? Or get_random_nearby_point(), and let the radius parameter speak about how "near" we mean. I don't understand morse_potential_func(). I'm looking for the well depth D_e. Apparently we assume it is unity? Or maybe this is normalized_morse_potential()? Add a """docstring""" or maybe a # comment.
{ "domain": "codereview.stackexchange", "id": 44821, "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, simulation, physics", "url": null }
python, simulation, physics In lj_energy_func(), computing (σ ** 6 / r ** 6) seems slightly less convenient than computing (σ / r) ** 6. If there is some numeric analysis consideration going on here, please document it. It's a perfectly good identifier, but you must spell it out in the docstring: def lj_energy(r: float) -> float: """Returns the Lennard-Jones potential.""" For harmonic energy and the other two potential functions, I am concerned that caller might accidentally violate assumptions and then rely on an incorrect computed value. For example if you expect a non-negative radius, spell that out explicitly, either with assert r >= 0, r or if r < 0: raise ValueError(f"got a negative radius: {r}") I am especially concerned that you might expect the radius shall not exceed the periodic boundary. So you might want two checks. In square_well_func you kind of lost me. en += 10000000 As a kindness to the Reader, let's help with counting those zeros: en += 10_000_000 Ok, on to the substantive item. What does that even mean? 10 MJ? Where did it come from? This is a classic magic number. You need to name it, and it would be really helpful to cite some reference both for this and for the -1 quantity. Simplest way to name it is to stick it in the signature: def square_well(r: float, mystery_energy=10_000_000) -> float: I was expecting to see some mention of Planck's constant, and the particle mass, but I didn't notice them. In get_potential(), this appears to be the Wrong comment: if index_int >= 1: # 1....8
{ "domain": "codereview.stackexchange", "id": 44821, "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, simulation, physics", "url": null }
python, simulation, physics In get_potential(), this appears to be the Wrong comment: if index_int >= 1: # 1....8 I mean, sure, it's probably numerically true ATM. But you wanted to phrase that in terms of N, I believe. (Plus, we should find a better name, perhaps N_ATOMS.) It appears to me that get_potential() is where the action is. You've been building up primitives and here you combine them all together. So it is absolutely criminal that you chose to not write at least a one-sentence """docstring""" for this function. Tell me what I get, and how to interpret it. Cite the occasional reference. What assumptions have we made here? In get_total_potential() we see bead_i_plus_1 = polymer_chain_vec[i + 1] Arrgh! Don't do that. We don't write comments like i += 1 # Increments the integer index so it is exactly 1 bigger. and we don't invent identifiers like bead_i_plus_1. Call it next_bead and leave it at that. It's a local variable, so the Reader can easily locate the assignment to find the details. Later we see pair_float += morse_potential_func(r_float) which is just wrong. It's not a pair. Call it pair_potential or pair_energy or even just energy since it's summed across many pairs. Say what you mean and mean what you say. Looking at def run_simulation(), it appears we could move the temperature global into the signature as a keyword default arg. It would be less trouble than turning all these functions into class methods. The if __name__ guard is very nice. There's just eight lines of code, so it's not too long yet. But still, it would be worthwhile to push those eight lines into a def main(): function, so that some variables could become local variables, which go out of scope when the function exits. Plus it definitely needs to be longer than eight lines. What result am I looking at? Give the chart a title. What do the X and Y axes depict? Give them labels, which include either SI units or "ångström" as applicable).
{ "domain": "codereview.stackexchange", "id": 44821, "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, simulation, physics", "url": null }
python, simulation, physics I inspect particle positions in this way: import numpy as np import pandas as pd import seaborn as sns pos = np.array(polymer_chain_vec) df = pd.DataFrame(pos, columns=['x', 'y']) sns.scatterplot(x=df.x, y=df.y) plt.show() I guess the potentials are influencing where the particles wind up? But it's hard to see, looks pretty random. I would like to see some verifiable assertions made about the resulting polymer, maybe claims about what the distribution of nearest neighbor distances should look like. Consider adopting optional type annotation, and linting with mypy. This code appears to achieve its design goals. Certainly it computes a result without crashing. It_word is_word hard_word to_word read_word. Some rename refactors could quickly remedy that. I would not be willing to maintain this code in its current form.
{ "domain": "codereview.stackexchange", "id": 44821, "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, simulation, physics", "url": null }
android, database Title: Storing icons in Room Database Question: I want to store some 512x512 icons for my Android app in a Room database. This is so each item in a list can have all the text data along with the image data stored in a single record. The answers to this question https://stackoverflow.com/questions/46337519/how-insert-image-in-room-persistence-library indicate this is not a good practice, however the images I'm saving aren't even 1 kilobyte. Under these circumstances would it be acceptable to store images in a database like this? I want the database to come preloaded with certain default list items, but the users will also be able to add their own items with custom icons. Given that this is the case it may be better to just store URIs in the database but I would like some insight on this. Answer: would it be acceptable to store images in a database like this?
{ "domain": "codereview.stackexchange", "id": 44822, "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": "android, database", "url": null }
android, database Answer: would it be acceptable to store images in a database like this? Yes, of course. The standard advice about "keep pixels out of the DB, just store image file pathnames" is all about playing to the DB's strengths, and making sensible use of cache memory. It sounds like you have maybe 1000 bytes of image and 100 bytes of text for each item, a 10:1 ratio, and when you need one you always need the other. So sure, put both in a single row. When would we not do that? Well perhaps you frequently tablescan looking for text matches, and for the < 1% matching rows you display the corresponding image. In that case a columnstore, or segregated sqlite rowstore tables, would let you conserve 90% of cache memory, yielding better cache hit ratio and faster queries. So one narrow text table would have (id, description) while the other wider table has (id, image_blob). That lets us efficiently tablescan the text descriptions, and only bring in the handful of needed images for the matches. I/O takes time, and reading lots of big images takes lots of time. This becomes a more pressing concern when images are megabytes rather than a kilobyte. For your use case, as I understand it, when you read a description you always need the corresponding image BLOB. So there's no need for extra complexity or JOINs; a simple (id, description, image_blob) row will suffice.
{ "domain": "codereview.stackexchange", "id": 44822, "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": "android, database", "url": null }
c, linux, kernel, string-processing Title: LKM: Extract cpu model name from /proc/cpuinfo Question: I wrote a small LKM that opens the /proc/cpuinfo file, reads it line by line, and attempts to the cpu model name. If the function fails to extract the cpu model name, or for some reason it can't read the cpuinfo file, it should return "N/A". While I am aware that I can also achieve this with a user-space application, I would like to do it within the LKM. I find string processing inside a LKM quiet challenging. I appreciate any feedback. I am especially interested in the following aspects: String-Processing: Can the extraction of the cpu model name string be simplified? Edge cases: Are there any edge cases that aren't covered, that could lead to memory leaks or crashes? Below is the LKM code, and a Makefile. test.c #include <linux/init.h> #include <linux/module.h> #include <linux/printk.h> #include <linux/types.h> #include <linux/path.h> #include <linux/fs.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("test"); static int lkm_init(void); char *get_cpu_model_name(void); static void lkm_exit(void); static int lkm_init(void) { pr_info("Initializing\n"); pr_info("cpu: %s\n", get_cpu_model_name()); return 0; } char *get_cpu_model_name(void) { const char *filename = "/proc/cpuinfo"; struct file *file = filp_open(filename, O_RDONLY, 0); if (IS_ERR(file)) { return "N/A"; } // Alloc buffer char *buffer = kmalloc(PAGE_SIZE, GFP_KERNEL); if (!buffer) { filp_close(file, NULL); return "N/A"; }
{ "domain": "codereview.stackexchange", "id": 44823, "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, linux, kernel, string-processing", "url": null }
c, linux, kernel, string-processing ssize_t bytes_read; char *newline_pos; while ((bytes_read = kernel_read(file, buffer, PAGE_SIZE - 1, &file->f_pos)) > 0) { // Ensure buffer has null terminator at the end. buffer[bytes_read] = '\0'; // Process each line char *line = buffer; while ((newline_pos = strchr(line, '\n')) != NULL) { *newline_pos = '\0'; // Check if the line starts with "model name" if (strncmp(line, "model name", 10) == 0) { // Skip until ":" char *colon_pos = strchr(line, ':'); if (colon_pos != NULL) { // Skip ":" and "" colon_pos += 2; return colon_pos; } } line = newline_pos + 1; } memset(buffer, 0, PAGE_SIZE); } kfree(buffer); filp_close(file, NULL); return "N/A"; } static void lkm_exit(void) { pr_info("Unloading\n"); } module_init(lkm_init); module_exit(lkm_exit); Makefile obj-m := test.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean Compile the LKM using make, and load it with sudo insmod test.ko. Observe the output in dmesg: sudo dmesg. Afterwards, unload the LKM with sudo rmmod test. Answer: get_cpu_model_name() should define a string constant for "N/A" which can be used by both it and its consumers. There are multiple calls to filp_close() which should be handled using the goto out resource cleanup idiom.
{ "domain": "codereview.stackexchange", "id": 44823, "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, linux, kernel, string-processing", "url": null }
c, linux, kernel, string-processing It's not obvious to me that, on a multi-core machine, the text will always fit within PAGE_SIZE. Put another way, you could consider allocating a buffer that you're confident can hold more than a line of text, and then stream your way through the file with multiple reads. We might declare support for lines up to length 127, allocate three 128-byte buffers, and use the first two as read() bounce buffers while get_line() copies each line out to the third. This would force us to skip most of the rather long "flags:" line, or we could choose bigger constants if parsing that was of interest. Alternatively, perhaps there is a code assumption that should be explicitly documented: "All occurrences of 'model name' are specified to have identical content, and the first occurrence is guaranteed to appear within PAGE_SIZE of the beginning." if (strncmp(line, "model name", 10) == 0) { This is clear enough. But still, 10 is a magic number. A manifest string constant or even a simple macro would be an improvement and would DRY this up a bit. Maybe the toolchain permits compiler const expressions? // Skip ":" and "" Code defect: some comments lie, including this one. Author's intent was " " rather than "". It's not terrible that we don't verify a SPACE character at that position. But I wouldn't mind seeing that sanity check, for example by using strstr(). Also, we might verify the return value points at a non-SPACE character. Returning a truncated CPU name seems kind of OK, but returning a zero-length name would be bad. Come to think of it, maybe by bad luck the : colon appears at end of buffer, and you wrote a '\0' zero on top of the subsequent SPACE, leading to invalid return address. return colon_pos;
{ "domain": "codereview.stackexchange", "id": 44823, "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, linux, kernel, string-processing", "url": null }
c, linux, kernel, string-processing This is correct code, but it's not terrific. That is, sometimes identifiers lie, as we see here. This was a beautiful, informative, accurate identifier when we assigned strchr() to it. Here, I recommend omitting the increment and simply doing return colon_pos + 2; which is perfectly accurate. memset(buffer, 0, PAGE_SIZE); Beautiful, it resembles the 0xDEADBEEF convention. This is a nice touch, I like it. Maybe there is some style guide or another advice URL you'd like to cite for this in a // comment? It just seems like a kindness to other folks debugging their modules. I do have a concern about it, though. The crypto community has a whole DSE (dead store elimination) literature about those mean old compilers optimizing out a buffer clear like this one, see e.g. sodium_memzero(). At least in user space, it is often the case that a compiler can prove that clearing a secret password buffer has "no effect", or that code trying to read the buffer would have "undefined behavior". Changing the compiler flags can mean the difference between zeroing or not zeroing. So we maybe want a second comment here about recommended flag settings where we observed via https://godbolt.org or similar that the zeroing actually happened. In the Makefile I confess I don't know why M=$(PWD) is necessary, but I imagine it truly is. Looks good, very clear. This code achieves its design goals. I would be happy to delegate or accept maintenance tasks on this codebase. EDIT "on a multi-core machine, the text [might not] fit within PAGE_SIZE"
{ "domain": "codereview.stackexchange", "id": 44823, "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, linux, kernel, string-processing", "url": null }
c, linux, kernel, string-processing There is a spec of sorts for cpuinfo output text, such as being comprised of "x : y\n" lines. There's no real size limit on how much output it could produce. When going from a uniprocessor to dual-, quad-, 8-core machines we see that its length increases, without any fixed bound. It seems plausible to me, though not guaranteed, that uniprocessor output (first core output) would usually fit within PAGE_SIZE. I was looking to make that explicit, and also to make it clear that once we see "model name : y" we require that any subsequent mention must also say "y". If we saw e.g. "...i3-3220 CPU @ 3.30GHz" and subsequently saw "...i3-3220 CPU @ 1.00GHz" we would be sad. bounce buffers Arbitrary limits can often be designed out of an algorithm. So for example we might malloc(n) rather than declare char buf[80]. Or we might do stream processing, which I briefly described above. Arbitrarily define MAX_LINE to be 127, large enough for consumer to parse any line it is interested in. Define BUFSIZE to be some larger power of 2 such as 128. Allocate three such buffers and ask that they be aligned on cache lines, such as kmalloc() offers. (Allocate a fourth buffer, and ignore part of it, if requesting aligned allocations is inconvenient.) Consumer reads from result buffer and never from either private bounce buffer. Define get_line() which issues reads, finds next newline, and strcpy's next line into the result buffer. It's a fixed-size result buffer so long lines get truncated. Init with a BUFSIZE-byte read to fill the first bounce buffer, and set an end index to the amount read. Set current index to 0. Define a buf_num() helper that maps an index to 0 or 1. Each request to get another line will use memchr to find next \n newline in the valid portion of current buffer. If not found, issue a BUFSIZE-byte read for the alternate buffer, updating end, and scan for newline again. Possibly it's not found and we set a NO_NEWLINE flag and set newline index to end of that buffer,
{ "domain": "codereview.stackexchange", "id": 44823, "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, linux, kernel, string-processing", "url": null }